AI store generator for ecommerce, Malaysia first. Laravel 13 + React + TypeScript.
Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173
  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\Subscription;
  7. use App\Models\User;
  8. use Illuminate\Support\Carbon;
  9. /**
  10. * Starting, changing and cancelling a merchant's paid plan.
  11. *
  12. * Stripe is the source of truth. Our "subscriptions" table is a copy that is refreshed
  13. * whenever Stripe tells us something (webhook) or we ask it (billing page, after a change).
  14. */
  15. class Billing
  16. {
  17. public function __construct(private readonly SubscriptionGateway $gateway) {}
  18. /**
  19. * Send the merchant to a payment page to start the given plan.
  20. *
  21. * @throws PaymentException
  22. */
  23. public function startCheckout(User $user, Plan $plan, string $successUrl, string $cancelUrl): CheckoutLink
  24. {
  25. $subscription = $this->record($user);
  26. if ($subscription->stripe_customer_id === null) {
  27. $subscription->stripe_customer_id = $this->gateway->createCustomer($user);
  28. $subscription->save();
  29. }
  30. return $this->gateway->startCheckout(
  31. $subscription->stripe_customer_id,
  32. $this->priceId($plan),
  33. $successUrl,
  34. $cancelUrl,
  35. );
  36. }
  37. /**
  38. * The merchant came back from the payment page. Attach the subscription it created.
  39. * Returns true when a subscription was attached.
  40. *
  41. * @throws PaymentException
  42. */
  43. public function completeCheckout(User $user, string $checkoutId): bool
  44. {
  45. $state = $this->gateway->findByCheckout($checkoutId);
  46. $subscription = $this->record($user);
  47. // The payment page must belong to this merchant. An id copied from someone else is ignored.
  48. if ($state === null || $state->customerId !== $subscription->stripe_customer_id) {
  49. return false;
  50. }
  51. $this->apply($subscription, $state);
  52. return true;
  53. }
  54. /**
  55. * Move to another paid plan.
  56. *
  57. * @throws PaymentException
  58. */
  59. public function changePlan(User $user, Plan $plan): void
  60. {
  61. $subscription = $this->record($user);
  62. if ($subscription->stripe_subscription_id === null) {
  63. throw new PaymentException('There is no subscription to change.');
  64. }
  65. $this->apply($subscription, $this->gateway->changePrice($subscription->stripe_subscription_id, $this->priceId($plan)));
  66. }
  67. /**
  68. * Cancel at the end of the paid-for period, or undo that.
  69. *
  70. * @throws PaymentException
  71. */
  72. public function setCancel(User $user, bool $cancel): void
  73. {
  74. $subscription = $this->record($user);
  75. if ($subscription->stripe_subscription_id === null) {
  76. throw new PaymentException('There is no subscription to change.');
  77. }
  78. $this->apply($subscription, $this->gateway->setCancelAtPeriodEnd($subscription->stripe_subscription_id, $cancel));
  79. }
  80. /**
  81. * Ask Stripe for the latest state of this merchant's subscription.
  82. * A failure is reported and otherwise ignored, so the billing page still opens.
  83. */
  84. public function refresh(User $user): void
  85. {
  86. $subscription = $user->subscription;
  87. if ($subscription?->stripe_subscription_id === null) {
  88. return;
  89. }
  90. try {
  91. $this->apply($subscription, $this->gateway->find($subscription->stripe_subscription_id));
  92. } catch (PaymentException $e) {
  93. report($e);
  94. }
  95. }
  96. /**
  97. * Stripe told us about a subscription through the webhook.
  98. */
  99. public function applyFromWebhook(SubscriptionState $state): void
  100. {
  101. $subscription = Subscription::query()->where('stripe_customer_id', $state->customerId)->first();
  102. if ($subscription !== null) {
  103. $this->apply($subscription, $state);
  104. }
  105. }
  106. /**
  107. * Copy what Stripe says into our table.
  108. */
  109. private function apply(Subscription $subscription, SubscriptionState $state): void
  110. {
  111. $plan = $state->priceId !== null ? Plan::query()->where('stripe_price_id', $state->priceId)->first() : null;
  112. $subscription->stripe_subscription_id = $state->subscriptionId;
  113. $subscription->status = $state->status;
  114. $subscription->plan_id = $plan !== null ? $plan->id : $subscription->plan_id;
  115. $subscription->current_period_end = $state->currentPeriodEnd !== null ? Carbon::createFromTimestamp($state->currentPeriodEnd) : null;
  116. $subscription->cancel_at_period_end = $state->cancelAtPeriodEnd;
  117. $subscription->save();
  118. $subscription->user->unsetRelation('subscription');
  119. }
  120. /**
  121. * The provider's price id for a plan, creating it at the provider the first time.
  122. */
  123. private function priceId(Plan $plan): string
  124. {
  125. if ($plan->stripe_price_id === null) {
  126. $created = $this->gateway->createPrice($plan);
  127. $plan->stripe_product_id = $created['product'];
  128. $plan->stripe_price_id = $created['price'];
  129. $plan->save();
  130. }
  131. return $plan->stripe_price_id;
  132. }
  133. private function record(User $user): Subscription
  134. {
  135. $subscription = $user->subscription ?? new Subscription;
  136. if (! $subscription->exists) {
  137. $subscription->user_id = $user->id;
  138. $subscription->save();
  139. $user->setRelation('subscription', $subscription);
  140. }
  141. return $subscription;
  142. }
  143. }