On a SaaS, I set up a subscription with Stripe. The first payment is the easy part. The rest comes afterwards, on its own: renewals, failed payments, cancellations.
Stripe tells your application about it through webhooks. According to its documentation, most subscription activity is asynchronous, so that's where the forgotten cases are.
switch (event.type) {
case "invoice.paid":
// fetch the subscription, check it is "active", extend access
break;
case "invoice.payment_failed":
// notify the customer
break;
case "customer.subscription.deleted":
// revoke access
break;
case "charge.dispute.created":
// decide: send evidence, restrict access
break;
}
Four points not to miss.
1. Access is decided on the event, not on the payment's return. When you receive invoice.paid, fetch the subscription and check it's actually active before extending access. A paid invoice doesn't always make it active.
2. Failed payments have follow-ups. invoice.payment_failed: notify the customer. A past_due subscription: ask them to update their card. canceled or unpaid: revoke access.
3. A webhook that answers badly is replayed. In production, Stripe retries for up to 3 days. Processing the same event twice must therefore break nothing. And always verify the event really comes from Stripe, using the signature.
4. Disputes and refunds. If you don't subscribe to charge.dispute.created and charge.refunded, your application only finds out when you open the Dashboard.
A subscription isn't done when the first payment goes through. It's done when you know what your application does for each event.
Amine Affif, full-stack developer in Paris. amineaffif.com
Top comments (2)
Point 1 is the one that bites: "paid" isn't "active". On point 3 I'd also store the event ids you've processed and skip repeats.
On mobile it maps almost one to one: App Store Server Notifications and Play's Real-time Developer Notifications play the webhook role. The big difference is failed payments: the stores run the retries, so your job is to read the state they report, not schedule retries.
Do you treat upgrades as
customer.subscription.updatedor as a newinvoice.paid?Thanks, storing the event ids is a good addition. I mentioned replays but not how to protect against them. Good to know for mobile too, I only covered Stripe.
For upgrades I use customer.subscription.updated. It tells me the plan changed and gives me the new status, so I update access from there. An invoice.paid only comes right away if you ask Stripe to bill the difference now (proration_behavior=always_invoice) or if the billing period changes. Otherwise the difference is added to the next invoice.
One thing to watch: by default Stripe applies the upgrade even if that payment fails, and the subscription goes past_due. So I check the status too, not only the plan.