Files
Momento/memento-note/app/api/billing/portal/route.ts

41 lines
1.3 KiB
TypeScript

import { NextRequest, NextResponse } from 'next/server';
import { auth } from '@/auth';
import { stripe } from '@/lib/stripe';
import { prisma } from '@/lib/prisma';
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;
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 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,
return_url: `${origin}/settings/billing`,
});
return NextResponse.json({ url: portalSession.url });
} catch (error) {
console.error('[billing/portal]', error);
return NextResponse.json({ error: 'Failed to create portal session' }, { status: 500 });
}
}