Skip to content

Multiple subscriptions #40

@camadamsmd

Description

@camadamsmd

At work I am porting a Laravel App to Nextjs and Nestjs. The existing app cancelled the subscription when the payment failed. The customer had to start a new subscription in this case. Stripe dashboard you can't remove a subscription for legal and historical accuracy reasons.

So Theos solution here is a bit flawed - the part where he gets the customers id from the webhook and fetches all their subscriptions limiting to 1. What if we fetch the cancelled subscription? Then you'd sync you local db to the wrong sub.

You would need to get the subscription id from the webhook. Not sure how to do that at the moment for all the webhooks that Theo is listening to.

export async function syncStripeDataToKV(customerId: string) {
  // Fetch latest subscription data from Stripe
  const subscriptions = await stripe.subscriptions.list({
    customer: customerId,
    limit: 1,
    status: "all",
    expand: ["data.default_payment_method"],
  });

  if (subscriptions.data.length === 0) {
    const subData = { status: "none" };
    await kv.set(`stripe:customer:${customerId}`, subData);
    return subData;
  }

  // If a user can have multiple subscriptions, that's your problem
  const subscription = subscriptions.data[0];

  // Store complete subscription state
  const subData = {
    subscriptionId: subscription.id,
    status: subscription.status,
    priceId: subscription.items.data[0].price.id,
    currentPeriodEnd: subscription.current_period_end,
    currentPeriodStart: subscription.current_period_start,
    cancelAtPeriodEnd: subscription.cancel_at_period_end,
    paymentMethod:
      subscription.default_payment_method &&
      typeof subscription.default_payment_method !== "string"
        ? {
            brand: subscription.default_payment_method.card?.brand ?? null,
            last4: subscription.default_payment_method.card?.last4 ?? null,
          }
        : null,
  };

  // Store the data in your KV
  await kv.set(`stripe:customer:${customerId}`, subData);
  return subData;
}```

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions