Skip to content

Commit

Permalink
Update createCheckoutSession.ts
Browse files Browse the repository at this point in the history
  • Loading branch information
ArhanAnsari authored Oct 6, 2024
1 parent 1240534 commit bc28aa5
Showing 1 changed file with 30 additions and 20 deletions.
50 changes: 30 additions & 20 deletions actions/createCheckoutSession.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,28 +20,38 @@ export const createCheckoutSession = async (userEmail: string, plan: string) =>
if (!isWithinLimit) {
throw new Error("You have reached your plan's request limit.");
}
// first check if the user already has a stripeCustomerId
let stripeCustomerId;

const user = await adminDb.collection("users").doc(user).get();
stripeCustomerId = user.data()?.stripeCustomerId;

if (!stripeCustomerId) {
// create a new stripe customer
const customer = await stripe.customers.create({
email: userDetails.email,
name: userDetails.name,
metadata: {
userId,
},
});

await adminDb.collection("users").doc(userId).set({
stripeCustomerId: customer.id,
});
// First check if the user already has a stripeCustomerId
let stripeCustomerId;

// Fetch the user document using userEmail
const userDoc = await adminDb.collection("users").doc(userEmail).get();
const userDetails = userDoc.data();

if (!userDetails) {
throw new Error("User details not found.");
}

stripeCustomerId = userDetails.stripeCustomerId;

if (!stripeCustomerId) {
// Create a new stripe customer
const customer = await stripe.customers.create({
email: userDetails.email,
name: userDetails.name,
metadata: {
userId: userEmail, // Using userEmail as userId
},
});

// Update Firestore with the new Stripe customer ID
await adminDb.collection("users").doc(userEmail).set({
stripeCustomerId: customer.id,
}, { merge: true }); // Use merge to avoid overwriting existing data

stripeCustomerId = customer.id;
}

stripeCustomerId = customer.id;
}
// Stripe price IDs for plans
const priceId = plan === "pro"
? "price_1Q0L3aSCr1Ne8DGFAI9n4GbW" // Pro Plan price ID
Expand Down

0 comments on commit bc28aa5

Please sign in to comment.