OrderController.php 13 KB

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