Files
2026-02-10 01:14:19 +00:00

106 lines
3.1 KiB
TypeScript

import { NextResponse } from "next/server";
import { stripeClient } from "../../../../../lib/stripeClient";
import { prisma } from "../../../../../lib/prisma";
import { getServerSession } from "next-auth";
import { authOptions } from "../../../../../lib/auth";
export async function POST(req: Request) {
try {
const session = await getServerSession(authOptions);
if (!session?.user?.email) {
return NextResponse.json({ error: "Unauthorized." }, { status: 401 });
}
const body = await req.json();
const displayName = body.displayName as string;
const contactEmail = body.contactEmail as string;
const slug = body.slug as string;
const website = body.website as string | undefined;
if (!displayName || !contactEmail || !slug) {
return NextResponse.json(
{ error: "displayName, contactEmail, and slug are required." },
{ status: 400 }
);
}
// Create a V2 connected account with the exact properties requested.
const account = await stripeClient.v2.core.accounts.create({
display_name: displayName,
contact_email: contactEmail,
identity: {
country: "us",
},
dashboard: "full",
defaults: {
responsibilities: {
fees_collector: "stripe",
losses_collector: "stripe",
},
},
configuration: {
customer: {},
merchant: {
capabilities: {
card_payments: {
requested: true,
},
},
},
},
});
// Persist mapping between your store slug and account.id.
const user = await prisma.user.findUnique({
where: { email: session.user.email },
});
if (!user) {
return NextResponse.json({ error: "User not found." }, { status: 404 });
}
const existing = await prisma.store.findUnique({ where: { slug } });
if (existing && existing.userId !== user.id) {
return NextResponse.json({ error: "Slug already in use." }, { status: 409 });
}
let defaultSellingPreferences: any = null;
if (process.env.STORE_DEFAULT_SELLING_PREFERENCES) {
try {
defaultSellingPreferences = JSON.parse(
process.env.STORE_DEFAULT_SELLING_PREFERENCES
);
} catch {
defaultSellingPreferences = {
raw: process.env.STORE_DEFAULT_SELLING_PREFERENCES,
};
}
}
await prisma.store.upsert({
where: { userId: user.id },
update: {
slug,
stripeAccountId: account.id,
name: displayName,
website: website || process.env.STORE_DEFAULT_WEBSITE || null,
defaultSellingPreferences,
},
create: {
userId: user.id,
slug,
stripeAccountId: account.id,
name: displayName,
website: website || process.env.STORE_DEFAULT_WEBSITE || null,
defaultSellingPreferences,
},
});
return NextResponse.json({ accountId: account.id, slug });
} catch (err: any) {
return NextResponse.json(
{ error: err?.message || "Failed to create connected account." },
{ status: 500 }
);
}
}