Stripe.php 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170
  1. <?php
  2. namespace App\Payments;
  3. use App\Models\Payment;
  4. use App\Payments\Library\Gateway;
  5. use Auth;
  6. use Exception;
  7. use Illuminate\Http\JsonResponse;
  8. use Log;
  9. use Response;
  10. use Stripe\Checkout\Session;
  11. use Stripe\Exception\SignatureVerificationException;
  12. use Stripe\Source;
  13. use Stripe\Webhook;
  14. use UnexpectedValueException;
  15. class Stripe extends Gateway
  16. {
  17. public function __construct()
  18. {
  19. \Stripe\Stripe::setApiKey(sysConfig('stripe_secret_key'));
  20. }
  21. public function purchase($request): JsonResponse
  22. {
  23. $type = $request->input('type');
  24. $payment = $this->creatNewPayment(Auth::id(), $request->input('id'), $request->input('amount'));
  25. if ($type == 1 || $type == 3) {
  26. $source = Source::create([
  27. 'amount' => ceil($payment->amount * 100),
  28. 'currency' => strtolower(sysConfig('standard_currency')),
  29. 'type' => $type == 1 ? 'alipay' : 'wechat',
  30. 'statement_descriptor' => $payment->trade_no,
  31. 'metadata' => [
  32. 'user_id' => $payment->user_id,
  33. 'out_trade_no' => $payment->trade_no,
  34. 'identifier' => '',
  35. ],
  36. 'redirect' => [
  37. 'return_url' => route('invoice'),
  38. ],
  39. ]);
  40. if ($type == 3) {
  41. if (! $source['wechat']['qr_code_url']) {
  42. Log::warning('创建订单错误:未知错误');
  43. $payment->failed();
  44. return Response::json(['status' => 'fail', 'message' => '创建订单失败:未知错误']);
  45. }
  46. $payment->update(['qr_code' => 1, 'url' => $source['wechat']['qr_code_url']]);
  47. return Response::json(['status' => 'success', 'data' => $payment->trade_no, 'message' => '创建订单成功!']);
  48. }
  49. if (! $source['redirect']['url']) {
  50. Log::warning('创建订单错误:未知错误');
  51. $payment->failed();
  52. return response()->json(['code' => 0, 'msg' => '创建订单失败:未知错误']);
  53. }
  54. $payment->update(['url' => $source['redirect']['url']]);
  55. return Response::json(['status' => 'success', 'url' => $source['redirect']['url'], 'message' => '创建订单成功!']);
  56. }
  57. $data = $this->getCheckoutSessionData($payment->trade_no, $payment->amount, $type);
  58. try {
  59. $session = Session::create($data);
  60. $url = route('stripe.checkout', ['session_id' => $session->id]);
  61. $payment->update(['url' => $url]);
  62. return Response::json(['status' => 'success', 'url' => $url, 'message' => '创建订单成功!']);
  63. } catch (Exception $e) {
  64. Log::error('【Stripe】错误: '.$e->getMessage());
  65. exit;
  66. }
  67. }
  68. public function redirectPage($session_id)
  69. { // redirect to Stripe Payment url
  70. return view('user.components.payment.stripe', ['session_id' => $session_id]);
  71. }
  72. public function notify($request): void
  73. { // url = '/callback/notify?method=stripe'
  74. $sigHeader = $_SERVER['HTTP_STRIPE_SIGNATURE'];
  75. $endpointSecret = sysConfig('stripe_signing_secret');
  76. $payload = @file_get_contents('php://input');
  77. try {
  78. $event = Webhook::constructEvent($payload, $sigHeader, $endpointSecret);
  79. } catch (UnexpectedValueException $e) {
  80. // Invalid payload
  81. http_response_code(400);
  82. exit;
  83. } catch (SignatureVerificationException $e) {
  84. // Invalid signature
  85. http_response_code(400);
  86. exit;
  87. }
  88. Log::info('【Stripe】Passed signature verification!');
  89. switch ($event->type) {
  90. case 'checkout.session.completed':
  91. /* @var $session Session */
  92. $session = $event->data->object;
  93. // Check if the order is paid (e.g., from a card payment)
  94. //
  95. // A delayed notification payment will have an `unpaid` status, as
  96. // you're still waiting for funds to be transferred from the customer's
  97. // account.
  98. if ($session->payment_status == 'paid') {
  99. // Fulfill the purchase
  100. $this->paymentReceived($session->client_reference_id);
  101. }
  102. break;
  103. case 'checkout.session.async_payment_succeeded':
  104. $session = $event->data->object;
  105. // Fulfill the purchase
  106. $this->paymentReceived($session->client_reference_id);
  107. break;
  108. case 'checkout.session.async_payment_failed':
  109. $session = $event->data->object;
  110. // Send an email to the customer asking them to retry their order
  111. $this->failedPayment($session);
  112. break;
  113. }
  114. http_response_code(200);
  115. exit;
  116. }
  117. public function failedPayment(Session $session)
  118. { // 未支付成功则关闭订单
  119. $payment = Payment::whereTradeNo($session->client_reference_id)->first();
  120. if ($payment) {
  121. $payment->order->close();
  122. }
  123. }
  124. protected function getCheckoutSessionData(string $tradeNo, int $amount, int $type): array
  125. {
  126. $unitAmount = $amount * 100;
  127. return [
  128. 'payment_method_types' => ['card'],
  129. 'line_items' => [
  130. [
  131. 'price_data' => [
  132. 'currency' => 'usd',
  133. 'product_data' => ['name' => sysConfig('subject_name') ?: sysConfig('website_name')],
  134. 'unit_amount' => $unitAmount,
  135. ],
  136. 'quantity' => 1,
  137. ],
  138. ],
  139. 'mode' => 'payment',
  140. 'success_url' => route('invoice'),
  141. 'cancel_url' => route('invoice'),
  142. 'client_reference_id' => $tradeNo,
  143. 'customer_email' => Auth::getUser()->email,
  144. ];
  145. }
  146. }