From 19cfd33d6631e5d65c005abd9732d1750be3b3f5 Mon Sep 17 00:00:00 2001 From: Luke Vella Date: Fri, 7 Mar 2025 10:01:30 +0000 Subject: [PATCH] =?UTF-8?q?=F0=9F=90=9B=20Create=20stripe=20customer=20on?= =?UTF-8?q?=20checkout=20(#1620)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- apps/web/src/app/api/stripe/checkout/route.ts | 36 +++++++++++++------ 1 file changed, 26 insertions(+), 10 deletions(-) diff --git a/apps/web/src/app/api/stripe/checkout/route.ts b/apps/web/src/app/api/stripe/checkout/route.ts index 3aeb99d34..95d00d1a8 100644 --- a/apps/web/src/app/api/stripe/checkout/route.ts +++ b/apps/web/src/app/api/stripe/checkout/route.ts @@ -39,6 +39,7 @@ export async function POST(request: NextRequest) { }, select: { email: true, + name: true, customerId: true, subscription: { select: { @@ -52,6 +53,26 @@ export async function POST(request: NextRequest) { return new NextResponse(null, { status: 404 }); } + let customerId = user.customerId; + + if (!customerId) { + const customer = await stripe.customers.create({ + email: user.email, + name: user.name, + }); + + await prisma.user.update({ + where: { + id: userSession.user.id, + }, + data: { + customerId: customer.id, + }, + }); + + customerId = customer.id; + } + if (user.subscription?.active === true) { // User already has an active subscription. Take them to customer portal return NextResponse.redirect( @@ -67,16 +88,11 @@ export async function POST(request: NextRequest) { return_path ?? "/api/stripe/portal?session_id={CHECKOUT_SESSION_ID}", ), cancel_url: absoluteUrl(return_path), - ...(user.customerId - ? { - customer: user.customerId, - customer_update: { - name: "auto", - }, - } - : { - customer_email: user.email, - }), + customer: customerId, + customer_update: { + name: "auto", + address: "auto", + }, mode: "subscription", allow_promotion_codes: true, billing_address_collection: "auto",