OrderController.php 14 KB

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