OrderController.php 19 KB

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