PaymentController.php 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208
  1. <?php
  2. namespace App\Http\Controllers;
  3. use App\Events\PaymentStatusUpdated;
  4. use App\Models\Coupon;
  5. use App\Models\Goods;
  6. use App\Models\Order;
  7. use App\Models\Payment;
  8. use App\Services\CouponService;
  9. use App\Utils\Helpers;
  10. use App\Utils\Library\Templates\Gateway;
  11. use App\Utils\Payments\PaymentManager;
  12. use Exception;
  13. use Illuminate\Container\Container;
  14. use Illuminate\Contracts\View\View;
  15. use Illuminate\Http\JsonResponse;
  16. use Illuminate\Http\Request;
  17. use Log;
  18. class PaymentController extends Controller
  19. {
  20. public static string $method;
  21. public static function notify(Request $request)
  22. {
  23. self::$method = $request->query('method') ?: $request->input('method');
  24. Log::notice('[{method}] '.trans('admin.menu.log.payment_callback').': {body}', ['method' => self::$method, 'body' => var_export($request->all(), true)]);
  25. return self::getClient()->notify($request);
  26. }
  27. public static function getClient(): Gateway
  28. {
  29. $method = self::$method;
  30. $paymentClasses = PaymentManager::discover();
  31. if (isset($paymentClasses[$method])) {
  32. try {
  33. return Container::getInstance()->make($paymentClasses[$method]['class']);
  34. } catch (Exception $e) {
  35. Log::emergency('Failed to instantiate payment class: '.$e->getMessage());
  36. abort(500);
  37. }
  38. }
  39. Log::emergency(trans('user.payment.order_creation.unknown_payment').': '.$method);
  40. abort(404);
  41. }
  42. public static function getStatus(Request $request): JsonResponse
  43. {
  44. $payment = Payment::whereTradeNo($request->input('trade_no'))->first();
  45. if ($payment) {
  46. if ($payment->status === 1) {
  47. // 触发支付成功事件
  48. broadcast(new PaymentStatusUpdated($payment->trade_no, 'success', trans('common.success_item', ['attribute' => trans('user.pay')])));
  49. return response()->json(['status' => 'success', 'message' => trans('common.success_item', ['attribute' => trans('user.pay')])]);
  50. }
  51. if ($payment->status === -1) {
  52. // 触发支付失败事件
  53. broadcast(new PaymentStatusUpdated($payment->trade_no, 'error', trans('user.payment.order_creation.order_timeout')));
  54. return response()->json(['status' => 'error', 'message' => trans('user.payment.order_creation.order_timeout')]);
  55. }
  56. return response()->json(['status' => 'fail', 'message' => trans('common.status.payment_pending')]);
  57. }
  58. return response()->json(['status' => 'error', 'message' => trans('user.payment.order_creation.unknown_order')]);
  59. }
  60. public function purchase(Request $request): JsonResponse
  61. { // 创建支付订单
  62. $goods_id = $request->input('goods_id');
  63. $coupon_sn = $request->input('coupon_sn');
  64. $coupon = null;
  65. self::$method = $request->input('method');
  66. $credit = $request->input('amount');
  67. $pay_type = $request->input('pay_type');
  68. $amount = 0;
  69. // 充值余额
  70. if ($credit) {
  71. if (! is_numeric($credit) || $credit <= 0) {
  72. return response()->json(['status' => 'fail', 'message' => trans('user.payment.error')]);
  73. }
  74. $amount = $credit;
  75. } elseif ($goods_id && self::$method) { // 购买服务
  76. $goods = Goods::find($goods_id);
  77. if (! $goods || ! $goods->status) {
  78. return response()->json(['status' => 'fail', 'message' => trans('user.payment.order_creation.product_unavailable')]);
  79. }
  80. $amount = $goods->price;
  81. // 是否有生效的套餐
  82. $activePlan = Order::userActivePlan()->doesntExist();
  83. // 无生效套餐,禁止购买加油包
  84. if ($goods->type === 1 && $activePlan) {
  85. return response()->json(['status' => 'fail', 'message' => trans('user.payment.order_creation.plan_required')]);
  86. }
  87. // 单个商品限购
  88. if ($goods->limit_num) {
  89. $count = Order::uid()->where('status', '>=', 0)->whereGoodsId($goods_id)->count();
  90. if ($count >= $goods->limit_num) {
  91. return response()->json(['status' => 'fail', 'message' => trans('user.payment.order_creation.order_limit', ['limit_num' => $goods->limit_num, 'count' => $count])]);
  92. }
  93. }
  94. // 使用优惠券
  95. if ($coupon_sn) {
  96. $coupon = (new CouponService($coupon_sn))->search($goods); // 检查券合规性
  97. if (! $coupon instanceof Coupon) {
  98. return $coupon;
  99. }
  100. // 计算实际应支付总价
  101. $amount = $coupon->type === 2 ? $goods->price * $coupon->value / 100 : $goods->price - $coupon->value;
  102. $amount = $amount > 0 ? round($amount, 2) : 0; // 四舍五入保留2位小数,避免无法正常创建订单
  103. }
  104. // 非余额付款下,检查在线支付是否开启
  105. if (self::$method !== 'credit') {
  106. // 判断是否开启在线支付
  107. if (! sysConfig('is_onlinePay') && ! sysConfig('wechat_qrcode') && ! sysConfig('alipay_qrcode')) {
  108. return response()->json(['status' => 'fail', 'message' => trans('user.payment.order_creation.payment_disabled')]);
  109. }
  110. // 判断是否存在同个商品的未支付订单
  111. if (Order::uid()->whereStatus(0)->exists()) {
  112. return response()->json(['status' => 'fail', 'message' => trans('user.payment.order_creation.pending_order')]);
  113. }
  114. } elseif (auth()->user()->credit < $amount) { // 验证账号余额是否充足
  115. return response()->json(['status' => 'fail', 'message' => trans('user.payment.insufficient_balance')]);
  116. }
  117. // 价格异常判断
  118. if ($amount < 0) {
  119. return response()->json(['status' => 'fail', 'message' => trans('user.payment.order_creation.price_issue')]);
  120. }
  121. if ($amount === 0 && self::$method !== 'credit') {
  122. return response()->json(['status' => 'fail', 'message' => trans('user.payment.order_creation.price_zero')]);
  123. }
  124. }
  125. // 生成订单
  126. try {
  127. $newOrder = Order::create([
  128. 'sn' => date('ymdHis').random_int(100000, 999999),
  129. 'user_id' => auth()->id(),
  130. 'goods_id' => $credit ? null : $goods_id,
  131. 'coupon_id' => $coupon?->id,
  132. 'origin_amount' => $credit ?: ($goods->price ?? 0),
  133. 'amount' => $amount,
  134. 'pay_type' => $pay_type,
  135. 'pay_way' => self::$method,
  136. ]);
  137. // 使用优惠券,减少可使用次数
  138. if ($coupon !== null) {
  139. if ($coupon->usable_times > 0) {
  140. $coupon->decrement('usable_times');
  141. }
  142. Helpers::addCouponLog('Coupon used in order.', $coupon->id, $goods_id, $newOrder->id);
  143. }
  144. $request->merge(['id' => $newOrder->id, 'type' => $pay_type, 'amount' => $amount]);
  145. // 生成支付单
  146. return self::getClient()->purchase($request);
  147. } catch (Exception $e) {
  148. Log::emergency(trans('common.failed_action_item', ['action' => trans('common.create'), 'attribute' => trans('model.order.attribute')]).': '.$e->getMessage());
  149. }
  150. return response()->json(['status' => 'fail', 'message' => trans('common.failed_action_item', ['action' => trans('common.create'), 'attribute' => trans('model.order.attribute')])]);
  151. }
  152. public function close(Order $order): JsonResponse
  153. {
  154. if (! $order->close()) {
  155. return response()->json(['status' => 'fail', 'message' => trans('common.failed_action_item', ['action' => trans('common.close'), 'attribute' => trans('model.order.attribute')])]);
  156. }
  157. return response()->json(['status' => 'success', 'message' => trans('common.success_action_item', ['action' => trans('common.close'), 'attribute' => trans('model.order.attribute')])]);
  158. }
  159. public function detail(string $trade_no): View
  160. { // 支付单详情
  161. $payment = Payment::uid()->with(['order', 'order.goods'])->whereTradeNo($trade_no)->firstOrFail();
  162. $goods = $payment->order->goods;
  163. return view('user.components.payment.default', [
  164. 'payment' => $payment,
  165. 'name' => $goods->name ?? trans('user.recharge_credit'),
  166. 'days' => $goods->days ?? 0,
  167. 'pay_type' => $payment->order->pay_type_label ?: 0,
  168. 'pay_type_icon' => $payment->order->pay_type_icon,
  169. ]);
  170. }
  171. }