OrderController.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469
  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. if ($request->input('cycle') === 'reset_price' && $user->expired_at <= time()) {
  88. abort(500, '当前订阅已过期,无法购买重置包');
  89. }
  90. DB::beginTransaction();
  91. $order = new Order();
  92. $orderService = new OrderService($order);
  93. $order->user_id = $request->session()->get('id');
  94. $order->plan_id = $plan->id;
  95. $order->cycle = $request->input('cycle');
  96. $order->trade_no = Helper::guid();
  97. $order->total_amount = $plan[$request->input('cycle')];
  98. if ($request->input('coupon_code')) {
  99. $couponService = new CouponService($request->input('coupon_code'));
  100. if (!$couponService->use($order)) {
  101. DB::rollBack();
  102. abort(500, '优惠券使用失败');
  103. }
  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.paytaro_enable')) {
  197. abort(500, '支付方式不可用');
  198. }
  199. return response([
  200. 'type' => 1,
  201. 'data' => $this->payTaro($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. default:
  212. abort(500, '支付方式不存在');
  213. }
  214. }
  215. public function check(Request $request)
  216. {
  217. $tradeNo = $request->input('trade_no');
  218. $order = Order::where('trade_no', $tradeNo)
  219. ->where('user_id', $request->session()->get('id'))
  220. ->first();
  221. if (!$order) {
  222. abort(500, '订单不存在');
  223. }
  224. return response([
  225. 'data' => $order->status
  226. ]);
  227. }
  228. public function getPaymentMethod()
  229. {
  230. $data = [];
  231. if ((int)config('v2board.alipay_enable')) {
  232. $alipayF2F = new \StdClass();
  233. $alipayF2F->name = '支付宝';
  234. $alipayF2F->method = 0;
  235. $alipayF2F->icon = 'alipay';
  236. array_push($data, $alipayF2F);
  237. }
  238. if ((int)config('v2board.stripe_alipay_enable')) {
  239. $stripeAlipay = new \StdClass();
  240. $stripeAlipay->name = '支付宝';
  241. $stripeAlipay->method = 2;
  242. $stripeAlipay->icon = 'alipay';
  243. array_push($data, $stripeAlipay);
  244. }
  245. if ((int)config('v2board.stripe_wepay_enable')) {
  246. $stripeWepay = new \StdClass();
  247. $stripeWepay->name = '微信';
  248. $stripeWepay->method = 3;
  249. $stripeWepay->icon = 'wechat';
  250. array_push($data, $stripeWepay);
  251. }
  252. if ((int)config('v2board.bitpayx_enable')) {
  253. $bitpayX = new \StdClass();
  254. $bitpayX->name = config('v2board.bitpayx_name', '在线支付');
  255. $bitpayX->method = 4;
  256. $bitpayX->icon = 'wallet';
  257. array_push($data, $bitpayX);
  258. }
  259. if ((int)config('v2board.paytaro_enable')) {
  260. $obj = new \StdClass();
  261. $obj->name = config('v2board.paytaro_name', '在线支付');
  262. $obj->method = 5;
  263. $obj->icon = 'wallet';
  264. array_push($data, $obj);
  265. }
  266. if ((int)config('v2board.stripe_card_enable')) {
  267. $obj = new \StdClass();
  268. $obj->name = '信用卡';
  269. $obj->method = 6;
  270. $obj->icon = 'card';
  271. array_push($data, $obj);
  272. }
  273. return response([
  274. 'data' => $data
  275. ]);
  276. }
  277. public function cancel(Request $request)
  278. {
  279. if (empty($request->input('trade_no'))) {
  280. abort(500, '参数有误');
  281. }
  282. $order = Order::where('trade_no', $request->input('trade_no'))
  283. ->where('user_id', $request->session()->get('id'))
  284. ->first();
  285. if (!$order) {
  286. abort(500, '订单不存在');
  287. }
  288. if ($order->status !== 0) {
  289. abort(500, '只可以取消待支付订单');
  290. }
  291. $orderService = new OrderService($order);
  292. if (!$orderService->cancel()) {
  293. abort(500, '取消失败');
  294. }
  295. return response([
  296. 'data' => true
  297. ]);
  298. }
  299. private function alipayF2F($tradeNo, $totalAmount)
  300. {
  301. $gateway = Omnipay::create('Alipay_AopF2F');
  302. $gateway->setSignType('RSA2'); //RSA/RSA2
  303. $gateway->setAppId(config('v2board.alipay_appid'));
  304. $gateway->setPrivateKey(config('v2board.alipay_privkey')); // 可以是路径,也可以是密钥内容
  305. $gateway->setAlipayPublicKey(config('v2board.alipay_pubkey')); // 可以是路径,也可以是密钥内容
  306. $gateway->setNotifyUrl(url('/api/v1/guest/order/alipayNotify'));
  307. $request = $gateway->purchase();
  308. $request->setBizContent([
  309. 'subject' => config('v2board.app_name', 'V2Board') . ' - 订阅',
  310. 'out_trade_no' => $tradeNo,
  311. 'total_amount' => $totalAmount / 100
  312. ]);
  313. /** @var \Omnipay\Alipay\Responses\AopTradePreCreateResponse $response */
  314. $response = $request->send();
  315. $result = $response->getAlipayResponse();
  316. if ($result['code'] !== '10000') {
  317. abort(500, $result['sub_msg']);
  318. }
  319. // 获取收款二维码内容
  320. return $response->getQrCode();
  321. }
  322. private function stripeAlipay($order)
  323. {
  324. $currency = config('v2board.stripe_currency', 'hkd');
  325. $exchange = Helper::exchange('CNY', strtoupper($currency));
  326. if (!$exchange) {
  327. abort(500, '货币转换超时,请稍后再试');
  328. }
  329. Stripe::setApiKey(config('v2board.stripe_sk_live'));
  330. $source = Source::create([
  331. 'amount' => floor($order->total_amount * $exchange),
  332. 'currency' => $currency,
  333. 'type' => 'alipay',
  334. 'statement_descriptor' => $order->trade_no,
  335. 'metadata' => [
  336. 'user_id' => $order->user_id,
  337. 'out_trade_no' => $order->trade_no,
  338. 'identifier' => ''
  339. ],
  340. 'redirect' => [
  341. 'return_url' => config('v2board.app_url', env('APP_URL')) . '/#/order'
  342. ]
  343. ]);
  344. if (!$source['redirect']['url']) {
  345. abort(500, '支付网关请求失败');
  346. }
  347. return $source['redirect']['url'];
  348. }
  349. private function stripeWepay($order)
  350. {
  351. $currency = config('v2board.stripe_currency', 'hkd');
  352. $exchange = Helper::exchange('CNY', strtoupper($currency));
  353. if (!$exchange) {
  354. abort(500, '货币转换超时,请稍后再试');
  355. }
  356. Stripe::setApiKey(config('v2board.stripe_sk_live'));
  357. $source = Source::create([
  358. 'amount' => floor($order->total_amount * $exchange),
  359. 'currency' => $currency,
  360. 'type' => 'wechat',
  361. 'metadata' => [
  362. 'user_id' => $order->user_id,
  363. 'out_trade_no' => $order->trade_no,
  364. 'identifier' => ''
  365. ],
  366. 'redirect' => [
  367. 'return_url' => config('v2board.app_url', env('APP_URL')) . '/#/order'
  368. ]
  369. ]);
  370. if (!$source['wechat']['qr_code_url']) {
  371. abort(500, '支付网关请求失败');
  372. }
  373. return $source['wechat']['qr_code_url'];
  374. }
  375. private function stripeCard($order, string $token)
  376. {
  377. $currency = config('v2board.stripe_currency', 'hkd');
  378. $exchange = Helper::exchange('CNY', strtoupper($currency));
  379. if (!$exchange) {
  380. abort(500, '货币转换超时,请稍后再试');
  381. }
  382. Stripe::setApiKey(config('v2board.stripe_sk_live'));
  383. try {
  384. $charge = \Stripe\Charge::create([
  385. 'amount' => floor($order->total_amount * $exchange),
  386. 'currency' => $currency,
  387. 'source' => $token,
  388. 'metadata' => [
  389. 'user_id' => $order->user_id,
  390. 'out_trade_no' => $order->trade_no,
  391. 'identifier' => ''
  392. ]
  393. ]);
  394. } catch (\Exception $e) {
  395. abort(500, '遇到了点问题,请刷新页面稍后再试');
  396. }
  397. info($charge);
  398. if (!$charge->paid) {
  399. abort(500, '扣款失败,请检查信用卡信息');
  400. }
  401. return $charge->paid;
  402. }
  403. private function bitpayX($order)
  404. {
  405. $bitpayX = new BitpayX(config('v2board.bitpayx_appsecret'));
  406. $params = [
  407. 'merchant_order_id' => $order->trade_no,
  408. 'price_amount' => $order->total_amount / 100,
  409. 'price_currency' => 'CNY',
  410. 'title' => '支付单号:' . $order->trade_no,
  411. 'description' => '充值:' . $order->total_amount / 100 . ' 元',
  412. 'callback_url' => url('/api/v1/guest/order/bitpayXNotify'),
  413. 'success_url' => config('v2board.app_url', env('APP_URL')) . '/#/order',
  414. 'cancel_url' => config('v2board.app_url', env('APP_URL')) . '/#/order'
  415. ];
  416. $strToSign = $bitpayX->prepareSignId($params['merchant_order_id']);
  417. $params['token'] = $bitpayX->sign($strToSign);
  418. $result = $bitpayX->mprequest($params);
  419. // Log::info('bitpayXSubmit: ' . json_encode($result));
  420. return isset($result['payment_url']) ? $result['payment_url'] : false;
  421. }
  422. private function payTaro($order)
  423. {
  424. $payTaro = new PayTaro(config('v2board.paytaro_app_id'), config('v2board.paytaro_app_secret'));
  425. $result = $payTaro->pay([
  426. 'app_id' => config('v2board.paytaro_app_id'),
  427. 'out_trade_no' => $order->trade_no,
  428. 'total_amount' => $order->total_amount,
  429. 'notify_url' => url('/api/v1/guest/order/payTaroNotify'),
  430. 'return_url' => config('v2board.app_url', env('APP_URL')) . '/#/order'
  431. ]);
  432. return $result;
  433. }
  434. }