When you have a new user on your app, you will have to check if they are already having a subscription on Stripe, either because they were added to a shared subscription or because you added their subscription manually from the Stripe Dashboard.
onNewUser.ts
This code example is a triggered called when a new user is created on your app
It's up to you to implement it this way or another, this code can also be part of your backend code that is called when a new user sign up.
It will check if the user is part of an active shared subscription or has an active personal subscription and add it to the database
import { firestore } from "../utils/firebase"
import stripe, { Stripe } from "../utils/stripe"
const setUser = (uid, user) => firestore.collection("users").doc(uid).set(user, { merge: true })
export default ({ uid, displayName = "", email = "" }) => {
// example of default user data you want to store on your database
const userData = {
email,
displayName
}
return stripe.customers
.list({
email,
expand: ["data.subscriptions"]
})
.then((customers) => {
if (!customers || customers?.data?.length === 0) {
// no stripe customer yet
return setUser(uid, userData)
}
// stripe customer exists for this account
const customer = customers.data[0]
const sharedSubscriptionId = customer.metadata?.billing_shared_subscription_id
if (sharedSubscriptionId) {
// customer is part of a shared subscription
return stripe.subscriptions.retrieve(sharedSubscriptionId).then((subscription) => {
if (["active", "trialing"].includes(subscription.status)) {
// shared subscription is active
return setUser(uid, {
...userData,
subscription: {
id: sharedSubscriptionId,
status: subscription.status,
plan: subscription.items?.data[0]?.price?.id ?? ""
}
})
}
// shared subscription is not active
return setUser(uid, userData)
})
}
const subscription = customer.subscriptions?.data.find((s) => ["active", "trialing"].includes(s.status))
if (subscription) {
// user has an active subscription
return setUser(uid, {
...userData,
subscription: {
id: subscription.id,
status: subscription.status,
plan: subscription.items?.data[0]?.price?.id ?? ""
}
})
}
// user has no active subscription
return setUser(uid, userData)
})
}