OrderController.php 12 KB

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