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 7.3KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184
  1. <?php
  2. namespace App\Commerce\Payments;
  3. use App\Models\Order;
  4. use App\Models\OrderItem;
  5. use App\Models\Store;
  6. use Stripe\Checkout\Session;
  7. use Stripe\Exception\ApiErrorException;
  8. use Stripe\Exception\SignatureVerificationException;
  9. use Stripe\StripeClient;
  10. use Stripe\Webhook;
  11. use UnexpectedValueException;
  12. /**
  13. * Payments through Stripe Checkout: Stripe hosts the payment page, so card details never touch our server.
  14. *
  15. * The page is made in the merchant's own Stripe account (Stripe Connect "direct charges"), so the money goes
  16. * straight to them and they are the seller on the shopper's receipt. We take no cut.
  17. *
  18. * No payment method list is sent, so Stripe shows whatever is switched on in the Stripe dashboard
  19. * for Malaysian Ringgit (cards, FPX, GrabPay and so on).
  20. */
  21. final class StripeGateway implements PaymentGateway
  22. {
  23. public function __construct(private readonly StripeConnect $connect) {}
  24. public function name(): string
  25. {
  26. return 'stripe';
  27. }
  28. public function canTakePayments(Store $store): bool
  29. {
  30. return $this->connect->canTakePayments($store);
  31. }
  32. public function startCheckout(Order $order, string $successUrl, string $cancelUrl): CheckoutLink
  33. {
  34. $account = $order->store->stripeAccount?->account_id;
  35. if ($account === null) {
  36. throw new PaymentException('The store has not connected its Stripe account.');
  37. }
  38. // Everything for this payment is made in the merchant's account.
  39. $in = ['stripe_account' => $account];
  40. try {
  41. $session = $this->client()->checkout->sessions->create([
  42. 'mode' => 'payment',
  43. 'customer_email' => $order->customer_email,
  44. 'client_reference_id' => (string) $order->id,
  45. 'metadata' => ['order_id' => (string) $order->id, 'store_id' => (string) $order->store_id],
  46. 'line_items' => $order->items->map(fn (OrderItem $item) => [
  47. 'quantity' => $item->quantity,
  48. 'price_data' => [
  49. 'currency' => strtolower($order->currency),
  50. 'unit_amount' => $item->unit_price,
  51. 'product_data' => ['name' => $item->name],
  52. ],
  53. ])->values()->all(),
  54. // A one-off Stripe coupon for exactly the discount, so Stripe's page shows the code and the saving.
  55. ...($order->discount_total > 0 ? ['discounts' => [['coupon' => $this->couponFor($order, $in)]]] : []),
  56. // Shipping is shown on Stripe's page as its own line, so the shopper sees what they pay for.
  57. 'shipping_options' => [[
  58. 'shipping_rate_data' => [
  59. 'type' => 'fixed_amount',
  60. 'fixed_amount' => ['amount' => $order->shipping_total, 'currency' => strtolower($order->currency)],
  61. 'display_name' => $this->shippingLabel($order),
  62. ],
  63. ]],
  64. // Stripe replaces {CHECKOUT_SESSION_ID} with the real id when it sends the shopper back.
  65. 'success_url' => $successUrl.(str_contains($successUrl, '?') ? '&' : '?').'session_id={CHECKOUT_SESSION_ID}',
  66. 'cancel_url' => $cancelUrl,
  67. ], $in);
  68. } catch (ApiErrorException $e) {
  69. throw new PaymentException('Stripe could not create the payment page: '.$e->getMessage(), 0, $e);
  70. }
  71. if (! is_string($session->url)) {
  72. throw new PaymentException('Stripe did not return a payment page address.');
  73. }
  74. return new CheckoutLink($session->id, $session->url, $account);
  75. }
  76. /**
  77. * A coupon that can be used once, worth exactly this order's discount.
  78. * Stripe takes it off the products only, never off shipping, which matches our own rule.
  79. *
  80. * @param array{stripe_account: string} $in
  81. *
  82. * @throws ApiErrorException
  83. */
  84. private function couponFor(Order $order, array $in): string
  85. {
  86. return $this->client()->coupons->create([
  87. 'amount_off' => $order->discount_total,
  88. 'currency' => strtolower($order->currency),
  89. 'duration' => 'once',
  90. 'max_redemptions' => 1,
  91. // The code, or the automatic discount's name, such as "Raya Sale".
  92. 'name' => $order->discount_code ?? $order->discount_name ?? 'Discount',
  93. 'metadata' => ['order_id' => (string) $order->id],
  94. ], $in)->id;
  95. }
  96. private function shippingLabel(Order $order): string
  97. {
  98. $malay = $order->store->language->value === 'ms';
  99. if ($order->shipping_total === 0) {
  100. return $malay ? 'Penghantaran percuma' : 'Free shipping';
  101. }
  102. return $malay ? 'Penghantaran' : 'Shipping';
  103. }
  104. public function checkPayment(Order $order): PaymentStatus
  105. {
  106. if ($order->payment_checkout_id === null) {
  107. throw new PaymentException('The order has no payment page.');
  108. }
  109. // Older test orders were paid into our own account and have no merchant account.
  110. $in = $order->payment_account !== null ? ['stripe_account' => $order->payment_account] : [];
  111. try {
  112. return $this->status($this->client()->checkout->sessions->retrieve($order->payment_checkout_id, [], $in));
  113. } catch (ApiErrorException $e) {
  114. throw new PaymentException('Stripe could not find the payment: '.$e->getMessage(), 0, $e);
  115. }
  116. }
  117. public function readWebhook(string $payload, string $signature, bool $fromMerchants = false): ?PaymentStatus
  118. {
  119. // Stripe signs messages about merchants' accounts with a different secret.
  120. $name = $fromMerchants ? 'connect_webhook_secret' : 'webhook_secret';
  121. $secret = (string) config('services.stripe.'.$name);
  122. if ($secret === '') {
  123. throw new PaymentException('services.stripe.'.$name.' is not set.');
  124. }
  125. try {
  126. $event = Webhook::constructEvent($payload, $signature, $secret);
  127. } catch (SignatureVerificationException|UnexpectedValueException $e) {
  128. throw new PaymentException('The webhook message is not from Stripe.', 0, $e);
  129. }
  130. $session = $event->data->object ?? null;
  131. // "async_payment_succeeded" covers methods such as FPX that confirm a little later.
  132. if (! in_array($event->type, ['checkout.session.completed', 'checkout.session.async_payment_succeeded'], true)
  133. || ! $session instanceof Session) {
  134. return null;
  135. }
  136. return $this->status($session, is_string($event->account ?? null) ? $event->account : null);
  137. }
  138. private function status(Session $session, ?string $account = null): PaymentStatus
  139. {
  140. return new PaymentStatus(
  141. checkoutId: $session->id,
  142. paid: $session->payment_status === 'paid',
  143. reference: is_string($session->payment_intent) ? $session->payment_intent : null,
  144. amount: $session->amount_total,
  145. account: $account,
  146. );
  147. }
  148. private function client(): StripeClient
  149. {
  150. $secret = (string) config('services.stripe.secret');
  151. if ($secret === '') {
  152. throw new PaymentException('STRIPE_SECRET is missing in the settings file.');
  153. }
  154. return new StripeClient($secret);
  155. }
  156. }