OrderController.php 17 KB

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