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"constsetUser= (uid, user) =>firestore.collection("users").doc(uid).set(user, { merge:true })exportdefault ({ uid, displayName ="", email ="" }) => {// example of default user data you want to store on your databaseconstuserData= { email, displayName }returnstripe.customers.list({ email, expand: ["data.subscriptions"] }).then((customers) => {if (!customers ||customers?.data?.length===0) {// no stripe customer yetreturnsetUser(uid, userData) }// stripe customer exists for this accountconstcustomer=customers.data[0]constsharedSubscriptionId=customer.metadata?.billing_shared_subscription_idif (sharedSubscriptionId) {// customer is part of a shared subscriptionreturnstripe.subscriptions.retrieve(sharedSubscriptionId).then((subscription) => {if (["active","trialing"].includes(subscription.status)) {// shared subscription is activereturnsetUser(uid, {...userData, subscription: { id: sharedSubscriptionId, status:subscription.status, plan:subscription.items?.data[0]?.price?.id ??"" } }) }// shared subscription is not activereturnsetUser(uid, userData) }) }constsubscription=customer.subscriptions?.data.find((s) => ["active","trialing"].includes(s.status))if (subscription) {// user has an active subscriptionreturnsetUser(uid, {...userData, subscription: { id:subscription.id, status:subscription.status, plan:subscription.items?.data[0]?.price?.id ??"" } }) }// user has no active subscriptionreturnsetUser(uid, userData) })}