Failed payments

Why subscription payments fail, and what to try in what order

A renewal is a payment nobody is watching. The customer isn't on the page, the card was saved months ago, and the bank gets to say no without explaining itself. Some of those failures fix themselves, some need the customer, and one needs the customer and their banking app. Here's how to tell them apart, the order to try the fixes in, and a webhook handler that does the sorting, with the retry material from chapter 5.

A failed subscription payment is a renewal the card issuer declined, or one that couldn't run at all. It's an off-session payment: the customer isn't there, so nobody can retype a number or approve a prompt. On Stripe, the subscription moves to past_due, the invoice stays open, and invoice.payment_failed fires on each attempt (Stripe).

If you're the subscriber

Your bank declined the renewal, and the business usually isn't told why. Check that the card on file hasn't expired or been replaced, update it from the link in the business's email or your account page, and if the card looks fine, call the number on the back of it. If your bank asks you to confirm a payment, do it from the link the business sent or in your banking app, never by reading a code to someone who phoned you.

Why renewals fail

CauseTypical Stripe codeSoft or hardSmart Retries?What fixes it
Not enough money right nowinsufficient_fundsSoftYesTime: a retry after money lands
Expired or replaced cardexpired_cardSoft, if the network updates itYesCard account updater or network token; otherwise a new card
Generic refusalgeneric_decline, do_not_honorUnknownYesOne retry, then the customer (do not honor)
Card lost, stolen, or picked uplost_card, stolen_card, pickup_cardHardNoA new payment method
Card number wrong, or payment type not allowedincorrect_number, transaction_not_allowedHardNoA new payment method
Customer told the bank to stoprevocation_of_authorization, revocation_of_all_authorizationsHardNoTreat as a cancellation
Bank wants the customer to authenticateauthentication_requiredNeither: needs the customerNoThe customer completes 3D Secure
Issuer unreachable, processing errorissuer_not_available, processing_errorSoftYesA retry, usually soon

The Smart Retries column is Stripe's own list: for incorrect_number, lost_card, pickup_card, stolen_card, the two revocation codes, authentication_required, highest_risk_level and transaction_not_allowed, retries stay scheduled and attempt_count keeps climbing, but nothing actually runs until the customer adds a new payment method (Stripe). expired_card isn't on that list, which fits: if the network has replaced the card in the meantime, a later attempt can go through on the new details. Every other code, with its network meaning, is in card decline codes.

Authentication on a payment nobody is present for

Renewals on a properly saved card are merchant-initiated transactions, which sit outside Europe's Strong Customer Authentication rules. Outside isn't immune. Stripe's own wording: "Exemptions aren't guaranteed, and off-session payments might still require authentication by the bank" (Stripe). When that happens, the decline code is authentication_required (Stripe), the PaymentIntent waits in requires_action, and Stripe sends invoice.payment_action_required (Stripe).

No retry fixes that. The only way through is the customer, on a page that can run 3D Secure: Stripe's hosted invoice page does (Stripe), and Stripe can email them a hosted confirmation link for you (Stripe). Prevention is in how the card was saved: authenticate it on-session with the Setup Intents API (or setup_future_usage) set for off-session use, and flag renewals as off-session (Stripe). The 3D Secure exemptions guide covers the rules.

The recovery order of operations

  1. Keep the card current before it fails. Card account updaters and network tokens replace a reissued card's details without the customer doing anything. On Stripe both are automatic; Stripe says the updater is widely supported on US-issued cards, that international support varies by country, and that "it isn't possible to identify cards that support automatic updates" (Stripe). So the practical rule is: if no payment_method.automatically_updated event has arrived by the card's expiry month, ask the customer for the new card.
  2. Classify the decline. Soft, hard, or authentication, from the table above. This decides everything after it, and it's what the handler below does.
  3. Retry the soft ones, and only those. Smart Retries does the timing; Stripe recommends at most eight retries for charges that permit them and warns that issuers can read more as fraud (Stripe). The card networks also cap reattempts per card, with fees for going over; the limits are in card decline codes.
  4. Contact the customer. Straight away for hard declines and authentication; after the first failed attempt for soft ones; never on day one for an expired card the updater may still replace. The wording is in dunning email templates, and the whole sequence, from the first email to the cut-off, is in the dunning guide.
  5. Grace period. Access during past_due is your call (Stripe). Keep it for as long as retries are still running: cutting someone off while the bank might still say yes costs a customer to save a few days of service.
  6. Stop. When retries end, Stripe does what your Dashboard says: cancel, mark unpaid, pause, or leave the subscription past_due (Stripe). Stripe says to revoke access on unpaid and canceled (Stripe). Pick the outcome on purpose, then stop emailing.

One trap in step 4: the new card has to land where the retry looks. Stripe retries with the subscription's default_payment_method before the customer's default, so updating only the customer's default leaves the retries on the old card (Stripe). The customer portal's payment_method_update flow sets the customer's invoice default (Stripe), so either don't set a subscription-level default, or update it too when the customer changes card.

In code: classify the failure, pick the next step

A Flask handler for the renewal events. It verifies the signature against the raw body, skips events it has already handled, reads the decline code from the invoice's open payment (through the invoice payments list, which is how the current API links an invoice to its PaymentIntent), and maps it to one action. act, revoke_access and the idempotency helpers are yours.

import os

import stripe
from flask import Flask, abort, request

app = Flask(__name__)
stripe.api_key = os.environ["STRIPE_SECRET_KEY"]
WEBHOOK_SECRET = os.environ["STRIPE_WEBHOOK_SECRET"]

# Stripe's Smart Retries list: scheduled retries won't run on these
# until the customer adds a new payment method.
NEEDS_NEW_METHOD = {
    "incorrect_number", "lost_card", "pickup_card", "stolen_card",
    "revocation_of_authorization", "revocation_of_all_authorizations",
    "highest_risk_level", "transaction_not_allowed",
}


def failure_details(invoice_id):
    """(PaymentIntent status, decline code) for the invoice's open payment."""
    for ip in stripe.InvoicePayment.list(invoice=invoice_id, status="open").auto_paging_iter():
        if ip.is_default and ip.payment.type == "payment_intent":
            pi = stripe.PaymentIntent.retrieve(ip.payment.payment_intent)
            err = pi.last_payment_error
            code = (getattr(err, "decline_code", None) or getattr(err, "code", None)) if err else None
            return pi.status, code
    return None, None


def next_step(pi_status, code, attempt_count):
    if pi_status == "requires_action" or code == "authentication_required":
        return "ask_to_authenticate"      # retries can't fix this one
    if code in NEEDS_NEW_METHOD:
        return "ask_for_new_card"         # now, not after the retries
    if code == "expired_card" and attempt_count < 2:
        return "wait_for_card_updater"    # the network may replace it
    if attempt_count == 1:
        return "send_first_failure_email" # soft decline: retries continue
    return "let_retries_run"


@app.post("/webhooks/stripe")
def stripe_webhook():
    try:
        event = stripe.Webhook.construct_event(
            request.get_data(), request.headers.get("Stripe-Signature", ""), WEBHOOK_SECRET)
    except (ValueError, stripe.SignatureVerificationError):
        abort(400)
    if already_processed(event["id"]):   # your idempotency store
        return "", 200

    obj = event["data"]["object"]
    if event["type"] == "invoice.payment_failed" and obj["billing_reason"] != "subscription_create":
        status, code = failure_details(obj["id"])
        act(next_step(status, code, obj["attempt_count"]), obj)
    elif event["type"] == "invoice.payment_action_required":
        act("ask_to_authenticate", obj)  # link: obj["hosted_invoice_url"]
    elif event["type"] == "customer.subscription.updated":
        old = event["data"].get("previous_attributes", {}).get("status")
        if obj["status"] in ("unpaid", "paused", "canceled"):
            revoke_access(obj["customer"])
        elif old in ("past_due", "unpaid", "paused") and obj["status"] == "active":
            restore_access(obj["customer"])  # and send the "fixed" receipt
    elif event["type"] == "customer.subscription.deleted":
        revoke_access(obj["customer"])

    mark_processed(event["id"])
    return "", 200

Two choices in there are deliberate. The first renewal failure on an expired_card sends nothing, because the network may replace the card before the next attempt. And invoice.payment_failed for subscription_create is skipped: Smart Retries doesn't retry a first payment, so that decline belongs to your signup page, not your dunning (Stripe subscriptions covers it).

Soft, hard and authentication-required, in one paragraph. From chapter 5.

Not all errors are equal, and neither are declines. A network timeout gets retried in seconds. A soft decline, such as insufficient funds or an issuer that was briefly unreachable, gets retried too, but in hours or days, a limited number of times, and within the card networks' reattempt limits. A hard decline (a lost or stolen card, an account that doesn't exist, or an issuer advice code that says don't try again) never gets retried on the same card. And "authentication required" isn't a failure to retry at all: it's a request to bring the customer back. Telling these apart is what separates systems that recover revenue from ones that hammer a stolen card until the network notices.

The same split as code you can run for payments you retry yourself, with delays that match chapter 24's dunning schedule.

Retry Strategies

Different failure types call for different retry patterns. The delays for declines below match the dunning schedule in Chapter 24: insufficient funds waits about 72 hours, a generic decline gets one retry a day later.

HOUR = 3600
DAY = 24 * HOUR

# Never retry these on the same card. The issuer has said the card is gone,
# wrong, or dangerous, and reattempting a dead card is exactly what the
# networks' retry rules exist to stop. Expired cards are here too: wait for
# an account updater to supply the new details, or ask the customer.
HARD_DECLINES = {
    'lost_card', 'stolen_card', 'pickup_card', 'restricted_card',
    'fraudulent', 'merchant_blacklist', 'invalid_account',
    'incorrect_number', 'invalid_number', 'expired_card',
}


class PaymentRetryManager:
    """Decide whether, when, and how to recover from a failed payment.

    attempt_count is the number of retries already made for this charge:
    0 after the original attempt fails, 1 after the first retry fails.
    Per-type limits stay well inside the card networks' reattempt limits
    and Stripe's recommendation of at most eight retries per charge.
    """

    def __init__(self):
        self.retry_configs = {
            # Infrastructure errors: the issuer never saw the request.
            'network_error': {
                'max_retries': 5,
                'backoff': 'exponential',
                'base_delay': 1,  # seconds
                'max_delay': 30,
            },
            'rate_limit': {
                'max_retries': 3,
                'backoff': 'linear',
                'base_delay': 60,  # Wait longer for rate limits
                'max_delay': 300,
            },
            # Soft declines: the issuer said "not now", so wait for "now" to change.
            'insufficient_funds': {
                'max_retries': 3,
                'backoff': 'fixed',
                'base_delay': 3 * DAY,  # Give a payday a chance to land
                'max_delay': 3 * DAY,
                'notify_customer': True,
            },
            'do_not_honor': {
                'max_retries': 1,  # One retry, then ask for another card
                'backoff': 'fixed',
                'base_delay': DAY,
                'max_delay': DAY,
                'suggest_alternatives': True,
            },
            'generic_decline': {
                'max_retries': 1,
                'backoff': 'fixed',
                'base_delay': DAY,
                'max_delay': DAY,
                'suggest_alternatives': True,
            },
            'issuer_not_available': {
                'max_retries': 3,
                'backoff': 'exponential',
                'base_delay': HOUR,
                'max_delay': 6 * HOUR,
            },
            'processing_error': {
                'max_retries': 2,
                'backoff': 'fixed',
                'base_delay': HOUR,
                'max_delay': HOUR,
            },
            # Not a retry: the customer has to come back and authenticate.
            'authentication_required': {
                'max_retries': 0,
                'next_step': 'authenticate',
            },
        }

    def next_step(self, error_type, advice_code=None):
        """What to do instead of (or before) retrying"""
        if advice_code == 'do_not_try_again' or error_type in HARD_DECLINES:
            return 'request_new_payment_method'
        config = self.retry_configs.get(error_type)
        if config is None:
            return 'request_new_payment_method'  # Unknown: don't guess
        return config.get('next_step', 'retry')

    def should_retry(self, error_type, attempt_count, advice_code=None):
        """Determine if payment should be retried automatically"""
        if self.next_step(error_type, advice_code) != 'retry':
            return False
        max_retries = self.retry_configs[error_type]['max_retries']
        return attempt_count < max_retries

    def calculate_delay(self, error_type, attempt_count):
        """Seconds to wait before the next retry"""
        config = self.retry_configs.get(error_type, {})
        if 'base_delay' not in config:
            raise ValueError(f"{error_type} is never retried automatically")
        base_delay = config['base_delay']
        max_delay = config['max_delay']

        if config['backoff'] == 'exponential':
            delay = base_delay * (2 ** attempt_count)
        elif config['backoff'] == 'linear':
            delay = base_delay * (attempt_count + 1)
        else:  # fixed
            delay = base_delay

        return min(delay, max_delay)

The advice code check matters as much as the decline code. Stripe passes the issuer's advice_code alongside the decline, and do_not_try_again overrides whatever the decline code alone would suggest. If you're on Stripe Billing, Smart Retries handles the timing for subscription invoices; this logic is for the payments you retry yourself.

Questions

Why do subscription payments fail?

Mostly because a saved card can't be charged when the renewal runs: not enough money at that moment, an expired or replaced card, a generic refusal from the bank, a lost or stolen card, or the bank asking the customer to authenticate a payment they aren't present for.

What is the difference between a soft and a hard decline?

A soft decline, such as insufficient funds or an unreachable issuer, can succeed later, so it's retried. A hard decline, such as a lost or stolen card or a wrong card number, will never succeed on that card, so you ask for a new payment method. Authentication required is neither: only the customer can fix it.

Does Stripe retry failed subscription payments?

Yes. Smart Retries is on by default for new accounts, at up to 8 retries within 2 weeks. For hard decline codes such as lost_card, stolen_card, incorrect_number and authentication_required, retries stay scheduled but don't run until the customer adds a new payment method.

Why does a renewal fail with authentication_required?

Renewals are merchant-initiated and usually exempt from Strong Customer Authentication, but exemptions aren't guaranteed and the bank can still ask for authentication. The customer has to come back and complete 3D Secure, for example on Stripe's hosted invoice page. No retry fixes it.

In what order should you recover a failed subscription payment?

Keep cards current with account updater and network tokens, classify the decline, retry only the soft ones, contact the customer, keep access during the retry window, and then cancel, pause or mark the subscription unpaid and stop.

What the book adds

What chapters 5 and 24 add

  • Circuit breakers for a processor that's down
  • Failure categories, and the action each one gets
  • A dunning sequence, day by day
  • Pause, downgrade or cancel at the end of it
  • Churn prediction signals

30-day money-back · Instant PDF and EPUB

All 42 chapters