OrderController.php 17 KB

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