update_subscription_tier


A supabase function that is triggered by a database webhook when the stripe_customer_id is createdcreate_stripe_customerA supabase function that creates a stripe customer and returns the stripe_customer_id. Steps: 1. Get the supabase_user_id from the request 1. Check if stripe_customer_id already exists in the table. If it does, skip the following steps 1. Create stripe customer and store the stripe_customer_id 1. Update the table with the stripe_customer_id and return it Example Code Video Walkthrough or updated.

  1. Check if it's a valid stripe_customer_id by querying subscriptions
  2. If subscription is "active" or "trialing", then retrieve the subscription_tier from the metadata of the subscription plan.
  3. Otherwise, set the subscription_tier to "free"
  4. Update the row of the stripe_customer_id with the new subscription_tier
let subscription_tier = 'free';

// Step 1
const sub = await stripe.subscriptions.list({
  customer: record.stripe_customer_id,
  limit: 1,
});
if (sub.data.length > 0) {
  const subData = sub.data[0];
  
  // Step 2
  if (["active", "trialing"].includes(subData.status)) {
	const prod = await stripe.products.retrieve(subData.plan.product);
	subscription_tier = prod.metadata.supabaseTier || 'free';
  }
}

// Step 3 (default subscription_tier is free)

// Step 4
const { error } = await supabase
  .from("customers")
  .update({
	subscription_tier,
  })
  .match({ id: record.id })
  .neq('subscription_tier', subscription_tier);