OrderController.php 18 KB

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