Search code examples
stripe-paymentssubscription

Detect if subscription is cancelled automatically


I have setup my Stripe subscriptions to be automatically cancelled after 3 failed payment attempts and I have a customer.subscription.deleted webhook to record the cancelled subscription.

Is there a way to detect in the customer.subscription.deleted webhook if the subscription is cancelled by Stripe because of failed payment attempts OR manually cancelled through the Stripe dashboard OR cancelled because of an API request made from our application?


Solution

  • You can't differentiate between the last two cases, as the dashboard itself uses the API.

    However, you can differentiate between automatic and manual cancelations. Simply look at the request attribute in the customer.subscription.deleted event's body.

    If the subscription was canceled automatically after too many failed payments, then request will have a null value.

    Otherwise, if the subscription was canceled through the API or the dashboard, request will have a non-null value: the request ID ("req_...") of the subscription cancelation request.

    EDIT: as Yoni Rabinovitch pointed out, the above is true if the subscription was canceled with at_period_end=false (or no at_period_end parameter, as false is the default value).

    If the subscription was canceled with at_period_end=true, then a customer.subscription.updated event would be fired immediately (to reflect the fact that the subscription's cancel_at_period_end attribute is now true), and that event's request would have the request ID of the subscription cancelation request.

    However, the customer.subscription.deleted event that would be sent when the subscription is actually canceled at the end of the billing period would have request=null, just like an automatic cancelation after too many failed payements.