OrderController.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350
  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 && $coupon->limit_use !== NULL) {
  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. if ($coupon->limit_use !== NULL) {
  119. $coupon->limit_use = $coupon->limit_use - 1;
  120. if (!$coupon->save()) {
  121. DB::rollback();
  122. abort(500, '优惠券使用失败');
  123. }
  124. }
  125. }
  126. // free process
  127. if ($order->total_amount <= 0) {
  128. $order->total_amount = 0;
  129. $order->status = 1;
  130. }
  131. if (!$order->save()) {
  132. DB::rollback();
  133. abort(500, '订单创建失败');
  134. }
  135. DB::commit();
  136. return response([
  137. 'data' => $order->trade_no
  138. ]);
  139. }
  140. public function checkout (Request $request) {
  141. $tradeNo = $request->input('trade_no');
  142. $method = $request->input('method');
  143. $order = Order::where('trade_no', $tradeNo)
  144. ->where('user_id', $request->session()->get('id'))
  145. ->where('status', 0)
  146. ->first();
  147. if (!$order) {
  148. abort(500, '订单不存在或已支付');
  149. }
  150. switch ($method) {
  151. // return type => 0: QRCode / 1: URL
  152. case 0:
  153. // alipayF2F
  154. if (!(int)config('v2board.alipay_enable')) {
  155. abort(500, '支付方式不可用');
  156. }
  157. return response([
  158. 'type' => 0,
  159. 'data' => $this->alipayF2F($tradeNo, $order->total_amount)
  160. ]);
  161. case 2:
  162. // stripeAlipay
  163. if (!(int)config('v2board.stripe_alipay_enable')) {
  164. abort(500, '支付方式不可用');
  165. }
  166. return response([
  167. 'type' => 1,
  168. 'data' => $this->stripeAlipay($order)
  169. ]);
  170. case 3:
  171. // stripeWepay
  172. if (!(int)config('v2board.stripe_wepay_enable')) {
  173. abort(500, '支付方式不可用');
  174. }
  175. return response([
  176. 'type' => 0,
  177. 'data' => $this->stripeWepay($order)
  178. ]);
  179. case 4:
  180. // bitpayX
  181. if (!(int)config('v2board.bitpayx_enable')) {
  182. abort(500, '支付方式不可用');
  183. }
  184. return response([
  185. 'type' => 1,
  186. 'data' => $this->bitpayX($order)
  187. ]);
  188. default:
  189. abort(500, '支付方式不存在');
  190. }
  191. }
  192. public function check (Request $request) {
  193. $tradeNo = $request->input('trade_no');
  194. $order = Order::where('trade_no', $tradeNo)
  195. ->where('user_id', $request->session()->get('id'))
  196. ->first();
  197. if (!$order) {
  198. abort(500, '订单不存在');
  199. }
  200. return response([
  201. 'data' => $order->status
  202. ]);
  203. }
  204. public function getPaymentMethod () {
  205. $data = [];
  206. if ((int)config('v2board.alipay_enable')) {
  207. $alipayF2F = new \StdClass();
  208. $alipayF2F->name = '支付宝';
  209. $alipayF2F->method = 0;
  210. $alipayF2F->icon = 'alipay';
  211. array_push($data, $alipayF2F);
  212. }
  213. if ((int)config('v2board.stripe_alipay_enable')) {
  214. $stripeAlipay = new \StdClass();
  215. $stripeAlipay->name = '支付宝';
  216. $stripeAlipay->method = 2;
  217. $stripeAlipay->icon = 'alipay';
  218. array_push($data, $stripeAlipay);
  219. }
  220. if ((int)config('v2board.stripe_wepay_enable')) {
  221. $stripeWepay = new \StdClass();
  222. $stripeWepay->name = '微信';
  223. $stripeWepay->method = 3;
  224. $stripeWepay->icon = 'wechat';
  225. array_push($data, $stripeWepay);
  226. }
  227. if ((int)config('v2board.bitpayx_enable')) {
  228. $bitpayX = new \StdClass();
  229. $bitpayX->name = '虚拟货币';
  230. $bitpayX->method = 4;
  231. $bitpayX->icon = 'bitcoin';
  232. array_push($data, $bitpayX);
  233. }
  234. return response([
  235. 'data' => $data
  236. ]);
  237. }
  238. private function alipayF2F ($tradeNo, $totalAmount) {
  239. $gateway = Omnipay::create('Alipay_AopF2F');
  240. $gateway->setSignType('RSA2'); //RSA/RSA2
  241. $gateway->setAppId(config('v2board.alipay_appid'));
  242. $gateway->setPrivateKey(config('v2board.alipay_privkey')); // 可以是路径,也可以是密钥内容
  243. $gateway->setAlipayPublicKey(config('v2board.alipay_pubkey')); // 可以是路径,也可以是密钥内容
  244. $gateway->setNotifyUrl(url('/api/v1/guest/order/alipayNotify'));
  245. $request = $gateway->purchase();
  246. $request->setBizContent([
  247. 'subject' => config('v2board.app_name', 'V2Board') . ' - 订阅',
  248. 'out_trade_no' => $tradeNo,
  249. 'total_amount' => $totalAmount / 100
  250. ]);
  251. /** @var \Omnipay\Alipay\Responses\AopTradePreCreateResponse $response */
  252. $response = $request->send();
  253. $result = $response->getAlipayResponse();
  254. if ($result['code'] !== '10000') {
  255. abort(500, $result['sub_msg']);
  256. }
  257. // 获取收款二维码内容
  258. return $response->getQrCode();
  259. }
  260. private function stripeAlipay ($order) {
  261. $exchange = Helper::exchange('CNY', 'HKD');
  262. if (!$exchange) {
  263. abort(500, '货币转换超时,请稍后再试');
  264. }
  265. Stripe::setApiKey(config('v2board.stripe_sk_live'));
  266. $source = Source::create([
  267. 'amount' => floor($order->total_amount * $exchange),
  268. 'currency' => 'hkd',
  269. 'type' => 'alipay',
  270. 'redirect' => [
  271. 'return_url' => config('v2board.app_url', env('APP_URL')) . '/#/order'
  272. ]
  273. ]);
  274. if (!$source['redirect']['url']) {
  275. abort(500, '支付网关请求失败');
  276. }
  277. if (!Redis::set($source['id'], $order->trade_no)) {
  278. abort(500, '订单创建失败');
  279. }
  280. Redis::expire($source['id'], 3600);
  281. return $source['redirect']['url'];
  282. }
  283. private function stripeWepay ($order) {
  284. $exchange = Helper::exchange('CNY', 'HKD');
  285. if (!$exchange) {
  286. abort(500, '货币转换超时,请稍后再试');
  287. }
  288. Stripe::setApiKey(config('v2board.stripe_sk_live'));
  289. $source = Source::create([
  290. 'amount' => floor($order->total_amount * $exchange),
  291. 'currency' => 'hkd',
  292. 'type' => 'wechat',
  293. 'redirect' => [
  294. 'return_url' => config('v2board.app_url', env('APP_URL')) . '/#/order'
  295. ]
  296. ]);
  297. if (!$source['wechat']['qr_code_url']) {
  298. abort(500, '支付网关请求失败');
  299. }
  300. if (!Redis::set($source['id'], $order->trade_no)) {
  301. abort(500, '订单创建失败');
  302. }
  303. Redis::expire($source['id'], 3600);
  304. return $source['wechat']['qr_code_url'];
  305. }
  306. private function bitpayX ($order) {
  307. $bitpayX = new BitpayX(config('v2board.bitpayx_appsecret'));
  308. $params = [
  309. 'merchant_order_id' => 'V2Board_' . $order->trade_no,
  310. 'price_amount' => $order->total_amount / 100,
  311. 'price_currency' => 'CNY',
  312. 'title' => '支付单号:' . $order->trade_no,
  313. 'description' => '充值:' . $order->total_amount / 100 . ' 元',
  314. 'callback_url' => url('/api/v1/guest/order/bitpayXNotify'),
  315. 'success_url' => config('v2board.app_url', env('APP_URL')) . '/#/order',
  316. 'cancel_url' => config('v2board.app_url', env('APP_URL')) . '/#/order'
  317. ];
  318. $strToSign = $bitpayX->prepareSignId($params['merchant_order_id']);
  319. $params['token'] = $bitpayX->sign($strToSign);
  320. $result = $bitpayX->mprequest($params);
  321. Log::info('bitpayXSubmit: ' . json_encode($result));
  322. return isset($result['payment_url']) ? $result['payment_url'] : false;
  323. }
  324. }