OrderController.php 13 KB

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