A Stripe subscription end to end: the cases people forget
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
- 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. - Failed payments have follow-ups.
invoice.payment_failed: notify the customer. Apast_duesubscription: ask them to update their card.canceledorunpaid: revoke access. - 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.
- Disputes and refunds. If you don't subscribe to
charge.dispute.createdandcharge.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
Comments
No comments yet. Start the discussion.