OrderController.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527
  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\OrderService;
  6. use App\Services\UserService;
  7. use Illuminate\Http\Request;
  8. use Illuminate\Support\Facades\Cache;
  9. use Illuminate\Support\Facades\Log;
  10. use Illuminate\Support\Facades\DB;
  11. use App\Models\Order;
  12. use App\Models\Plan;
  13. use App\Models\User;
  14. use App\Models\Coupon;
  15. use App\Utils\Helper;
  16. use Omnipay\Omnipay;
  17. use Stripe\Stripe;
  18. use Stripe\Source;
  19. use Library\BitpayX;
  20. use Library\PayTaro;
  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. private function isNotCompleteOrderByUserId($userId)
  61. {
  62. $order = Order::whereIn('status', [0, 1])
  63. ->where('user_id', $userId)
  64. ->first();
  65. if (!$order) {
  66. return false;
  67. }
  68. return true;
  69. }
  70. // surplus value
  71. private function getSurplusValue(User $user)
  72. {
  73. $plan = Plan::find($user->plan_id);
  74. if ($user->expired_at === NULL) {
  75. return $this->getSurplusValueByOneTime($user, $plan);
  76. } else {
  77. return $this->getSurplusValueByCycle($user, $plan);
  78. }
  79. }
  80. private function getSurplusValueByOneTime(User $user, Plan $plan)
  81. {
  82. $trafficUnitPrice = 0;
  83. $trafficUnitPrice = $plan->onetime_price / $plan->transfer_enable;
  84. if ($user->discount && $trafficUnitPrice) {
  85. $trafficUnitPrice = $trafficUnitPrice - ($trafficUnitPrice * $user->discount / 100);
  86. }
  87. $notUsedTrafficPrice = $plan->transfer_enable - (($user->u + $user->d) / 1073741824);
  88. $result = $trafficUnitPrice * $notUsedTrafficPrice;
  89. return $result > 0 ? $result : 0;
  90. }
  91. private function getSurplusValueByCycle(User $user, Plan $plan)
  92. {
  93. $dayPrice = 0;
  94. $day = ($user->expired_at - time()) / 86400;
  95. if ($plan->month_price) {
  96. $dayPrice = $plan->month_price / $day;
  97. } else if ($plan->quarter_price) {
  98. $dayPrice = $plan->quarter_price / $day;
  99. } else if ($plan->half_year_price) {
  100. $dayPrice = $plan->half_year_price / $day;
  101. } else if ($plan->year_price) {
  102. $dayPrice = $plan->year_price / $day;
  103. }
  104. // exclude discount
  105. if ($user->discount && $dayPrice) {
  106. $dayPrice = $dayPrice - ($dayPrice * $user->discount / 100);
  107. }
  108. $result = $day * $dayPrice;
  109. return $result > 0 ? $result : 0;
  110. }
  111. public function save(OrderSave $request)
  112. {
  113. if ($this->isNotCompleteOrderByUserId($request->session()->get('id'))) {
  114. abort(500, '存在未付款订单,请取消后再试');
  115. }
  116. $plan = Plan::find($request->input('plan_id'));
  117. $user = User::find($request->session()->get('id'));
  118. if (!$plan) {
  119. abort(500, '该订阅不存在');
  120. }
  121. if ((!$plan->show && !$plan->renew) || (!$plan->show && $user->plan_id !== $plan->id)) {
  122. abort(500, '该订阅已售罄');
  123. }
  124. if (!$plan->renew && $user->plan_id == $plan->id) {
  125. abort(500, '该订阅无法续费,请更换其他订阅');
  126. }
  127. if ($plan[$request->input('cycle')] === NULL) {
  128. abort(500, '该订阅周期无法进行购买,请选择其他周期');
  129. }
  130. if ($request->input('coupon_code')) {
  131. $coupon = Coupon::where('code', $request->input('coupon_code'))->first();
  132. if (!$coupon) {
  133. abort(500, '优惠券无效');
  134. }
  135. if ($coupon->limit_use <= 0 && $coupon->limit_use !== NULL) {
  136. abort(500, '优惠券已无可用次数');
  137. }
  138. if (time() < $coupon->started_at) {
  139. abort(500, '优惠券还未到可用时间');
  140. }
  141. if (time() > $coupon->ended_at) {
  142. abort(500, '优惠券已过期');
  143. }
  144. }
  145. DB::beginTransaction();
  146. $order = new Order();
  147. $order->user_id = $request->session()->get('id');
  148. $order->plan_id = $plan->id;
  149. $order->cycle = $request->input('cycle');
  150. $order->trade_no = Helper::guid();
  151. $order->total_amount = $plan[$request->input('cycle')];
  152. // coupon start
  153. if (isset($coupon)) {
  154. switch ($coupon->type) {
  155. case 1:
  156. $order->discount_amount = $coupon->value;
  157. break;
  158. case 2:
  159. $order->discount_amount = $order->total_amount * ($coupon->value / 100);
  160. break;
  161. }
  162. if ($coupon->limit_use !== NULL) {
  163. $coupon->limit_use = $coupon->limit_use - 1;
  164. if (!$coupon->save()) {
  165. DB::rollback();
  166. abort(500, '优惠券使用失败');
  167. }
  168. }
  169. }
  170. // coupon complete
  171. // discount start
  172. if ($user->discount) {
  173. $order->discount_amount = $order->discount_amount + ($order->total_amount * ($user->discount / 100));
  174. }
  175. // discount end
  176. $order->total_amount = $order->total_amount - $order->discount_amount;
  177. // renew and change subscribe process
  178. if ($user->plan_id !== NULL && $order->plan_id !== $user->plan_id) {
  179. if (!(int)config('v2board.plan_change_enable', 1)) abort(500, '目前不允许更改订阅,请联系客服或提交工单');
  180. $order->type = 3;
  181. $order->surplus_amount = $this->getSurplusValue($user);
  182. if ($order->surplus_amount >= $order->total_amount) {
  183. $order->refund_amount = $order->surplus_amount - $order->total_amount;
  184. $order->total_amount = 0;
  185. } else {
  186. $order->total_amount = $order->total_amount - $order->surplus_amount;
  187. }
  188. } else if ($user->expired_at > time() && $order->plan_id == $user->plan_id) {
  189. $order->type = 2;
  190. } else {
  191. $order->type = 1;
  192. }
  193. // invite process
  194. if ($user->invite_user_id && $order->total_amount > 0) {
  195. $order->invite_user_id = $user->invite_user_id;
  196. $commissionFirstTime = (int)config('v2board.commission_first_time_enable', 1);
  197. if (!$commissionFirstTime || ($commissionFirstTime && !Order::where('user_id', $user->id)->where('status', 3)->first())) {
  198. $inviter = User::find($user->invite_user_id);
  199. if ($inviter && $inviter->commission_rate) {
  200. $order->commission_balance = $order->total_amount * ($inviter->commission_rate / 100);
  201. } else {
  202. $order->commission_balance = $order->total_amount * (config('v2board.invite_commission', 10) / 100);
  203. }
  204. }
  205. }
  206. // use balance
  207. if ($user->balance && $order->total_amount > 0) {
  208. $remainingBalance = $user->balance - $order->total_amount;
  209. $userService = new UserService();
  210. if ($remainingBalance > 0) {
  211. if (!$userService->addBalance($order->user_id, - $order->total_amount)) {
  212. DB::rollBack();
  213. abort(500, '余额不足');
  214. }
  215. $order->balance_amount = $order->total_amount;
  216. $order->total_amount = 0;
  217. } else {
  218. if (!$userService->addBalance($order->user_id, - $user->balance)) {
  219. DB::rollBack();
  220. abort(500, '余额不足');
  221. }
  222. $order->balance_amount = $user->balance;
  223. $order->total_amount = $order->total_amount - $user->balance;
  224. }
  225. }
  226. if (!$order->save()) {
  227. DB::rollback();
  228. abort(500, '订单创建失败');
  229. }
  230. DB::commit();
  231. return response([
  232. 'data' => $order->trade_no
  233. ]);
  234. }
  235. public function checkout(Request $request)
  236. {
  237. $tradeNo = $request->input('trade_no');
  238. $method = $request->input('method');
  239. $order = Order::where('trade_no', $tradeNo)
  240. ->where('user_id', $request->session()->get('id'))
  241. ->where('status', 0)
  242. ->first();
  243. if (!$order) {
  244. abort(500, '订单不存在或已支付');
  245. }
  246. // free process
  247. if ($order->total_amount <= 0) {
  248. $order->total_amount = 0;
  249. $order->status = 1;
  250. $order->save();
  251. exit();
  252. }
  253. switch ($method) {
  254. // return type => 0: QRCode / 1: URL
  255. case 0:
  256. // alipayF2F
  257. if (!(int)config('v2board.alipay_enable')) {
  258. abort(500, '支付方式不可用');
  259. }
  260. return response([
  261. 'type' => 0,
  262. 'data' => $this->alipayF2F($tradeNo, $order->total_amount)
  263. ]);
  264. case 2:
  265. // stripeAlipay
  266. if (!(int)config('v2board.stripe_alipay_enable')) {
  267. abort(500, '支付方式不可用');
  268. }
  269. return response([
  270. 'type' => 1,
  271. 'data' => $this->stripeAlipay($order)
  272. ]);
  273. case 3:
  274. // stripeWepay
  275. if (!(int)config('v2board.stripe_wepay_enable')) {
  276. abort(500, '支付方式不可用');
  277. }
  278. return response([
  279. 'type' => 0,
  280. 'data' => $this->stripeWepay($order)
  281. ]);
  282. case 4:
  283. // bitpayX
  284. if (!(int)config('v2board.bitpayx_enable')) {
  285. abort(500, '支付方式不可用');
  286. }
  287. return response([
  288. 'type' => 1,
  289. 'data' => $this->bitpayX($order)
  290. ]);
  291. case 5:
  292. if (!(int)config('v2board.paytaro_enable')) {
  293. abort(500, '支付方式不可用');
  294. }
  295. return response([
  296. 'type' => 1,
  297. 'data' => $this->payTaro($order)
  298. ]);
  299. default:
  300. abort(500, '支付方式不存在');
  301. }
  302. }
  303. public function check(Request $request)
  304. {
  305. $tradeNo = $request->input('trade_no');
  306. $order = Order::where('trade_no', $tradeNo)
  307. ->where('user_id', $request->session()->get('id'))
  308. ->first();
  309. if (!$order) {
  310. abort(500, '订单不存在');
  311. }
  312. return response([
  313. 'data' => $order->status
  314. ]);
  315. }
  316. public function getPaymentMethod()
  317. {
  318. $data = [];
  319. if ((int)config('v2board.alipay_enable')) {
  320. $alipayF2F = new \StdClass();
  321. $alipayF2F->name = '支付宝';
  322. $alipayF2F->method = 0;
  323. $alipayF2F->icon = 'alipay';
  324. array_push($data, $alipayF2F);
  325. }
  326. if ((int)config('v2board.stripe_alipay_enable')) {
  327. $stripeAlipay = new \StdClass();
  328. $stripeAlipay->name = '支付宝';
  329. $stripeAlipay->method = 2;
  330. $stripeAlipay->icon = 'alipay';
  331. array_push($data, $stripeAlipay);
  332. }
  333. if ((int)config('v2board.stripe_wepay_enable')) {
  334. $stripeWepay = new \StdClass();
  335. $stripeWepay->name = '微信';
  336. $stripeWepay->method = 3;
  337. $stripeWepay->icon = 'wechat';
  338. array_push($data, $stripeWepay);
  339. }
  340. if ((int)config('v2board.bitpayx_enable')) {
  341. $bitpayX = new \StdClass();
  342. $bitpayX->name = '聚合支付';
  343. $bitpayX->method = 4;
  344. $bitpayX->icon = 'wallet';
  345. array_push($data, $bitpayX);
  346. }
  347. if ((int)config('v2board.paytaro_enable')) {
  348. $obj = new \StdClass();
  349. $obj->name = '聚合支付';
  350. $obj->method = 5;
  351. $obj->icon = 'wallet';
  352. array_push($data, $obj);
  353. }
  354. return response([
  355. 'data' => $data
  356. ]);
  357. }
  358. public function cancel(Request $request)
  359. {
  360. if (empty($request->input('trade_no'))) {
  361. abort(500, '参数有误');
  362. }
  363. $order = Order::where('trade_no', $request->input('trade_no'))
  364. ->where('user_id', $request->session()->get('id'))
  365. ->first();
  366. if (!$order) {
  367. abort(500, '订单不存在');
  368. }
  369. if ($order->status !== 0) {
  370. abort(500, '只可以取消待支付订单');
  371. }
  372. $orderService = new OrderService($order);
  373. if (!$orderService->cancel()) {
  374. abort(500, '取消失败');
  375. }
  376. return response([
  377. 'data' => true
  378. ]);
  379. }
  380. private function alipayF2F($tradeNo, $totalAmount)
  381. {
  382. $gateway = Omnipay::create('Alipay_AopF2F');
  383. $gateway->setSignType('RSA2'); //RSA/RSA2
  384. $gateway->setAppId(config('v2board.alipay_appid'));
  385. $gateway->setPrivateKey(config('v2board.alipay_privkey')); // 可以是路径,也可以是密钥内容
  386. $gateway->setAlipayPublicKey(config('v2board.alipay_pubkey')); // 可以是路径,也可以是密钥内容
  387. $gateway->setNotifyUrl(url('/api/v1/guest/order/alipayNotify'));
  388. $request = $gateway->purchase();
  389. $request->setBizContent([
  390. 'subject' => config('v2board.app_name', 'V2Board') . ' - 订阅',
  391. 'out_trade_no' => $tradeNo,
  392. 'total_amount' => $totalAmount / 100
  393. ]);
  394. /** @var \Omnipay\Alipay\Responses\AopTradePreCreateResponse $response */
  395. $response = $request->send();
  396. $result = $response->getAlipayResponse();
  397. if ($result['code'] !== '10000') {
  398. abort(500, $result['sub_msg']);
  399. }
  400. // 获取收款二维码内容
  401. return $response->getQrCode();
  402. }
  403. private function stripeAlipay($order)
  404. {
  405. $currency = config('stripe_currency', 'hkd');
  406. $exchange = Helper::exchange('CNY', strtoupper($currency));
  407. if (!$exchange) {
  408. abort(500, '货币转换超时,请稍后再试');
  409. }
  410. Stripe::setApiKey(config('v2board.stripe_sk_live'));
  411. $source = Source::create([
  412. 'amount' => floor($order->total_amount * $exchange),
  413. 'currency' => $currency,
  414. 'type' => 'alipay',
  415. 'statement_descriptor' => $order->trade_no,
  416. 'metadata' => [
  417. 'user_id' => $order->user_id,
  418. 'invoice_id' => $order->trade_no,
  419. 'identifier' => ''
  420. ],
  421. 'redirect' => [
  422. 'return_url' => config('v2board.app_url', env('APP_URL')) . '/#/order'
  423. ]
  424. ]);
  425. if (!$source['redirect']['url']) {
  426. abort(500, '支付网关请求失败');
  427. }
  428. if (!Cache::put($source['id'], $order->trade_no, 3600)) {
  429. abort(500, '订单创建失败');
  430. }
  431. return $source['redirect']['url'];
  432. }
  433. private function stripeWepay($order)
  434. {
  435. $currency = config('stripe_currency', 'hkd');
  436. $exchange = Helper::exchange('CNY', strtoupper($currency));
  437. if (!$exchange) {
  438. abort(500, '货币转换超时,请稍后再试');
  439. }
  440. Stripe::setApiKey(config('v2board.stripe_sk_live'));
  441. $source = Source::create([
  442. 'amount' => floor($order->total_amount * $exchange),
  443. 'currency' => $currency,
  444. 'type' => 'wechat',
  445. 'metadata' => [
  446. 'user_id' => $order->user_id,
  447. 'invoice_id' => $order->trade_no,
  448. 'identifier' => ''
  449. ],
  450. 'redirect' => [
  451. 'return_url' => config('v2board.app_url', env('APP_URL')) . '/#/order'
  452. ]
  453. ]);
  454. if (!$source['wechat']['qr_code_url']) {
  455. abort(500, '支付网关请求失败');
  456. }
  457. if (!Cache::put($source['id'], $order->trade_no, 3600)) {
  458. abort(500, '订单创建失败');
  459. }
  460. return $source['wechat']['qr_code_url'];
  461. }
  462. private function bitpayX($order)
  463. {
  464. $bitpayX = new BitpayX(config('v2board.bitpayx_appsecret'));
  465. $params = [
  466. 'merchant_order_id' => $order->trade_no,
  467. 'price_amount' => $order->total_amount / 100,
  468. 'price_currency' => 'CNY',
  469. 'title' => '支付单号:' . $order->trade_no,
  470. 'description' => '充值:' . $order->total_amount / 100 . ' 元',
  471. 'callback_url' => url('/api/v1/guest/order/bitpayXNotify'),
  472. 'success_url' => config('v2board.app_url', env('APP_URL')) . '/#/order',
  473. 'cancel_url' => config('v2board.app_url', env('APP_URL')) . '/#/order'
  474. ];
  475. $strToSign = $bitpayX->prepareSignId($params['merchant_order_id']);
  476. $params['token'] = $bitpayX->sign($strToSign);
  477. $result = $bitpayX->mprequest($params);
  478. // Log::info('bitpayXSubmit: ' . json_encode($result));
  479. return isset($result['payment_url']) ? $result['payment_url'] : false;
  480. }
  481. private function payTaro($order)
  482. {
  483. $payTaro = new PayTaro(config('v2board.paytaro_app_id'), config('v2board.paytaro_app_secret'));
  484. $result = $payTaro->pay([
  485. 'app_id' => config('v2board.paytaro_app_id'),
  486. 'out_trade_no' => $order->trade_no,
  487. 'total_amount' => $order->total_amount,
  488. 'notify_url' => url('/api/v1/guest/order/payTaroNotify'),
  489. 'return_url' => config('v2board.app_url', env('APP_URL')) . '/#/order'
  490. ]);
  491. return $result;
  492. }
  493. }