OrderController.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467
  1. <?php
  2. namespace App\Http\Controllers\User;
  3. use App\Http\Controllers\Controller;
  4. use App\Http\Requests\User\OrderSave;
  5. use Illuminate\Http\Request;
  6. use Illuminate\Support\Facades\Cache;
  7. use Illuminate\Support\Facades\Log;
  8. use Illuminate\Support\Facades\DB;
  9. use App\Models\Order;
  10. use App\Models\Plan;
  11. use App\Models\User;
  12. use App\Models\Coupon;
  13. use App\Utils\Helper;
  14. use Omnipay\Omnipay;
  15. use Stripe\Stripe;
  16. use Stripe\Source;
  17. use Library\BitpayX;
  18. use Library\PayTaro;
  19. class OrderController extends Controller
  20. {
  21. public function fetch(Request $request)
  22. {
  23. $model = Order::where('user_id', $request->session()->get('id'))
  24. ->orderBy('created_at', 'DESC');
  25. if ($request->input('status') !== null) {
  26. $model->where('status', $request->input('status'));
  27. }
  28. $order = $model->get();
  29. $plan = Plan::get();
  30. for ($i = 0; $i < count($order); $i++) {
  31. for ($x = 0; $x < count($plan); $x++) {
  32. if ($order[$i]['plan_id'] === $plan[$x]['id']) {
  33. $order[$i]['plan'] = $plan[$x];
  34. }
  35. }
  36. }
  37. return response([
  38. 'data' => $order
  39. ]);
  40. }
  41. public function details(Request $request)
  42. {
  43. $order = Order::where('user_id', $request->session()->get('id'))
  44. ->where('trade_no', $request->input('trade_no'))
  45. ->first();
  46. if (!$order) {
  47. abort(500, '订单不存在');
  48. }
  49. $order['plan'] = Plan::find($order->plan_id);
  50. $order['try_out_plan_id'] = (int)config('v2board.try_out_plan_id');
  51. if (!$order['plan']) {
  52. abort(500, '订阅不存在');
  53. }
  54. return response([
  55. 'data' => $order
  56. ]);
  57. }
  58. private function isNotCompleteOrderByUserId($userId)
  59. {
  60. $order = Order::whereIn('status', [0, 1])
  61. ->where('user_id', $userId)
  62. ->first();
  63. if (!$order) {
  64. return false;
  65. }
  66. return true;
  67. }
  68. // surplus value
  69. private function getSurplusValue(User $user)
  70. {
  71. $plan = Plan::find($user->plan_id);
  72. $dayPrice = 0;
  73. if ($plan->month_price) {
  74. $dayPrice = $plan->month_price / 2592000;
  75. } else if ($plan->quarter_price) {
  76. $dayPrice = $plan->quarter_price / 7862400;
  77. } else if ($plan->half_year_price) {
  78. $dayPrice = $plan->half_year_price / 15811200;
  79. } else if ($plan->year_price) {
  80. $dayPrice = $plan->year_price / 31536000;
  81. }
  82. // exclude discount
  83. if ($user->discount) {
  84. $dayPrice = $dayPrice * $user->discount / 100;
  85. }
  86. $remainingDay = $user->expired_at - time();
  87. return $remainingDay * $dayPrice;
  88. }
  89. public function save(OrderSave $request)
  90. {
  91. if ($this->isNotCompleteOrderByUserId($request->session()->get('id'))) {
  92. abort(500, '存在未付款订单,请取消后再试');
  93. }
  94. $plan = Plan::find($request->input('plan_id'));
  95. $user = User::find($request->session()->get('id'));
  96. if (!$plan) {
  97. abort(500, '该订阅不存在');
  98. }
  99. if ((!$plan->show && !$plan->renew) || (!$plan->show && $user->plan_id !== $plan->id)) {
  100. abort(500, '该订阅已售罄');
  101. }
  102. if (!$plan->renew && $user->plan_id == $plan->id) {
  103. abort(500, '该订阅无法续费,请更换其他订阅');
  104. }
  105. if ($plan[$request->input('cycle')] === NULL) {
  106. abort(500, '该订阅周期无法进行购买,请选择其他周期');
  107. }
  108. if ($request->input('coupon_code')) {
  109. $coupon = Coupon::where('code', $request->input('coupon_code'))->first();
  110. if (!$coupon) {
  111. abort(500, '优惠券无效');
  112. }
  113. if ($coupon->limit_use <= 0 && $coupon->limit_use !== NULL) {
  114. abort(500, '优惠券已无可用次数');
  115. }
  116. if (time() < $coupon->started_at) {
  117. abort(500, '优惠券还未到可用时间');
  118. }
  119. if (time() > $coupon->ended_at) {
  120. abort(500, '优惠券已过期');
  121. }
  122. }
  123. DB::beginTransaction();
  124. $order = new Order();
  125. $order->user_id = $request->session()->get('id');
  126. $order->plan_id = $plan->id;
  127. $order->cycle = $request->input('cycle');
  128. $order->trade_no = Helper::guid();
  129. $order->total_amount = $plan[$request->input('cycle')];
  130. // discount start
  131. // coupon
  132. if (isset($coupon)) {
  133. switch ($coupon->type) {
  134. case 1:
  135. $order->discount_amount = $coupon->value;
  136. break;
  137. case 2:
  138. $order->discount_amount = $order->total_amount * ($coupon->value / 100);
  139. break;
  140. }
  141. if ($coupon->limit_use !== NULL) {
  142. $coupon->limit_use = $coupon->limit_use - 1;
  143. if (!$coupon->save()) {
  144. DB::rollback();
  145. abort(500, '优惠券使用失败');
  146. }
  147. }
  148. }
  149. // user
  150. if ($user->discount) {
  151. $order->discount_amount = $order->discount_amount + ($order->total_amount * ($user->discount / 100));
  152. }
  153. // discount complete
  154. $order->total_amount = $order->total_amount - $order->discount_amount;
  155. // discount end
  156. // renew and change subscribe process
  157. if ($user->expired_at > time() && $order->plan_id !== $user->plan_id) {
  158. if (!(int)config('v2board.plan_change_enable', 1)) abort(500, '目前不允许更改订阅,请联系管理员');
  159. $order->type = 3;
  160. $order->surplus_amount = $this->getSurplusValue($user);
  161. if ($order->surplus_amount >= $order->total_amount) {
  162. $order->refund_amount = $order->surplus_amount - $order->total_amount;
  163. $order->total_amount = 0;
  164. } else {
  165. $order->total_amount = $order->total_amount - $order->surplus_amount;
  166. }
  167. } else if ($user->expired_at > time() && $order->plan_id == $user->plan_id) {
  168. $order->type = 2;
  169. } else {
  170. $order->type = 1;
  171. }
  172. // invite process
  173. if ($user->invite_user_id && $order->total_amount > 0) {
  174. $order->invite_user_id = $user->invite_user_id;
  175. $inviter = User::find($user->invite_user_id);
  176. if ($inviter && $inviter->commission_rate) {
  177. $order->commission_balance = $order->total_amount * ($inviter->commission_rate / 100);
  178. } else {
  179. $order->commission_balance = $order->total_amount * (config('v2board.invite_commission', 10) / 100);
  180. }
  181. }
  182. if (!$order->save()) {
  183. DB::rollback();
  184. abort(500, '订单创建失败');
  185. }
  186. DB::commit();
  187. return response([
  188. 'data' => $order->trade_no
  189. ]);
  190. }
  191. public function checkout(Request $request)
  192. {
  193. $tradeNo = $request->input('trade_no');
  194. $method = $request->input('method');
  195. $order = Order::where('trade_no', $tradeNo)
  196. ->where('user_id', $request->session()->get('id'))
  197. ->where('status', 0)
  198. ->first();
  199. if (!$order) {
  200. abort(500, '订单不存在或已支付');
  201. }
  202. // free process
  203. if ($order->total_amount <= 0) {
  204. $order->total_amount = 0;
  205. $order->status = 1;
  206. $order->save();
  207. exit();
  208. }
  209. switch ($method) {
  210. // return type => 0: QRCode / 1: URL
  211. case 0:
  212. // alipayF2F
  213. if (!(int)config('v2board.alipay_enable')) {
  214. abort(500, '支付方式不可用');
  215. }
  216. return response([
  217. 'type' => 0,
  218. 'data' => $this->alipayF2F($tradeNo, $order->total_amount)
  219. ]);
  220. case 2:
  221. // stripeAlipay
  222. if (!(int)config('v2board.stripe_alipay_enable')) {
  223. abort(500, '支付方式不可用');
  224. }
  225. return response([
  226. 'type' => 1,
  227. 'data' => $this->stripeAlipay($order)
  228. ]);
  229. case 3:
  230. // stripeWepay
  231. if (!(int)config('v2board.stripe_wepay_enable')) {
  232. abort(500, '支付方式不可用');
  233. }
  234. return response([
  235. 'type' => 0,
  236. 'data' => $this->stripeWepay($order)
  237. ]);
  238. case 4:
  239. // bitpayX
  240. if (!(int)config('v2board.bitpayx_enable')) {
  241. abort(500, '支付方式不可用');
  242. }
  243. return response([
  244. 'type' => 1,
  245. 'data' => $this->bitpayX($order)
  246. ]);
  247. case 5:
  248. if (!(int)config('v2board.paytaro_enable')) {
  249. abort(500, '支付方式不可用');
  250. }
  251. return response([
  252. 'type' => 1,
  253. 'data' => $this->payTaro($order)
  254. ]);
  255. default:
  256. abort(500, '支付方式不存在');
  257. }
  258. }
  259. public function check(Request $request)
  260. {
  261. $tradeNo = $request->input('trade_no');
  262. $order = Order::where('trade_no', $tradeNo)
  263. ->where('user_id', $request->session()->get('id'))
  264. ->first();
  265. if (!$order) {
  266. abort(500, '订单不存在');
  267. }
  268. return response([
  269. 'data' => $order->status
  270. ]);
  271. }
  272. public function getPaymentMethod()
  273. {
  274. $data = [];
  275. if ((int)config('v2board.alipay_enable')) {
  276. $alipayF2F = new \StdClass();
  277. $alipayF2F->name = '支付宝';
  278. $alipayF2F->method = 0;
  279. $alipayF2F->icon = 'alipay';
  280. array_push($data, $alipayF2F);
  281. }
  282. if ((int)config('v2board.stripe_alipay_enable')) {
  283. $stripeAlipay = new \StdClass();
  284. $stripeAlipay->name = '支付宝';
  285. $stripeAlipay->method = 2;
  286. $stripeAlipay->icon = 'alipay';
  287. array_push($data, $stripeAlipay);
  288. }
  289. if ((int)config('v2board.stripe_wepay_enable')) {
  290. $stripeWepay = new \StdClass();
  291. $stripeWepay->name = '微信';
  292. $stripeWepay->method = 3;
  293. $stripeWepay->icon = 'wechat';
  294. array_push($data, $stripeWepay);
  295. }
  296. if ((int)config('v2board.bitpayx_enable')) {
  297. $bitpayX = new \StdClass();
  298. $bitpayX->name = '聚合支付';
  299. $bitpayX->method = 4;
  300. $bitpayX->icon = 'wallet';
  301. array_push($data, $bitpayX);
  302. }
  303. if ((int)config('v2board.paytaro_enable')) {
  304. $obj = new \StdClass();
  305. $obj->name = '聚合支付';
  306. $obj->method = 5;
  307. $obj->icon = 'wallet';
  308. array_push($data, $obj);
  309. }
  310. return response([
  311. 'data' => $data
  312. ]);
  313. }
  314. public function cancel(Request $request)
  315. {
  316. if (empty($request->input('trade_no'))) {
  317. abort(500, '参数有误');
  318. }
  319. $order = Order::where('trade_no', $request->input('trade_no'))
  320. ->where('user_id', $request->session()->get('id'))
  321. ->first();
  322. if (!$order) {
  323. abort(500, '订单不存在');
  324. }
  325. if ($order->status !== 0) {
  326. abort(500, '只可以取消待支付订单');
  327. }
  328. $order->status = 2;
  329. if (!$order->save()) {
  330. abort(500, '取消失败');
  331. }
  332. return response([
  333. 'data' => true
  334. ]);
  335. }
  336. private function alipayF2F($tradeNo, $totalAmount)
  337. {
  338. $gateway = Omnipay::create('Alipay_AopF2F');
  339. $gateway->setSignType('RSA2'); //RSA/RSA2
  340. $gateway->setAppId(config('v2board.alipay_appid'));
  341. $gateway->setPrivateKey(config('v2board.alipay_privkey')); // 可以是路径,也可以是密钥内容
  342. $gateway->setAlipayPublicKey(config('v2board.alipay_pubkey')); // 可以是路径,也可以是密钥内容
  343. $gateway->setNotifyUrl(url('/api/v1/guest/order/alipayNotify'));
  344. $request = $gateway->purchase();
  345. $request->setBizContent([
  346. 'subject' => config('v2board.app_name', 'V2Board') . ' - 订阅',
  347. 'out_trade_no' => $tradeNo,
  348. 'total_amount' => $totalAmount / 100
  349. ]);
  350. /** @var \Omnipay\Alipay\Responses\AopTradePreCreateResponse $response */
  351. $response = $request->send();
  352. $result = $response->getAlipayResponse();
  353. if ($result['code'] !== '10000') {
  354. abort(500, $result['sub_msg']);
  355. }
  356. // 获取收款二维码内容
  357. return $response->getQrCode();
  358. }
  359. private function stripeAlipay($order)
  360. {
  361. $exchange = Helper::exchange('CNY', 'HKD');
  362. if (!$exchange) {
  363. abort(500, '货币转换超时,请稍后再试');
  364. }
  365. Stripe::setApiKey(config('v2board.stripe_sk_live'));
  366. $source = Source::create([
  367. 'amount' => floor($order->total_amount * $exchange),
  368. 'currency' => 'hkd',
  369. 'type' => 'alipay',
  370. 'redirect' => [
  371. 'return_url' => config('v2board.app_url', env('APP_URL')) . '/#/order'
  372. ]
  373. ]);
  374. if (!$source['redirect']['url']) {
  375. abort(500, '支付网关请求失败');
  376. }
  377. if (!Cache::put($source['id'], $order->trade_no, 3600)) {
  378. abort(500, '订单创建失败');
  379. }
  380. return $source['redirect']['url'];
  381. }
  382. private function stripeWepay($order)
  383. {
  384. $exchange = Helper::exchange('CNY', 'HKD');
  385. if (!$exchange) {
  386. abort(500, '货币转换超时,请稍后再试');
  387. }
  388. Stripe::setApiKey(config('v2board.stripe_sk_live'));
  389. $source = Source::create([
  390. 'amount' => floor($order->total_amount * $exchange),
  391. 'currency' => 'hkd',
  392. 'type' => 'wechat',
  393. 'redirect' => [
  394. 'return_url' => config('v2board.app_url', env('APP_URL')) . '/#/order'
  395. ]
  396. ]);
  397. if (!$source['wechat']['qr_code_url']) {
  398. abort(500, '支付网关请求失败');
  399. }
  400. if (!Cache::put($source['id'], $order->trade_no, 3600)) {
  401. abort(500, '订单创建失败');
  402. }
  403. return $source['wechat']['qr_code_url'];
  404. }
  405. private function bitpayX($order)
  406. {
  407. $bitpayX = new BitpayX(config('v2board.bitpayx_appsecret'));
  408. $params = [
  409. 'merchant_order_id' => $order->trade_no,
  410. 'price_amount' => $order->total_amount / 100,
  411. 'price_currency' => 'CNY',
  412. 'title' => '支付单号:' . $order->trade_no,
  413. 'description' => '充值:' . $order->total_amount / 100 . ' 元',
  414. 'callback_url' => url('/api/v1/guest/order/bitpayXNotify'),
  415. 'success_url' => config('v2board.app_url', env('APP_URL')) . '/#/order',
  416. 'cancel_url' => config('v2board.app_url', env('APP_URL')) . '/#/order'
  417. ];
  418. $strToSign = $bitpayX->prepareSignId($params['merchant_order_id']);
  419. $params['token'] = $bitpayX->sign($strToSign);
  420. $result = $bitpayX->mprequest($params);
  421. Log::info('bitpayXSubmit: ' . json_encode($result));
  422. return isset($result['payment_url']) ? $result['payment_url'] : false;
  423. }
  424. private function payTaro($order)
  425. {
  426. $payTaro = new PayTaro(config('v2board.paytaro_app_id'), config('v2board.paytaro_app_secret'));
  427. $result = $payTaro->pay([
  428. 'app_id' => config('v2board.paytaro_app_id'),
  429. 'out_trade_no' => $order->trade_no,
  430. 'total_amount' => $order->total_amount,
  431. 'notify_url' => url('/api/v1/guest/order/payTaroNotify'),
  432. 'return_url' => config('v2board.app_url', env('APP_URL')) . '/#/order'
  433. ]);
  434. return $result;
  435. }
  436. }