Skip to content

Commit 0ea0dc4

Browse files
feat: add Stripe customer creation during user initialization
Co-Authored-By: WeWrite <getwewrite@gmail.com>
1 parent 2c7d36b commit 0ea0dc4

File tree

2 files changed

+69
-9
lines changed

2 files changed

+69
-9
lines changed

app/api/payments/create-customer/route.js

Lines changed: 25 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,34 @@
11
import { NextResponse } from 'next/server';
22
import Stripe from 'stripe';
3+
import { getDatabase } from '@/firebase/database';
34

45
const stripe = new Stripe(process.env.STRIPE_SECRET_KEY);
6+
const db = getDatabase();
57

6-
export async function POST() {
8+
export async function POST(request) {
79
try {
8-
const customer = await stripe.customers.create();
10+
const { userId, email, name } = await request.json();
11+
12+
if (!userId) {
13+
return NextResponse.json(
14+
{ error: 'User ID is required' },
15+
{ status: 400 }
16+
);
17+
}
18+
19+
// Create a Stripe customer with user information
20+
const customer = await stripe.customers.create({
21+
email,
22+
name,
23+
metadata: {
24+
userId,
25+
},
26+
});
27+
28+
// Update user record with Stripe customer ID
29+
await db.ref(`users/${userId}`).update({
30+
stripeCustomerId: customer.id,
31+
});
932

1033
return NextResponse.json({
1134
customerId: customer.id

app/providers/AuthProvider.js

Lines changed: 44 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,10 @@
22

33
import { useEffect, useState, createContext, useContext } from "react";
44
import { auth, onAuthStateChanged } from "../firebase/auth";
5+
import { getDatabase } from "../firebase/database";
56

67
export const AuthContext = createContext();
8+
const db = getDatabase();
79

810
export const useAuth = () => {
911
const context = useContext(AuthContext);
@@ -18,6 +20,32 @@ export const AuthProvider = ({ children }) => {
1820
const [loading, setLoading] = useState(true);
1921
const [error, setError] = useState(null);
2022

23+
const createStripeCustomer = async (userData) => {
24+
try {
25+
const response = await fetch('/api/payments/create-customer', {
26+
method: 'POST',
27+
headers: {
28+
'Content-Type': 'application/json',
29+
},
30+
body: JSON.stringify({
31+
userId: userData.uid,
32+
email: userData.email,
33+
name: userData.displayName,
34+
}),
35+
});
36+
37+
if (!response.ok) {
38+
throw new Error('Failed to create Stripe customer');
39+
}
40+
41+
const { customerId } = await response.json();
42+
return customerId;
43+
} catch (error) {
44+
console.error('Error creating Stripe customer:', error);
45+
return null;
46+
}
47+
};
48+
2149
useEffect(() => {
2250
if (typeof window === 'undefined') {
2351
setLoading(false);
@@ -26,15 +54,24 @@ export const AuthProvider = ({ children }) => {
2654

2755
let unsubscribe;
2856
try {
29-
unsubscribe = onAuthStateChanged(auth, (user) => {
57+
unsubscribe = onAuthStateChanged(auth, async (authUser) => {
3058
try {
31-
if (user) {
59+
if (authUser) {
60+
const userSnapshot = await db.ref(`users/${authUser.uid}`).get();
61+
const userData = userSnapshot.val() || {};
62+
63+
let stripeCustomerId = userData.stripeCustomerId;
64+
if (!stripeCustomerId) {
65+
stripeCustomerId = await createStripeCustomer(authUser);
66+
}
67+
3268
setUser({
33-
uid: user.uid,
34-
email: user.email,
35-
displayName: user.displayName,
36-
username: user.username || user.displayName,
37-
groups: user.groups || ['default-group']
69+
uid: authUser.uid,
70+
email: authUser.email,
71+
displayName: authUser.displayName,
72+
username: userData.username || authUser.displayName,
73+
groups: userData.groups || ['default-group'],
74+
stripeCustomerId,
3875
});
3976
} else {
4077
setUser(null);

0 commit comments

Comments
 (0)