OrderController.php 14 KB

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