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); } } }