40 lines
1.2 KiB
TypeScript
40 lines
1.2 KiB
TypeScript
import { NextResponse } from "next/server";
|
|
|
|
import { assertAgencyAdmin, getRouteAgencyContextOrThrow } from "@/lib/agency";
|
|
import { env } from "@/lib/env";
|
|
import { getStripeClient } from "@/lib/stripe";
|
|
import { createSupabaseRouteClient } from "@/lib/supabase/route";
|
|
|
|
export async function POST() {
|
|
try {
|
|
const context = await getRouteAgencyContextOrThrow();
|
|
assertAgencyAdmin(context);
|
|
|
|
const supabase = createSupabaseRouteClient();
|
|
const stripe = getStripeClient();
|
|
|
|
const { data: billing, error } = await supabase
|
|
.from("billing_accounts")
|
|
.select("stripe_customer_id")
|
|
.eq("agency_id", context.agencyId)
|
|
.maybeSingle();
|
|
|
|
if (error) throw error;
|
|
if (!billing?.stripe_customer_id) {
|
|
throw new Error("No Stripe customer is linked to this agency");
|
|
}
|
|
|
|
const session = await stripe.billingPortal.sessions.create({
|
|
customer: billing.stripe_customer_id,
|
|
return_url: `${env.appUrl}/dashboard`,
|
|
});
|
|
|
|
return NextResponse.json({ url: session.url });
|
|
} catch (error) {
|
|
return NextResponse.json(
|
|
{ error: error instanceof Error ? error.message : "Failed to open billing portal" },
|
|
{ status: 400 },
|
|
);
|
|
}
|
|
}
|