mirror of
https://github.com/yusufipk/OpenFrame.git
synced 2026-09-11 09:36:08 +00:00
The Stripe client was built without an apiVersion, so the SDK followed whatever version it shipped with. Two fields moved in the Basil API version: the billing period went from the subscription onto its items, and the invoice link to its subscription went under parent.subscription_details. Both reads returned undefined without failing, which left stripeCurrentPeriodEnd null for every subscriber and left the app with no invoice handling at all. A customer whose card failed saw nothing about the invoice that was still retrying, and a cancellation did nothing to stop those retries. - Pin the API version, with `satisfies` so an SDK bump is a compile error here before it is a null read in production. - Read the period off subscription items and the subscription off invoice parents, keeping the legacy fields as a fallback for older payloads. - Handle invoice.paid, invoice.payment_failed, invoice.voided and invoice.marked_uncollectible through the existing customer-wide resync, so the mirror reflects payment health during dunning rather than after it. - Add an in-app cancellation route: at period end when the subscription is paid, immediately plus voiding the open invoices when it is not, because cancelling alone does not stop collection on an invoice already issued. - Ask Stripe, not just the local mirror, before opening checkout. - Show the open invoice, the retry date and a payment-method-update shortcut in settings, and put a confirmation in front of cancellation. Access no longer rests on the reported period alone. Stripe advances the period when it issues the renewal invoice, paid or not, and the period survives cancellation, so once the period field started being read correctly that check would have handed a full free month to anyone whose renewal failed, and the new cancel route would have let them void the invoice and keep the month. Access now follows the subscription status, billingAccessEndedAt is enforced as a hard cutoff in both hasBillingAccess and the query that mirrors it, and a subscription behind on payment keeps access for Stripe's retry window rather than for the period it never paid for.
86 lines
3.1 KiB
TypeScript
86 lines
3.1 KiB
TypeScript
import { NextRequest } from 'next/server';
|
|
import type Stripe from 'stripe';
|
|
import { syncStripeCustomerSubscriptions } from '@/lib/billing';
|
|
import { getStripe, getStripeWebhookSecret } from '@/lib/stripe';
|
|
import { logError } from '@/lib/logger';
|
|
|
|
export const runtime = 'nodejs';
|
|
|
|
function getCustomerId(
|
|
customer: string | Stripe.Customer | Stripe.DeletedCustomer | null
|
|
): string | null {
|
|
if (!customer) return null;
|
|
return typeof customer === 'string' ? customer : customer.id;
|
|
}
|
|
|
|
export async function POST(request: NextRequest) {
|
|
const signature = request.headers.get('stripe-signature');
|
|
if (!signature) {
|
|
return new Response('Missing Stripe signature', { status: 400 });
|
|
}
|
|
|
|
let event: Stripe.Event;
|
|
|
|
try {
|
|
const stripe = getStripe();
|
|
const body = await request.text();
|
|
event = stripe.webhooks.constructEvent(body, signature, getStripeWebhookSecret());
|
|
} catch (error) {
|
|
logError('Failed to verify Stripe webhook:', error);
|
|
return new Response('Invalid webhook signature', { status: 400 });
|
|
}
|
|
|
|
try {
|
|
// Every subscription-related event re-derives the user's state from the
|
|
// full set of the customer's Stripe subscriptions, so a stale event (e.g.
|
|
// an old subscription being deleted) can never clobber a newer active one.
|
|
switch (event.type) {
|
|
case 'checkout.session.completed': {
|
|
const session = event.data.object as Stripe.Checkout.Session;
|
|
if (session.mode === 'subscription') {
|
|
const customerId = getCustomerId(session.customer);
|
|
if (customerId) {
|
|
await syncStripeCustomerSubscriptions(customerId);
|
|
}
|
|
}
|
|
break;
|
|
}
|
|
case 'customer.subscription.created':
|
|
case 'customer.subscription.updated':
|
|
case 'customer.subscription.deleted': {
|
|
const subscription = event.data.object as Stripe.Subscription;
|
|
const customerId = getCustomerId(subscription.customer);
|
|
if (customerId) {
|
|
await syncStripeCustomerSubscriptions(customerId);
|
|
}
|
|
break;
|
|
}
|
|
// Invoice events carry the payment health of a subscription earlier and more
|
|
// reliably than the subscription events alone. Without them a customer whose card
|
|
// failed keeps the mirror of a healthy subscription until Stripe eventually gives
|
|
// up, which is the whole dunning window spent showing them the wrong state.
|
|
case 'invoice.paid':
|
|
case 'invoice.payment_failed':
|
|
case 'invoice.voided':
|
|
case 'invoice.marked_uncollectible': {
|
|
const invoice = event.data.object as Stripe.Invoice;
|
|
const customerId = getCustomerId(invoice.customer);
|
|
if (customerId) {
|
|
await syncStripeCustomerSubscriptions(customerId);
|
|
}
|
|
break;
|
|
}
|
|
default:
|
|
break;
|
|
}
|
|
|
|
return new Response(JSON.stringify({ received: true }), {
|
|
status: 200,
|
|
headers: { 'Content-Type': 'application/json' },
|
|
});
|
|
} catch (error) {
|
|
logError('Failed to process Stripe webhook:', error);
|
|
return new Response('Webhook processing failed', { status: 500 });
|
|
}
|
|
}
|