feat(billing): implement robust in-app subscription cancellation & fix CI/CD socket port typo

This commit is contained in:
Antigravity
2026-05-28 20:50:11 +00:00
parent f5608372dc
commit 457c6fa626
22 changed files with 656 additions and 460 deletions

View File

@@ -0,0 +1,30 @@
import { NextRequest, NextResponse } from 'next/server';
import { auth } from '@/auth';
import { cancelSubscription } from '@/lib/billing/cancel-subscription';
export const dynamic = 'force-dynamic';
export async function POST(req: NextRequest) {
const session = await auth();
if (!session?.user?.id) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
}
const userId = session.user.id;
try {
const result = await cancelSubscription(userId);
if (!result.success) {
const isNotFound = result.error === 'No active subscription found';
return NextResponse.json(
{ error: result.error },
{ status: isNotFound ? 404 : 400 }
);
}
return NextResponse.json({ success: true });
} catch (error) {
console.error('[billing/cancel] Route handler crash:', error);
return NextResponse.json({ error: 'Failed to cancel subscription' }, { status: 500 });
}
}

View File

@@ -31,21 +31,41 @@ export async function POST(req: NextRequest) {
const subscription = await prisma.subscription.findUnique({ where: { userId } });
let customerId = subscription?.stripeCustomerId ?? undefined;
if (customerId && customerId.startsWith('cus_mock')) {
customerId = undefined;
}
if (!customerId) {
const customer = await stripe.customers.create({
email: userEmail,
metadata: { userId },
});
customerId = customer.id;
// Update DB to save the real Stripe customer ID
await prisma.subscription.upsert({
where: { userId },
update: { stripeCustomerId: customerId },
create: {
userId,
stripeCustomerId: customerId,
tier: 'BASIC',
status: 'ACTIVE',
currentPeriodStart: new Date(),
currentPeriodEnd: new Date(Date.now() + 30 * 24 * 3600 * 1000), // temp basic dates
}
});
}
const origin = req.headers.get('origin') ?? process.env.NEXTAUTH_URL ?? 'http://localhost:3000';
const host = req.headers.get('x-forwarded-host') ?? req.headers.get('host') ?? 'localhost:3000';
const proto = req.headers.get('x-forwarded-proto') ?? 'http';
const origin = `${proto}://${host}`;
const sessionParams = {
customer: customerId,
mode: 'subscription' as const,
line_items: [{ price: priceId, quantity: 1 }],
ui_mode: 'embedded',
ui_mode: 'embedded_page',
return_url: `${origin}/settings/billing?session_id={CHECKOUT_SESSION_ID}`,
metadata: { userId, tier },
subscription_data: { metadata: { userId, tier } },

View File

@@ -3,6 +3,8 @@ import { auth } from '@/auth';
import { stripe } from '@/lib/stripe';
import { prisma } from '@/lib/prisma';
export const dynamic = 'force-dynamic';
export async function GET(req: NextRequest) {
const session = await auth();
if (!session?.user?.id) {

View File

@@ -11,13 +11,21 @@ export async function POST(req: NextRequest) {
const userId = session.user.id;
let action = 'portal';
try {
const body = await req.json();
if (body?.action) action = body.action;
} catch (_) {}
try {
const subscription = await prisma.subscription.findUnique({ where: { userId } });
if (!subscription?.stripeCustomerId) {
return NextResponse.json({ error: 'No active subscription found' }, { status: 404 });
}
const origin = req.headers.get('origin') ?? process.env.NEXTAUTH_URL ?? 'http://localhost:3000';
const host = req.headers.get('x-forwarded-host') ?? req.headers.get('host') ?? 'localhost:3000';
const proto = req.headers.get('x-forwarded-proto') ?? 'http';
const origin = `${proto}://${host}`;
const portalSession = await stripe.billingPortal.sessions.create({
customer: subscription.stripeCustomerId,

View File

@@ -1,20 +1,79 @@
import { NextResponse } from 'next/server';
import { NextRequest, NextResponse } from 'next/server';
import { auth } from '@/auth';
import { getUserInfo, getEffectiveTier } from '@/lib/entitlements';
import { stripe } from '@/lib/stripe';
import type Stripe from 'stripe';
import { priceIdToTier } from '@/lib/billing/stripe-prices';
export async function GET() {
export const dynamic = 'force-dynamic';
export async function GET(req: NextRequest) {
const session = await auth();
if (!session?.user?.id) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
}
const userId = session.user.id;
const { prisma } = await import('@/lib/prisma');
const sessionId = req.nextUrl.searchParams.get('session_id');
if (sessionId && sessionId.startsWith('cs_')) {
try {
const checkoutSession = await stripe.checkout.sessions.retrieve(sessionId);
if (checkoutSession.subscription && checkoutSession.status === 'complete') {
const subId = typeof checkoutSession.subscription === 'string'
? checkoutSession.subscription
: (checkoutSession.subscription as any).id;
const sub = await stripe.subscriptions.retrieve(subId);
const priceId = sub.items.data[0].price.id;
const tier = priceIdToTier(priceId) || (checkoutSession.metadata?.tier as any) || 'PRO';
const currentPeriodStartTimestamp =
sub.current_period_start ??
sub.items?.data?.[0]?.current_period_start ??
sub.start_date ??
Math.floor(Date.now() / 1000);
const currentPeriodEndTimestamp =
sub.current_period_end ??
sub.items?.data?.[0]?.current_period_end ??
(currentPeriodStartTimestamp + 30 * 24 * 3600);
await prisma.subscription.upsert({
where: { userId },
update: {
tier,
status: 'ACTIVE',
stripeCustomerId: checkoutSession.customer as string,
stripeSubscriptionId: sub.id,
stripePriceId: priceId,
currentPeriodStart: new Date(currentPeriodStartTimestamp * 1000),
currentPeriodEnd: new Date(currentPeriodEndTimestamp * 1000),
canceledAt: sub.canceled_at ? new Date(sub.canceled_at * 1000) : null,
cancelAtPeriodEnd: sub.cancel_at_period_end,
},
create: {
userId,
tier,
status: 'ACTIVE',
stripeCustomerId: checkoutSession.customer as string,
stripeSubscriptionId: sub.id,
stripePriceId: priceId,
currentPeriodStart: new Date(currentPeriodStartTimestamp * 1000),
currentPeriodEnd: new Date(currentPeriodEndTimestamp * 1000),
},
});
}
} catch (err) {
console.error('[billing/status] Failed to sync Stripe session:', err);
}
}
try {
const { tier, status, currentPeriodEnd } = await getUserInfo(userId);
const effectiveTier = await getEffectiveTier(userId);
const { prisma } = await import('@/lib/prisma');
const subscription = await prisma.subscription.findUnique({ where: { userId } });
return NextResponse.json({

View File

@@ -2,6 +2,8 @@ import { NextResponse } from 'next/server';
import { auth } from '@/auth';
import { getUserQuotas, getEffectiveTier } from '@/lib/entitlements';
export const dynamic = 'force-dynamic';
export async function GET() {
const session = await auth();