mirror of
https://github.com/yusufipk/OpenFrame.git
synced 2026-09-11 09:36:08 +00:00
fix(billing): prevent duplicate subscriptions and make webhook sync authoritative
A Stripe customer can own several subscriptions. Two defects let that happen
and corrupt the user's billing state:
1. Checkout allowed a fresh subscription whenever the user was not ACTIVE/
TRIALING, so a PAST_DUE user started a brand-new subscription (Stripe
Checkout always creates one) instead of recovering the existing one.
Add hasRecoverableSubscription() (ACTIVE/TRIALING/PAST_DUE/UNPAID/
INCOMPLETE); block checkout and route these users to the billing portal
('Update Payment Method') both in the API guard and the settings UI.
2. Subscription webhooks trusted the event's single subscription, so an old
subscription's deletion could clobber a newer active one (marking the user
CANCELED / No access). Every subscription event now re-derives state from
the full set of the customer's Stripe subscriptions via
syncStripeCustomerSubscriptions() + selectAuthoritativeSubscription(),
making the sync order-independent and self-healing.
This commit is contained in:
@@ -46,8 +46,15 @@ export async function POST(request: NextRequest) {
|
||||
}
|
||||
|
||||
const checkoutState = await getStripeCheckoutState(session.user.id);
|
||||
if (checkoutState.hasActiveSubscription) {
|
||||
return apiErrors.badRequest('An active subscription already exists for this account');
|
||||
// Block a fresh checkout whenever the customer already has a live subscription
|
||||
// (active/trialing OR a recoverable one like past_due/unpaid/incomplete).
|
||||
// Stripe Checkout in subscription mode always creates a NEW subscription, so
|
||||
// letting a past_due user through here duplicates their subscription instead
|
||||
// of recovering it. They should manage the existing one via the billing portal.
|
||||
if (checkoutState.hasRecoverableSubscription) {
|
||||
return apiErrors.badRequest(
|
||||
'A subscription already exists for this account. Manage it from the billing portal.'
|
||||
);
|
||||
}
|
||||
|
||||
const stripe = getStripe();
|
||||
|
||||
Reference in New Issue
Block a user