OrderController.php 19 KB

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