OrderController.php 16 KB

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