AI store generator for ecommerce, Malaysia first. Laravel 13 + React + TypeScript.
Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

StripeGateway.php 4.1KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  1. <?php
  2. namespace App\Commerce\Payments;
  3. use App\Models\Order;
  4. use App\Models\OrderItem;
  5. use Stripe\Checkout\Session;
  6. use Stripe\Exception\ApiErrorException;
  7. use Stripe\Exception\SignatureVerificationException;
  8. use Stripe\StripeClient;
  9. use Stripe\Webhook;
  10. use UnexpectedValueException;
  11. /**
  12. * Payments through Stripe Checkout: Stripe hosts the payment page, so card details never touch our server.
  13. *
  14. * No payment method list is sent, so Stripe shows whatever is switched on in the Stripe dashboard
  15. * for Malaysian Ringgit (cards, FPX, GrabPay and so on).
  16. */
  17. final class StripeGateway implements PaymentGateway
  18. {
  19. public function name(): string
  20. {
  21. return 'stripe';
  22. }
  23. public function startCheckout(Order $order, string $successUrl, string $cancelUrl): CheckoutLink
  24. {
  25. try {
  26. $session = $this->client()->checkout->sessions->create([
  27. 'mode' => 'payment',
  28. 'customer_email' => $order->customer_email,
  29. 'client_reference_id' => (string) $order->id,
  30. 'metadata' => ['order_id' => (string) $order->id, 'store_id' => (string) $order->store_id],
  31. 'line_items' => $order->items->map(fn (OrderItem $item) => [
  32. 'quantity' => $item->quantity,
  33. 'price_data' => [
  34. 'currency' => strtolower($order->currency),
  35. 'unit_amount' => $item->unit_price,
  36. 'product_data' => ['name' => $item->name],
  37. ],
  38. ])->values()->all(),
  39. // Stripe replaces {CHECKOUT_SESSION_ID} with the real id when it sends the shopper back.
  40. 'success_url' => $successUrl.(str_contains($successUrl, '?') ? '&' : '?').'session_id={CHECKOUT_SESSION_ID}',
  41. 'cancel_url' => $cancelUrl,
  42. ]);
  43. } catch (ApiErrorException $e) {
  44. throw new PaymentException('Stripe could not create the payment page: '.$e->getMessage(), 0, $e);
  45. }
  46. if (! is_string($session->url)) {
  47. throw new PaymentException('Stripe did not return a payment page address.');
  48. }
  49. return new CheckoutLink($session->id, $session->url);
  50. }
  51. public function checkPayment(string $checkoutId): PaymentStatus
  52. {
  53. try {
  54. return $this->status($this->client()->checkout->sessions->retrieve($checkoutId));
  55. } catch (ApiErrorException $e) {
  56. throw new PaymentException('Stripe could not find the payment: '.$e->getMessage(), 0, $e);
  57. }
  58. }
  59. public function readWebhook(string $payload, string $signature): ?PaymentStatus
  60. {
  61. $secret = (string) config('services.stripe.webhook_secret');
  62. if ($secret === '') {
  63. throw new PaymentException('STRIPE_WEBHOOK_SECRET is not set.');
  64. }
  65. try {
  66. $event = Webhook::constructEvent($payload, $signature, $secret);
  67. } catch (SignatureVerificationException|UnexpectedValueException $e) {
  68. throw new PaymentException('The webhook message is not from Stripe.', 0, $e);
  69. }
  70. $session = $event->data->object ?? null;
  71. // "async_payment_succeeded" covers methods such as FPX that confirm a little later.
  72. if (! in_array($event->type, ['checkout.session.completed', 'checkout.session.async_payment_succeeded'], true)
  73. || ! $session instanceof Session) {
  74. return null;
  75. }
  76. return $this->status($session);
  77. }
  78. private function status(Session $session): PaymentStatus
  79. {
  80. return new PaymentStatus(
  81. checkoutId: $session->id,
  82. paid: $session->payment_status === 'paid',
  83. reference: is_string($session->payment_intent) ? $session->payment_intent : null,
  84. amount: $session->amount_total,
  85. );
  86. }
  87. private function client(): StripeClient
  88. {
  89. $secret = (string) config('services.stripe.secret');
  90. if ($secret === '') {
  91. throw new PaymentException('STRIPE_SECRET is missing in the settings file.');
  92. }
  93. return new StripeClient($secret);
  94. }
  95. }