| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175 |
- <?php
-
- namespace App\Billing;
-
- use App\Commerce\Payments\CheckoutLink;
- use App\Commerce\Payments\PaymentException;
- use App\Models\Plan;
- use App\Models\User;
- use Stripe\Exception\ApiErrorException;
- use Stripe\Exception\SignatureVerificationException;
- use Stripe\StripeClient;
- use Stripe\Subscription as StripeSubscription;
- use Stripe\Webhook;
- use UnexpectedValueException;
-
- /**
- * Merchants' monthly subscriptions through Stripe Billing.
- * Stripe hosts the payment page and charges the card every month.
- */
- final class StripeSubscriptionGateway implements SubscriptionGateway
- {
- public function createCustomer(User $user): string
- {
- return $this->call(fn (StripeClient $stripe) => $stripe->customers->create([
- 'email' => $user->email,
- 'name' => $user->name,
- 'metadata' => ['user_id' => (string) $user->id],
- ])->id);
- }
-
- public function createPrice(Plan $plan): array
- {
- return $this->call(function (StripeClient $stripe) use ($plan): array {
- $product = $stripe->products->create([
- 'name' => config('app.name').' '.$plan->name,
- 'metadata' => ['plan' => $plan->key],
- ]);
-
- $price = $stripe->prices->create([
- 'product' => $product->id,
- 'currency' => 'myr',
- 'unit_amount' => $plan->price,
- 'recurring' => ['interval' => 'month'],
- 'metadata' => ['plan' => $plan->key],
- ]);
-
- return ['product' => $product->id, 'price' => $price->id];
- });
- }
-
- public function startCheckout(string $customerId, string $priceId, string $successUrl, string $cancelUrl): CheckoutLink
- {
- return $this->call(function (StripeClient $stripe) use ($customerId, $priceId, $successUrl, $cancelUrl): CheckoutLink {
- $session = $stripe->checkout->sessions->create([
- 'mode' => 'subscription',
- 'customer' => $customerId,
- 'line_items' => [['price' => $priceId, 'quantity' => 1]],
- // Stripe replaces {CHECKOUT_SESSION_ID} with the real id when it sends the merchant back.
- 'success_url' => $successUrl.(str_contains($successUrl, '?') ? '&' : '?').'session_id={CHECKOUT_SESSION_ID}',
- 'cancel_url' => $cancelUrl,
- ]);
-
- if (! is_string($session->url)) {
- throw new PaymentException('Stripe did not return a payment page address.');
- }
-
- return new CheckoutLink($session->id, $session->url);
- });
- }
-
- public function findByCheckout(string $checkoutId): ?SubscriptionState
- {
- $subscriptionId = $this->call(function (StripeClient $stripe) use ($checkoutId): ?string {
- $session = $stripe->checkout->sessions->retrieve($checkoutId);
-
- return $session->status === 'complete' && is_string($session->subscription) ? $session->subscription : null;
- });
-
- return $subscriptionId === null ? null : $this->find($subscriptionId);
- }
-
- public function find(string $subscriptionId): SubscriptionState
- {
- return $this->call(fn (StripeClient $stripe) => $this->state($stripe->subscriptions->retrieve($subscriptionId)));
- }
-
- public function changePrice(string $subscriptionId, string $priceId): SubscriptionState
- {
- return $this->call(function (StripeClient $stripe) use ($subscriptionId, $priceId): SubscriptionState {
- $itemId = $stripe->subscriptions->retrieve($subscriptionId)->items->data[0]->id ?? null;
-
- if (! is_string($itemId)) {
- throw new PaymentException('The subscription has nothing to change.');
- }
-
- return $this->state($stripe->subscriptions->update($subscriptionId, [
- 'items' => [['id' => $itemId, 'price' => $priceId]],
- // Charge or credit the difference for the rest of the month.
- 'proration_behavior' => 'create_prorations',
- // Changing plan also undoes a pending cancellation.
- 'cancel_at_period_end' => false,
- ]));
- });
- }
-
- public function setCancelAtPeriodEnd(string $subscriptionId, bool $cancel): SubscriptionState
- {
- return $this->call(fn (StripeClient $stripe) => $this->state(
- $stripe->subscriptions->update($subscriptionId, ['cancel_at_period_end' => $cancel]),
- ));
- }
-
- public function readWebhook(string $payload, string $signature): ?SubscriptionState
- {
- $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);
- }
-
- $subscription = $event->data->object ?? null;
-
- if (! str_starts_with($event->type, 'customer.subscription.') || ! $subscription instanceof StripeSubscription) {
- return null;
- }
-
- return $this->state($subscription);
- }
-
- private function state(StripeSubscription $subscription): SubscriptionState
- {
- $item = $subscription->items->data[0] ?? null;
-
- // Newer Stripe versions keep the period end on the item, older ones on the subscription.
- $periodEnd = $item->current_period_end ?? $subscription['current_period_end'] ?? null;
-
- return new SubscriptionState(
- subscriptionId: $subscription->id,
- customerId: is_string($subscription->customer) ? $subscription->customer : $subscription->customer->id,
- status: (string) $subscription->status,
- priceId: $item?->price?->id,
- currentPeriodEnd: is_int($periodEnd) ? $periodEnd : null,
- cancelAtPeriodEnd: (bool) $subscription->cancel_at_period_end,
- );
- }
-
- /**
- * Run one Stripe request, turning Stripe's errors into our own.
- *
- * @template T
- *
- * @param callable(StripeClient): T $request
- * @return T
- */
- private function call(callable $request): mixed
- {
- $secret = (string) config('services.stripe.secret');
-
- if ($secret === '') {
- throw new PaymentException('STRIPE_SECRET is missing in the settings file.');
- }
-
- try {
- return $request(new StripeClient($secret));
- } catch (ApiErrorException $e) {
- throw new PaymentException('Stripe request failed: '.$e->getMessage(), 0, $e);
- }
- }
- }
|