Files
OpenFrame/app/api/billing/checkout/route.ts
T
yusufipk 0faa4b4e2a 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.
2026-07-25 14:22:32 +07:00

94 lines
3.2 KiB
TypeScript

import { NextRequest } from 'next/server';
import { auth } from '@/lib/auth';
import { apiErrors, successResponse, withCacheControl } from '@/lib/api-response';
import {
DEFAULT_TRIAL_PERIOD_DAYS,
getOrCreateStripeCustomerId,
getStripeCheckoutState,
} from '@/lib/billing';
import { rateLimit } from '@/lib/rate-limit';
import { isStripeFeatureEnabled } from '@/lib/feature-flags';
import { getStripe, getStripePriceId, isStripeConfigured } from '@/lib/stripe';
import { isTrustedSameOriginRequest } from '@/lib/request-origin';
import { logError } from '@/lib/logger';
function getAppOrigin(request: NextRequest) {
if (isTrustedSameOriginRequest(request)) {
const origin = request.headers.get('origin');
if (origin) {
return new URL(origin).origin;
}
}
return request.nextUrl.origin;
}
export async function POST(request: NextRequest) {
try {
const limited = await rateLimit(request, 'mutate');
if (limited) return limited;
if (!isTrustedSameOriginRequest(request)) {
return apiErrors.forbidden('Invalid request origin');
}
const session = await auth();
if (!session?.user?.id) {
return apiErrors.unauthorized();
}
if (!isStripeFeatureEnabled()) {
return apiErrors.badRequest('Stripe billing is disabled by this host');
}
if (!isStripeConfigured()) {
return apiErrors.internalError('Stripe billing is not configured');
}
const checkoutState = await getStripeCheckoutState(session.user.id);
// 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();
const priceId = getStripePriceId();
const customerId = await getOrCreateStripeCustomerId(session.user.id);
const appOrigin = getAppOrigin(request);
const checkoutSession = await stripe.checkout.sessions.create({
mode: 'subscription',
customer: customerId,
line_items: [{ price: priceId, quantity: 1 }],
allow_promotion_codes: true,
success_url: `${appOrigin}/settings?billing=success`,
cancel_url: `${appOrigin}/settings?billing=canceled`,
metadata: {
userId: session.user.id,
},
subscription_data: {
metadata: {
userId: session.user.id,
},
...(checkoutState.isTrialEligible ? { trial_period_days: DEFAULT_TRIAL_PERIOD_DAYS } : {}),
},
});
if (!checkoutSession.url) {
throw new Error('Stripe did not return a checkout URL');
}
const response = successResponse({ url: checkoutSession.url });
return withCacheControl(response, 'private, no-store');
} catch (error) {
logError('Error creating Stripe checkout session:', error);
return apiErrors.internalError('Failed to start checkout');
}
}