OrderController.php 18 KB

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