| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173 |
- <?php
-
- namespace App\Billing;
-
- use App\Commerce\Payments\CheckoutLink;
- use App\Commerce\Payments\PaymentException;
- use App\Models\Plan;
- use App\Models\Subscription;
- use App\Models\User;
- use Illuminate\Support\Carbon;
-
- /**
- * Starting, changing and cancelling a merchant's paid plan.
- *
- * Stripe is the source of truth. Our "subscriptions" table is a copy that is refreshed
- * whenever Stripe tells us something (webhook) or we ask it (billing page, after a change).
- */
- class Billing
- {
- public function __construct(private readonly SubscriptionGateway $gateway) {}
-
- /**
- * Send the merchant to a payment page to start the given plan.
- *
- * @throws PaymentException
- */
- public function startCheckout(User $user, Plan $plan, string $successUrl, string $cancelUrl): CheckoutLink
- {
- $subscription = $this->record($user);
-
- if ($subscription->stripe_customer_id === null) {
- $subscription->stripe_customer_id = $this->gateway->createCustomer($user);
- $subscription->save();
- }
-
- return $this->gateway->startCheckout(
- $subscription->stripe_customer_id,
- $this->priceId($plan),
- $successUrl,
- $cancelUrl,
- );
- }
-
- /**
- * The merchant came back from the payment page. Attach the subscription it created.
- * Returns true when a subscription was attached.
- *
- * @throws PaymentException
- */
- public function completeCheckout(User $user, string $checkoutId): bool
- {
- $state = $this->gateway->findByCheckout($checkoutId);
- $subscription = $this->record($user);
-
- // The payment page must belong to this merchant. An id copied from someone else is ignored.
- if ($state === null || $state->customerId !== $subscription->stripe_customer_id) {
- return false;
- }
-
- $this->apply($subscription, $state);
-
- return true;
- }
-
- /**
- * Move to another paid plan.
- *
- * @throws PaymentException
- */
- public function changePlan(User $user, Plan $plan): void
- {
- $subscription = $this->record($user);
-
- if ($subscription->stripe_subscription_id === null) {
- throw new PaymentException('There is no subscription to change.');
- }
-
- $this->apply($subscription, $this->gateway->changePrice($subscription->stripe_subscription_id, $this->priceId($plan)));
- }
-
- /**
- * Cancel at the end of the paid-for period, or undo that.
- *
- * @throws PaymentException
- */
- public function setCancel(User $user, bool $cancel): void
- {
- $subscription = $this->record($user);
-
- if ($subscription->stripe_subscription_id === null) {
- throw new PaymentException('There is no subscription to change.');
- }
-
- $this->apply($subscription, $this->gateway->setCancelAtPeriodEnd($subscription->stripe_subscription_id, $cancel));
- }
-
- /**
- * Ask Stripe for the latest state of this merchant's subscription.
- * A failure is reported and otherwise ignored, so the billing page still opens.
- */
- public function refresh(User $user): void
- {
- $subscription = $user->subscription;
-
- if ($subscription?->stripe_subscription_id === null) {
- return;
- }
-
- try {
- $this->apply($subscription, $this->gateway->find($subscription->stripe_subscription_id));
- } catch (PaymentException $e) {
- report($e);
- }
- }
-
- /**
- * Stripe told us about a subscription through the webhook.
- */
- public function applyFromWebhook(SubscriptionState $state): void
- {
- $subscription = Subscription::query()->where('stripe_customer_id', $state->customerId)->first();
-
- if ($subscription !== null) {
- $this->apply($subscription, $state);
- }
- }
-
- /**
- * Copy what Stripe says into our table.
- */
- private function apply(Subscription $subscription, SubscriptionState $state): void
- {
- $plan = $state->priceId !== null ? Plan::query()->where('stripe_price_id', $state->priceId)->first() : null;
-
- $subscription->stripe_subscription_id = $state->subscriptionId;
- $subscription->status = $state->status;
- $subscription->plan_id = $plan !== null ? $plan->id : $subscription->plan_id;
- $subscription->current_period_end = $state->currentPeriodEnd !== null ? Carbon::createFromTimestamp($state->currentPeriodEnd) : null;
- $subscription->cancel_at_period_end = $state->cancelAtPeriodEnd;
- $subscription->save();
-
- $subscription->user->unsetRelation('subscription');
- }
-
- /**
- * The provider's price id for a plan, creating it at the provider the first time.
- */
- private function priceId(Plan $plan): string
- {
- if ($plan->stripe_price_id === null) {
- $created = $this->gateway->createPrice($plan);
-
- $plan->stripe_product_id = $created['product'];
- $plan->stripe_price_id = $created['price'];
- $plan->save();
- }
-
- return $plan->stripe_price_id;
- }
-
- private function record(User $user): Subscription
- {
- $subscription = $user->subscription ?? new Subscription;
-
- if (! $subscription->exists) {
- $subscription->user_id = $user->id;
- $subscription->save();
- $user->setRelation('subscription', $subscription);
- }
-
- return $subscription;
- }
- }
|