OrderController.php 17 KB

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