| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151 |
- <?php
-
- namespace App\Commerce\Payments;
-
- use App\Models\Order;
- use App\Models\OrderItem;
- use Stripe\Checkout\Session;
- use Stripe\Exception\ApiErrorException;
- use Stripe\Exception\SignatureVerificationException;
- use Stripe\StripeClient;
- use Stripe\Webhook;
- use UnexpectedValueException;
-
- /**
- * Payments through Stripe Checkout: Stripe hosts the payment page, so card details never touch our server.
- *
- * No payment method list is sent, so Stripe shows whatever is switched on in the Stripe dashboard
- * for Malaysian Ringgit (cards, FPX, GrabPay and so on).
- */
- final class StripeGateway implements PaymentGateway
- {
- public function name(): string
- {
- return 'stripe';
- }
-
- public function startCheckout(Order $order, string $successUrl, string $cancelUrl): CheckoutLink
- {
- try {
- $session = $this->client()->checkout->sessions->create([
- 'mode' => 'payment',
- 'customer_email' => $order->customer_email,
- 'client_reference_id' => (string) $order->id,
- 'metadata' => ['order_id' => (string) $order->id, 'store_id' => (string) $order->store_id],
- 'line_items' => $order->items->map(fn (OrderItem $item) => [
- 'quantity' => $item->quantity,
- 'price_data' => [
- 'currency' => strtolower($order->currency),
- 'unit_amount' => $item->unit_price,
- 'product_data' => ['name' => $item->name],
- ],
- ])->values()->all(),
- // A one-off Stripe coupon for exactly the discount, so Stripe's page shows the code and the saving.
- ...($order->discount_total > 0 ? ['discounts' => [['coupon' => $this->couponFor($order)]]] : []),
- // Shipping is shown on Stripe's page as its own line, so the shopper sees what they pay for.
- 'shipping_options' => [[
- 'shipping_rate_data' => [
- 'type' => 'fixed_amount',
- 'fixed_amount' => ['amount' => $order->shipping_total, 'currency' => strtolower($order->currency)],
- 'display_name' => $this->shippingLabel($order),
- ],
- ]],
- // Stripe replaces {CHECKOUT_SESSION_ID} with the real id when it sends the shopper back.
- 'success_url' => $successUrl.(str_contains($successUrl, '?') ? '&' : '?').'session_id={CHECKOUT_SESSION_ID}',
- 'cancel_url' => $cancelUrl,
- ]);
- } catch (ApiErrorException $e) {
- throw new PaymentException('Stripe could not create the payment page: '.$e->getMessage(), 0, $e);
- }
-
- if (! is_string($session->url)) {
- throw new PaymentException('Stripe did not return a payment page address.');
- }
-
- return new CheckoutLink($session->id, $session->url);
- }
-
- /**
- * A coupon that can be used once, worth exactly this order's discount.
- * Stripe takes it off the products only, never off shipping, which matches our own rule.
- *
- * @throws ApiErrorException
- */
- private function couponFor(Order $order): string
- {
- return $this->client()->coupons->create([
- 'amount_off' => $order->discount_total,
- 'currency' => strtolower($order->currency),
- 'duration' => 'once',
- 'max_redemptions' => 1,
- 'name' => (string) $order->discount_code,
- 'metadata' => ['order_id' => (string) $order->id],
- ])->id;
- }
-
- private function shippingLabel(Order $order): string
- {
- $malay = $order->store->language->value === 'ms';
-
- if ($order->shipping_total === 0) {
- return $malay ? 'Penghantaran percuma' : 'Free shipping';
- }
-
- return $malay ? 'Penghantaran' : 'Shipping';
- }
-
- public function checkPayment(string $checkoutId): PaymentStatus
- {
- try {
- return $this->status($this->client()->checkout->sessions->retrieve($checkoutId));
- } catch (ApiErrorException $e) {
- throw new PaymentException('Stripe could not find the payment: '.$e->getMessage(), 0, $e);
- }
- }
-
- public function readWebhook(string $payload, string $signature): ?PaymentStatus
- {
- $secret = (string) config('services.stripe.webhook_secret');
-
- if ($secret === '') {
- throw new PaymentException('STRIPE_WEBHOOK_SECRET is not set.');
- }
-
- try {
- $event = Webhook::constructEvent($payload, $signature, $secret);
- } catch (SignatureVerificationException|UnexpectedValueException $e) {
- throw new PaymentException('The webhook message is not from Stripe.', 0, $e);
- }
-
- $session = $event->data->object ?? null;
-
- // "async_payment_succeeded" covers methods such as FPX that confirm a little later.
- if (! in_array($event->type, ['checkout.session.completed', 'checkout.session.async_payment_succeeded'], true)
- || ! $session instanceof Session) {
- return null;
- }
-
- return $this->status($session);
- }
-
- private function status(Session $session): PaymentStatus
- {
- return new PaymentStatus(
- checkoutId: $session->id,
- paid: $session->payment_status === 'paid',
- reference: is_string($session->payment_intent) ? $session->payment_intent : null,
- amount: $session->amount_total,
- );
- }
-
- private function client(): StripeClient
- {
- $secret = (string) config('services.stripe.secret');
-
- if ($secret === '') {
- throw new PaymentException('STRIPE_SECRET is missing in the settings file.');
- }
-
- return new StripeClient($secret);
- }
- }
|