PaymentController.php 8.9 KB

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