AI store generator for ecommerce, Malaysia first. Laravel 13 + React + TypeScript.
Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

StripeGateway.php 7.7KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196
  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 methods(Store $store): array
  33. {
  34. $account = $store->stripeAccount;
  35. // FPX and GrabPay are asked for once the merchant finishes Stripe's form. Cards are always on.
  36. return array_values(array_filter([
  37. 'card',
  38. $account?->fpx_requested ? 'fpx' : null,
  39. $account?->grabpay_requested ? 'grabpay' : null,
  40. ]));
  41. }
  42. public function startCheckout(Order $order, string $successUrl, string $cancelUrl): CheckoutLink
  43. {
  44. $account = $order->store->stripeAccount?->account_id;
  45. if ($account === null) {
  46. throw new PaymentException('The store has not connected its Stripe account.');
  47. }
  48. // Everything for this payment is made in the merchant's account.
  49. $in = ['stripe_account' => $account];
  50. try {
  51. $session = $this->client()->checkout->sessions->create([
  52. 'mode' => 'payment',
  53. 'customer_email' => $order->customer_email,
  54. 'client_reference_id' => (string) $order->id,
  55. 'metadata' => ['order_id' => (string) $order->id, 'store_id' => (string) $order->store_id],
  56. 'line_items' => $order->items->map(fn (OrderItem $item) => [
  57. 'quantity' => $item->quantity,
  58. 'price_data' => [
  59. 'currency' => strtolower($order->currency),
  60. 'unit_amount' => $item->unit_price,
  61. 'product_data' => ['name' => $item->name],
  62. ],
  63. ])->values()->all(),
  64. // A one-off Stripe coupon for exactly the discount, so Stripe's page shows the code and the saving.
  65. ...($order->discount_total > 0 ? ['discounts' => [['coupon' => $this->couponFor($order, $in)]]] : []),
  66. // Shipping is shown on Stripe's page as its own line, so the shopper sees what they pay for.
  67. 'shipping_options' => [[
  68. 'shipping_rate_data' => [
  69. 'type' => 'fixed_amount',
  70. 'fixed_amount' => ['amount' => $order->shipping_total, 'currency' => strtolower($order->currency)],
  71. 'display_name' => $this->shippingLabel($order),
  72. ],
  73. ]],
  74. // Stripe replaces {CHECKOUT_SESSION_ID} with the real id when it sends the shopper back.
  75. 'success_url' => $successUrl.(str_contains($successUrl, '?') ? '&' : '?').'session_id={CHECKOUT_SESSION_ID}',
  76. 'cancel_url' => $cancelUrl,
  77. ], $in);
  78. } catch (ApiErrorException $e) {
  79. throw new PaymentException('Stripe could not create the payment page: '.$e->getMessage(), 0, $e);
  80. }
  81. if (! is_string($session->url)) {
  82. throw new PaymentException('Stripe did not return a payment page address.');
  83. }
  84. return new CheckoutLink($session->id, $session->url, $account);
  85. }
  86. /**
  87. * A coupon that can be used once, worth exactly this order's discount.
  88. * Stripe takes it off the products only, never off shipping, which matches our own rule.
  89. *
  90. * @param array{stripe_account: string} $in
  91. *
  92. * @throws ApiErrorException
  93. */
  94. private function couponFor(Order $order, array $in): string
  95. {
  96. return $this->client()->coupons->create([
  97. 'amount_off' => $order->discount_total,
  98. 'currency' => strtolower($order->currency),
  99. 'duration' => 'once',
  100. 'max_redemptions' => 1,
  101. // The code, or the automatic discount's name, such as "Raya Sale".
  102. 'name' => $order->discount_code ?? $order->discount_name ?? 'Discount',
  103. 'metadata' => ['order_id' => (string) $order->id],
  104. ], $in)->id;
  105. }
  106. private function shippingLabel(Order $order): string
  107. {
  108. $malay = $order->store->language->value === 'ms';
  109. if ($order->shipping_total === 0) {
  110. return $malay ? 'Penghantaran percuma' : 'Free shipping';
  111. }
  112. return $malay ? 'Penghantaran' : 'Shipping';
  113. }
  114. public function checkPayment(Order $order): PaymentStatus
  115. {
  116. if ($order->payment_checkout_id === null) {
  117. throw new PaymentException('The order has no payment page.');
  118. }
  119. // Older test orders were paid into our own account and have no merchant account.
  120. $in = $order->payment_account !== null ? ['stripe_account' => $order->payment_account] : [];
  121. try {
  122. return $this->status($this->client()->checkout->sessions->retrieve($order->payment_checkout_id, [], $in));
  123. } catch (ApiErrorException $e) {
  124. throw new PaymentException('Stripe could not find the payment: '.$e->getMessage(), 0, $e);
  125. }
  126. }
  127. public function readWebhook(string $payload, string $signature, bool $fromMerchants = false): ?PaymentStatus
  128. {
  129. // Stripe signs messages about merchants' accounts with a different secret.
  130. $name = $fromMerchants ? 'connect_webhook_secret' : 'webhook_secret';
  131. $secret = (string) config('services.stripe.'.$name);
  132. if ($secret === '') {
  133. throw new PaymentException('services.stripe.'.$name.' is not set.');
  134. }
  135. try {
  136. $event = Webhook::constructEvent($payload, $signature, $secret);
  137. } catch (SignatureVerificationException|UnexpectedValueException $e) {
  138. throw new PaymentException('The webhook message is not from Stripe.', 0, $e);
  139. }
  140. $session = $event->data->object ?? null;
  141. // "async_payment_succeeded" covers methods such as FPX that confirm a little later.
  142. if (! in_array($event->type, ['checkout.session.completed', 'checkout.session.async_payment_succeeded'], true)
  143. || ! $session instanceof Session) {
  144. return null;
  145. }
  146. return $this->status($session, is_string($event->account ?? null) ? $event->account : null);
  147. }
  148. private function status(Session $session, ?string $account = null): PaymentStatus
  149. {
  150. return new PaymentStatus(
  151. checkoutId: $session->id,
  152. paid: $session->payment_status === 'paid',
  153. reference: is_string($session->payment_intent) ? $session->payment_intent : null,
  154. amount: $session->amount_total,
  155. account: $account,
  156. );
  157. }
  158. private function client(): StripeClient
  159. {
  160. $secret = (string) config('services.stripe.secret');
  161. if ($secret === '') {
  162. throw new PaymentException('STRIPE_SECRET is missing in the settings file.');
  163. }
  164. return new StripeClient($secret);
  165. }
  166. }