PaymentController.php 8.3 KB

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