OrderController.php 16 KB

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