feat(#31): Add support for subscriptions to create stripe customers

This commit is contained in:
Josh Creek
2024-10-20 19:50:07 +01:00
parent 7d994d1c09
commit 4c44f772e5
+26 -3
View File
@@ -1,5 +1,7 @@
import { type RequestHandler, redirect } from '@sveltejs/kit';
import { stripe as stripeClient } from '$lib/utils/stripe';
import { getStripeCustomerId } from '$lib/utils/supabase/admin';
import type Stripe from 'stripe';
// Create a subscription checkout session
export const POST: RequestHandler = async ({ request, cookies, locals: { safeGetSession } }) => {
@@ -11,6 +13,7 @@ export const POST: RequestHandler = async ({ request, cookies, locals: { safeGet
}
const userId = session.user.id;
const userEmail = session.user.email;
// Get the price ID from the request body
const { priceId } = await request.json();
@@ -19,8 +22,16 @@ export const POST: RequestHandler = async ({ request, cookies, locals: { safeGet
return new Response('Price ID is required', { status: 400 });
}
// Create a subscription checkout session with Stripe
const checkoutSession = await stripeClient.checkout.sessions.create({
let stripeCustomerId = null;
// Get the existing Stripe customer ID from Supabase, if it exists
try {
stripeCustomerId = await getStripeCustomerId(userEmail!, userId);
} catch (error) {
console.error('Error fetching Stripe customer ID:', error);
}
const stripeCheckoutSessionObject = {
line_items: [
{
price: priceId,
@@ -33,7 +44,19 @@ export const POST: RequestHandler = async ({ request, cookies, locals: { safeGet
metadata: {
userId: userId
}
});
} as Stripe.Checkout.SessionCreateParams;
if (stripeCustomerId) {
// If the user has a Stripe customer ID, attach it to the checkout session
stripeCheckoutSessionObject.customer = stripeCustomerId;
} else {
// If the user doesn't have a Stripe customer ID, create a new customer
stripeCheckoutSessionObject.customer_creation = 'always';
stripeCheckoutSessionObject.customer_email = userEmail;
}
// Create a subscription checkout session with Stripe
const checkoutSession = await stripeClient.checkout.sessions.create(stripeCheckoutSessionObject);
// Store the checkout session.id for access from the frontend
cookies.set('checkout_session_id', checkoutSession.id, { path: '/' });