OrderController.php 17 KB

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