OrderController.php 15 KB

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