OrderController.php 14 KB

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