AI store generator for ecommerce, Malaysia first. Laravel 13 + React + TypeScript.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

StripeGateway.php 5.7KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151
  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. // A one-off Stripe coupon for exactly the discount, so Stripe's page shows the code and the saving.
  40. ...($order->discount_total > 0 ? ['discounts' => [['coupon' => $this->couponFor($order)]]] : []),
  41. // Shipping is shown on Stripe's page as its own line, so the shopper sees what they pay for.
  42. 'shipping_options' => [[
  43. 'shipping_rate_data' => [
  44. 'type' => 'fixed_amount',
  45. 'fixed_amount' => ['amount' => $order->shipping_total, 'currency' => strtolower($order->currency)],
  46. 'display_name' => $this->shippingLabel($order),
  47. ],
  48. ]],
  49. // Stripe replaces {CHECKOUT_SESSION_ID} with the real id when it sends the shopper back.
  50. 'success_url' => $successUrl.(str_contains($successUrl, '?') ? '&' : '?').'session_id={CHECKOUT_SESSION_ID}',
  51. 'cancel_url' => $cancelUrl,
  52. ]);
  53. } catch (ApiErrorException $e) {
  54. throw new PaymentException('Stripe could not create the payment page: '.$e->getMessage(), 0, $e);
  55. }
  56. if (! is_string($session->url)) {
  57. throw new PaymentException('Stripe did not return a payment page address.');
  58. }
  59. return new CheckoutLink($session->id, $session->url);
  60. }
  61. /**
  62. * A coupon that can be used once, worth exactly this order's discount.
  63. * Stripe takes it off the products only, never off shipping, which matches our own rule.
  64. *
  65. * @throws ApiErrorException
  66. */
  67. private function couponFor(Order $order): string
  68. {
  69. return $this->client()->coupons->create([
  70. 'amount_off' => $order->discount_total,
  71. 'currency' => strtolower($order->currency),
  72. 'duration' => 'once',
  73. 'max_redemptions' => 1,
  74. 'name' => (string) $order->discount_code,
  75. 'metadata' => ['order_id' => (string) $order->id],
  76. ])->id;
  77. }
  78. private function shippingLabel(Order $order): string
  79. {
  80. $malay = $order->store->language->value === 'ms';
  81. if ($order->shipping_total === 0) {
  82. return $malay ? 'Penghantaran percuma' : 'Free shipping';
  83. }
  84. return $malay ? 'Penghantaran' : 'Shipping';
  85. }
  86. public function checkPayment(string $checkoutId): PaymentStatus
  87. {
  88. try {
  89. return $this->status($this->client()->checkout->sessions->retrieve($checkoutId));
  90. } catch (ApiErrorException $e) {
  91. throw new PaymentException('Stripe could not find the payment: '.$e->getMessage(), 0, $e);
  92. }
  93. }
  94. public function readWebhook(string $payload, string $signature): ?PaymentStatus
  95. {
  96. $secret = (string) config('services.stripe.webhook_secret');
  97. if ($secret === '') {
  98. throw new PaymentException('STRIPE_WEBHOOK_SECRET is not set.');
  99. }
  100. try {
  101. $event = Webhook::constructEvent($payload, $signature, $secret);
  102. } catch (SignatureVerificationException|UnexpectedValueException $e) {
  103. throw new PaymentException('The webhook message is not from Stripe.', 0, $e);
  104. }
  105. $session = $event->data->object ?? null;
  106. // "async_payment_succeeded" covers methods such as FPX that confirm a little later.
  107. if (! in_array($event->type, ['checkout.session.completed', 'checkout.session.async_payment_succeeded'], true)
  108. || ! $session instanceof Session) {
  109. return null;
  110. }
  111. return $this->status($session);
  112. }
  113. private function status(Session $session): PaymentStatus
  114. {
  115. return new PaymentStatus(
  116. checkoutId: $session->id,
  117. paid: $session->payment_status === 'paid',
  118. reference: is_string($session->payment_intent) ? $session->payment_intent : null,
  119. amount: $session->amount_total,
  120. );
  121. }
  122. private function client(): StripeClient
  123. {
  124. $secret = (string) config('services.stripe.secret');
  125. if ($secret === '') {
  126. throw new PaymentException('STRIPE_SECRET is missing in the settings file.');
  127. }
  128. return new StripeClient($secret);
  129. }
  130. }