Stripe.php 4.5 KB

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