AI store generator for ecommerce, Malaysia first. Laravel 13 + React + TypeScript.
Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

StripeSubscriptionGateway.php 6.6KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175
  1. <?php
  2. namespace App\Billing;
  3. use App\Commerce\Payments\CheckoutLink;
  4. use App\Commerce\Payments\PaymentException;
  5. use App\Models\Plan;
  6. use App\Models\User;
  7. use Stripe\Exception\ApiErrorException;
  8. use Stripe\Exception\SignatureVerificationException;
  9. use Stripe\StripeClient;
  10. use Stripe\Subscription as StripeSubscription;
  11. use Stripe\Webhook;
  12. use UnexpectedValueException;
  13. /**
  14. * Merchants' monthly subscriptions through Stripe Billing.
  15. * Stripe hosts the payment page and charges the card every month.
  16. */
  17. final class StripeSubscriptionGateway implements SubscriptionGateway
  18. {
  19. public function createCustomer(User $user): string
  20. {
  21. return $this->call(fn (StripeClient $stripe) => $stripe->customers->create([
  22. 'email' => $user->email,
  23. 'name' => $user->name,
  24. 'metadata' => ['user_id' => (string) $user->id],
  25. ])->id);
  26. }
  27. public function createPrice(Plan $plan): array
  28. {
  29. return $this->call(function (StripeClient $stripe) use ($plan): array {
  30. $product = $stripe->products->create([
  31. 'name' => config('app.name').' '.$plan->name,
  32. 'metadata' => ['plan' => $plan->key],
  33. ]);
  34. $price = $stripe->prices->create([
  35. 'product' => $product->id,
  36. 'currency' => 'myr',
  37. 'unit_amount' => $plan->price,
  38. 'recurring' => ['interval' => 'month'],
  39. 'metadata' => ['plan' => $plan->key],
  40. ]);
  41. return ['product' => $product->id, 'price' => $price->id];
  42. });
  43. }
  44. public function startCheckout(string $customerId, string $priceId, string $successUrl, string $cancelUrl): CheckoutLink
  45. {
  46. return $this->call(function (StripeClient $stripe) use ($customerId, $priceId, $successUrl, $cancelUrl): CheckoutLink {
  47. $session = $stripe->checkout->sessions->create([
  48. 'mode' => 'subscription',
  49. 'customer' => $customerId,
  50. 'line_items' => [['price' => $priceId, 'quantity' => 1]],
  51. // Stripe replaces {CHECKOUT_SESSION_ID} with the real id when it sends the merchant back.
  52. 'success_url' => $successUrl.(str_contains($successUrl, '?') ? '&' : '?').'session_id={CHECKOUT_SESSION_ID}',
  53. 'cancel_url' => $cancelUrl,
  54. ]);
  55. if (! is_string($session->url)) {
  56. throw new PaymentException('Stripe did not return a payment page address.');
  57. }
  58. return new CheckoutLink($session->id, $session->url);
  59. });
  60. }
  61. public function findByCheckout(string $checkoutId): ?SubscriptionState
  62. {
  63. $subscriptionId = $this->call(function (StripeClient $stripe) use ($checkoutId): ?string {
  64. $session = $stripe->checkout->sessions->retrieve($checkoutId);
  65. return $session->status === 'complete' && is_string($session->subscription) ? $session->subscription : null;
  66. });
  67. return $subscriptionId === null ? null : $this->find($subscriptionId);
  68. }
  69. public function find(string $subscriptionId): SubscriptionState
  70. {
  71. return $this->call(fn (StripeClient $stripe) => $this->state($stripe->subscriptions->retrieve($subscriptionId)));
  72. }
  73. public function changePrice(string $subscriptionId, string $priceId): SubscriptionState
  74. {
  75. return $this->call(function (StripeClient $stripe) use ($subscriptionId, $priceId): SubscriptionState {
  76. $itemId = $stripe->subscriptions->retrieve($subscriptionId)->items->data[0]->id ?? null;
  77. if (! is_string($itemId)) {
  78. throw new PaymentException('The subscription has nothing to change.');
  79. }
  80. return $this->state($stripe->subscriptions->update($subscriptionId, [
  81. 'items' => [['id' => $itemId, 'price' => $priceId]],
  82. // Charge or credit the difference for the rest of the month.
  83. 'proration_behavior' => 'create_prorations',
  84. // Changing plan also undoes a pending cancellation.
  85. 'cancel_at_period_end' => false,
  86. ]));
  87. });
  88. }
  89. public function setCancelAtPeriodEnd(string $subscriptionId, bool $cancel): SubscriptionState
  90. {
  91. return $this->call(fn (StripeClient $stripe) => $this->state(
  92. $stripe->subscriptions->update($subscriptionId, ['cancel_at_period_end' => $cancel]),
  93. ));
  94. }
  95. public function readWebhook(string $payload, string $signature): ?SubscriptionState
  96. {
  97. $secret = (string) config('services.stripe.webhook_secret');
  98. if ($secret === '') {
  99. throw new PaymentException('STRIPE_WEBHOOK_SECRET is not set.');
  100. }
  101. try {
  102. $event = Webhook::constructEvent($payload, $signature, $secret);
  103. } catch (SignatureVerificationException|UnexpectedValueException $e) {
  104. throw new PaymentException('The webhook message is not from Stripe.', 0, $e);
  105. }
  106. $subscription = $event->data->object ?? null;
  107. if (! str_starts_with($event->type, 'customer.subscription.') || ! $subscription instanceof StripeSubscription) {
  108. return null;
  109. }
  110. return $this->state($subscription);
  111. }
  112. private function state(StripeSubscription $subscription): SubscriptionState
  113. {
  114. $item = $subscription->items->data[0] ?? null;
  115. // Newer Stripe versions keep the period end on the item, older ones on the subscription.
  116. $periodEnd = $item->current_period_end ?? $subscription['current_period_end'] ?? null;
  117. return new SubscriptionState(
  118. subscriptionId: $subscription->id,
  119. customerId: is_string($subscription->customer) ? $subscription->customer : $subscription->customer->id,
  120. status: (string) $subscription->status,
  121. priceId: $item?->price?->id,
  122. currentPeriodEnd: is_int($periodEnd) ? $periodEnd : null,
  123. cancelAtPeriodEnd: (bool) $subscription->cancel_at_period_end,
  124. );
  125. }
  126. /**
  127. * Run one Stripe request, turning Stripe's errors into our own.
  128. *
  129. * @template T
  130. *
  131. * @param callable(StripeClient): T $request
  132. * @return T
  133. */
  134. private function call(callable $request): mixed
  135. {
  136. $secret = (string) config('services.stripe.secret');
  137. if ($secret === '') {
  138. throw new PaymentException('STRIPE_SECRET is missing in the settings file.');
  139. }
  140. try {
  141. return $request(new StripeClient($secret));
  142. } catch (ApiErrorException $e) {
  143. throw new PaymentException('Stripe request failed: '.$e->getMessage(), 0, $e);
  144. }
  145. }
  146. }