OrderController.php 13 KB

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