66 lines
1.9 KiB
TypeScript
66 lines
1.9 KiB
TypeScript
import { NextResponse } from "next/server";
|
|
import { stripeClient } from "../../../../lib/stripeClient";
|
|
|
|
export async function POST(req: Request) {
|
|
try {
|
|
const body = await req.json();
|
|
const accountId = body.accountId as string;
|
|
const name = body.name as string;
|
|
const description = body.description as string;
|
|
const unitAmount = Number(body.unitAmount);
|
|
const currency = (body.currency as string) || "usd";
|
|
const quantity = Number(body.quantity) || 1;
|
|
|
|
if (!accountId || !name || !Number.isFinite(unitAmount)) {
|
|
return NextResponse.json(
|
|
{ error: "accountId, name, and unitAmount are required." },
|
|
{ status: 400 }
|
|
);
|
|
}
|
|
|
|
const baseUrl = process.env.NEXT_PUBLIC_BASE_URL;
|
|
if (!baseUrl) {
|
|
return NextResponse.json(
|
|
{
|
|
error:
|
|
"Missing NEXT_PUBLIC_BASE_URL. Set it so we can build success/cancel URLs.",
|
|
},
|
|
{ status: 500 }
|
|
);
|
|
}
|
|
|
|
// Direct charge to the connected account with an application fee.
|
|
const session = await stripeClient.checkout.sessions.create(
|
|
{
|
|
line_items: [
|
|
{
|
|
price_data: {
|
|
currency,
|
|
product_data: { name, description },
|
|
unit_amount: unitAmount,
|
|
},
|
|
quantity,
|
|
},
|
|
],
|
|
payment_intent_data: {
|
|
// Sample application fee. Adjust this based on your pricing model.
|
|
application_fee_amount: Math.max(50, Math.floor(unitAmount * 0.1)),
|
|
},
|
|
mode: "payment",
|
|
success_url: `${baseUrl}/success?session_id={CHECKOUT_SESSION_ID}`,
|
|
cancel_url: `${baseUrl}/cancel`,
|
|
},
|
|
{
|
|
stripeAccount: accountId,
|
|
}
|
|
);
|
|
|
|
return NextResponse.json({ url: session.url });
|
|
} catch (err: any) {
|
|
return NextResponse.json(
|
|
{ error: err?.message || "Failed to create checkout session." },
|
|
{ status: 500 }
|
|
);
|
|
}
|
|
}
|