OrderController.php 16 KB

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