Files
OpenFrame/app/api/billing/checkout/route.ts
T
yusufipk 7ca5abd041 feat(analytics): record where paying customers actually came from
Adds first-party acquisition attribution and a sixteen-event funnel, written to
this deployment's own database and read back on /admin/growth. Nothing is sent
anywhere else, and the whole subsystem is off unless OPENFRAME_ENABLE_ANALYTICS
is set, so a self-hosted instance carries the tables empty and pays nothing.

The proxy gives a visitor an anonymous id and stores what brought them in two
first-party cookies; signup copies that onto the account and claims the events
the visitor produced before they had one, which is what joins the two halves of
the funnel. Recording happens where each step actually happens rather than in
the browser: an ad blocker cannot undercount landing views, and blocking rates
differ by channel, so an undercounted denominator would have made GitHub traffic
look like it converts better than it does.

Every event carries a dedupe key on a UNIQUE column, so "recorded exactly once"
is a property of the schema rather than of fifteen call sites. Subscription
events are derived by comparing the row being overwritten with the row being
written inside the existing Stripe sync, which makes them order-independent and
replay-safe.

The scoreboard reports step-to-step conversion with the denominator beside it,
and splits by source over a rolling 28-day window rather than a week: at this
volume a weekly per-source cell holds single digits, and a percentage computed
from three visits reads exactly as confidently as one computed from three
hundred.

"How did you hear about us?" is asked on the first onboarding screen, not on the
registration form. The number being measured is the signup conversion rate, and
a question added to that form would move it.
2026-08-01 20:00:27 +03:00

104 lines
3.7 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';
import { eventKey, recordEvent } from '@/lib/analytics/record';
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');
}
// Keyed on the Stripe session, so an abandoned checkout followed by a second
// attempt counts twice. That is the intent: the gap between checkouts started
// and subscriptions started is the number worth watching.
await recordEvent({
name: 'CHECKOUT_STARTED',
dedupeKey: eventKey('CHECKOUT_STARTED', checkoutSession.id),
userId: session.user.id,
});
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');
}
}