OrderController.php 15 KB

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