SENIORCHAPTER 22

Card tokenisation, card-on-file and recurring payments

A saved card is a standing permission with no one in the room. Keep the token and not the number, tell a soft decline from a hard one, and measure what each retry earns before you pay for it

55 MINPAYMENTSUPDATED 2026-11-14
PREDICT

Tallowmere bills 1,000 subscribers on saved cards for four months. 8% of charges are declined for insufficient funds, at random, and a subscriber whose charge is declined is dropped from the list with no retry. Ignoring expired cards, about how many of the 1,000 are still subscribed after four months?

Why you do not keep the number

The 16 digits of a card number (the primary account number, or PAN) are what a thief needs. A database that holds them is a target, and every system that can read the database is in the scope of the card industry’s security standard, the PCI DSS. The chapter on PCI DSS and keeping card data out of scope, later in the course, covers the standard itself. This chapter takes its first lesson: the cheapest way to protect card numbers is to not hold them.

Tokenisation replaces the number with a surrogate, a token, that is useless outside the system that issued it. The PCI Security Standards Council’s Tokenization Guidelines information supplement (version 2.0, August 2011) is advisory. Search results say its cover lists it as a supplement to PCI DSS v2.0 dated August 2011, that it addresses how tokenisation can reduce the scope of a cardholder data environment, and that it states it does not replace or supersede the PCI DSS requirements. Commentators say it gives little concrete guidance on how much scope a token removes; that is their view and not the Council’sas of 2026-11. This build read the search summaries and not the PDF. Read the supplement for what a token must and must not allow before you rely on it to shrink scope.

Two kinds of token

The word covers two different things, and a design that mixes them up fails in a surprising place.

A network token is issued by the card scheme or its token service, in a framework that the card industry’s standards body, EMVCo, publishes. EMVCo publishes the EMV Payment Tokenisation Specification, Technical Framework. Search summaries say it was first released in March 2014, that a later version 2.3 is listed in EMVCo’s publications dated 19 October 2021, that it defines a Payment Account Reference (PAR) to link transactions made with tokens to the PAN they replace, and that the technical documents are free to download. The sources do not agree on every date, and this build could not confirm that 2.3 is the latest versionas of 2026-11. A network token travels through the card networks in place of the PAN. It can be limited to one merchant or one device, and the token service can keep it working when the underlying card is reissued.

A provider token is the payment provider’s own reference to a card it holds. The lab’s provider gives you an authorization_code. It is not a network token. It works only with that provider and only for the customer it was saved for, and behind it the provider still holds the number. Paystack, a payment provider, and a vendor whose description here is a vendor’s claim and not a rule, says in its recurring-charges documentation that once a customer’s first card payment succeeds you can store the authorisation and reuse it for later charges, that a reusable flag says whether an authorisation may be used for a recurring charge, and that you should use the code only when the flag is trueas of 2026-11. The lab’s response has the same shape: reusable: true.

The difference decides what you can do when things change. A provider token ties Tallowmere to its provider: moving to another provider means asking 300 patients for their cards again, unless the provider can migrate the numbers to the new one under the card standard’s rules. A network token can follow the card when it is reissued. Whichever you hold, the question to ask is the same: what does this reference let someone do, and what does it not?

What the first payment must establish

A renewal is charged without the patient. The scheme rules, and the provider’s checks, therefore treat it differently from a checkout. The vocabulary is a cardholder-initiated transaction (CIT), where the cardholder takes part, and a merchant-initiated transaction (MIT), where the merchant acts alone on earlier consent. Visa Acceptance Solutions, a vendor that describes Visa’s framework, and whose account is a vendor’s claim, says Visa’s stored credential framework splits card-on-file activity into these two types, that storing a credential starts with a cardholder-initiated transaction, that an MIT is a follow-on to that first transaction run without the cardholder present, and that merchants must pass identifiers on later transactions, among them the network transaction ID for Visa. Search results did not return Visa’s own rules text, so the details come from vendor documentation. Mastercard has its own versionas of 2026-11. Read the scheme rules or your acquirer’s guide for the fields your provider needs you to send.

In the lab, save_card: true on the first charge is the CIT. The patient is present, the card is entered, the charge succeeds and the provider keeps the card. For a real first payment, authentication with the payer (the 3-D Secure challenge that the later chapter on authenticating the payer teaches) belongs here, because this is the one moment the cardholder is in the room. Everything after is an MIT with no challenge.

That is also where a dispute will be fought. A patient who says “I did not agree to this” is disputing an MIT. The evidence is the first payment: who paid, when, that the card was stored with their agreement, the schedule they were told, and each renewal’s amount. The chapter on disputes and chargebacks covers the process. What you build here is the record that makes the evidence possible: store the time and the wording of consent next to the saved card.

A card is not a mandate. The direct debit chapter taught the mandate: a named cap, a frequency, a start and an end, held at the payer’s bank and checked on every debit. A saved card has no cap at the card’s bank. Whatever limits the patient was told, in the lab and in real life, are limits your own code enforces. The provider will charge the saved card for any amount you send, up to the card’s own limits.

One renewal, one reference

A renewal job is a scheduled call, and scheduled jobs run twice. The chapter on idempotency and moving money exactly once gave the rule: the second send must be a duplicate that the other side refuses. For a renewal, build the reference from what makes the charge unique: the patient, the billing cycle and the try number. RX-C0000042-2027-01-01-t0 is the first try for that patient’s January cycle. Run the job again and the provider answers 409 duplicate_reference with the first charge, and nobody is charged twice. The next try, -t1, is a new charge with its own reference, which is what you want. A reference built from a timestamp makes every run look new, which is the failure the idempotency chapter opened with.

The lab’s billing_date field stands in for the calendar. A real provider charges today. The mock lets your code say which day the charge is for, so that four months of renewals, and the expiry of cards among them, run in seconds. Step 1 of the lab shows the two layers together: the reference (409 if reused) and an Idempotency-Key header (the same response replayed, with Idempotent-Replayed: true).

Tell the patient before a charge that differs from the last. Nothing in the mock sends a notice, and a refill that rises from ₦18,500 to ₦22,000 is the commonest source of “I did not agree to this”.

Soft and hard declines

A declined renewal has a reason, and the reason decides the next step. Name the two classes before the schedule.

Class Example in the lab What changes it What to do
Soft decline insufficient_funds The payer’s balance, over days Retry on later days, a few times
Hard decline expired_card Only a new card Never retry. Ask the patient for a new card

The lab’s provider has these two decline codes. A real issuer has many more, and they fall into the same two classes: a card that is lost, stolen or closed is hard, and an issuer that is unavailable is soft. The schemes publish the class. PayPal, a payments vendor whose page is a vendor’s claim and not Visa’s rulebook, says Visa groups declines into categories: Category 1 declines (the issuer will not approve) should generally not be retried, and the others are soft. Sources disagree: most say the soft cap is 15 reattempts in 30 days, PayPal’s page says 20, and PayPal’s own pages differ on whether a few Category 1 codes may be retried, so treat both the cap and the exceptions as unconfirmed. Sources report that Visa charges a fee for excessive reattempts, and they give different fee figures that this build did not confirmas of 2026-11. Primer, an orchestration vendor, says Mastercard sends a Merchant Advice Code (MAC) with a decline, that MAC 03 means do not try again and MAC 21 means stop recurring payment requests. Other sources add that fees can apply to a retry within 30 days of these codes; this build could not read Primer’s full pageas of 2026-11. Both sources are vendor claims. Check the limits and the codes your acquirer applies before you set a schedule.

The practical consequence is the rule the previous chapter gave for mandates: only retry what can change. Persisting with a hard decline wastes calls, may cost fees and tells a cardholder who has cancelled that you ignored them.

What a retry earns

A retry costs a call, may cost a fee and can annoy the payer. It earns the renewal it recovers. Work the numbers before you choose a schedule.

Step 3 of the lab bills 1,000 subscribers ₦18,500 each, on four monthly due dates, with 8% of charges declined at random for insufficient funds. The cards’ expiry months come from the lab’s own cards table. One pass uses a schedule of up to three retries, on the due date plus 2, 5 and 9 days. The pass logs every attempt, and the script then replays the shorter schedules from the log. In the run quoted in the lab:

  • With no retries, 305 of the 1,000 subscribers are lost: 240 to declines and 65 to expired cards. That is 30.5%. The prediction gave 28.4% for declines alone (1 minus 0.7164), and the expired cards removed some subscribers before a decline could.
  • The first retry round sent 276 charges and 255 were paid, 92.4%. At ₦18,500 each, 255 payments are ₦4,717,500, so each charge sent returned about ₦17,092 (4,717,500 divided by 276). Churn fell from 30.5% to 9.2%.
  • The second round sent 21 charges and the third 2. Churn went to 7.4% and then 7.2%. The curve flattens because the first retry takes almost every soft decline, and later rounds have almost nothing left to work on.
  • The floor, 7.2%, is the 72 subscribers whose cards expired: 21 + 25 + 26, the cards that expire in December, January and February and fail the next month’s charge. No retry reaches them. Retrying all 72 three times, 216 calls, paid none.

The ₦17,092 is a break-even. A retry earns money as long as one attempt costs less than that. The processing fee in this lab is 1% of a successful charge, ₦185 on ₦18,500. If your acquirer charges a fee per attempt, put it against the figure.

Now doubt the figure. The mock draws each decline independently, so a payer who was short on the first try is no more likely to be short on the second. Real payers are. The break at the end of the lab changes the odds for a retried charge to 50% and the yield of a retry round falls to about 53%, ₦9,790 per charge sent. Three retries then recover less and take longer, and 10.7% churn remains. The replay trick that gave a clean table has a limit as well: it is valid here because outcomes do not depend on when you asked. On real data a log can replay only the schedules that are prefixes of the one you ran. To test a different schedule, run it on a share of subscribers and compare, as you would test a price.

Stopping declines before they happen

The expired card is the one decline you can see coming. The lab’s cards table gives each card an expiry month, and a saved card carries one too (exp_month in the authorisation). A watch list is a query: subscribers whose card expires this month or next. In the lab’s window 21, 25, 26 and 27 cards expire in the four months. Ask those patients for a new card before the date, by a message that names the card’s last four digits and not its number, and the hard decline never happens.

Two other tools exist. A card scheme’s account updater lets a merchant, through its acquirer, learn that a card was reissued. Visa Account Updater, per search summaries of Visa’s developer pages, lets issuers, acquirers and qualified merchants exchange updated account details (new numbers, expiry dates, closures) for recurring and card-on-file payments, in batch, through an API or in real time. It is offered through acquirers and issuers and not directly to every merchant, so confirm what your acquirer supportsas of 2026-11. Network tokens, above, serve the same purpose from the token service’s side. And the patient who updates a card at the payment page is a cardholder-initiated payment again, which is the safest way to refresh the stored consent.

Rules elsewhere, and in Nigeria

The rule that decides how much friction a recurring card payment needs is a regulator’s. The Reserve Bank of India’s notification of 16 June 2022 on processing e-mandates for recurring transactions raised the per-transaction limit for recurring card, prepaid instrument and UPI payments without an additional factor of authentication from ₹5,000 to ₹15,000. Search results, all news and law-firm commentary, describe a Digital Payments – E-mandate Framework, 2026, dated 21 April 2026, that keeps the ₹15,000 threshold and requires additional authentication for the first debit under any e-mandate. This build did not read the RBI’s 2026 text and the sources give different circular numbers, so check the RBI’s current frameworkas of 2026-11. It is India’s rule and not Nigeria’s. It shows a regulator bounding recurring pulls by amount, with a first authentication.

For Nigeria, a search for a CBN rule that specifically covers card tokenisation or recurring card-not-present payments found none. The search returned the CBN’s card issuance guidelines and its Guidelines on Operations of Electronic Payment Channels (2020) and could not confirm whether either addresses tokens or recurring charges. This chapter therefore states no Nigerian rule on card-on-file. Read those documents and your acquirer’s terms before you launch. The Nigerian pull rail that has its own scheme text is direct debit, which the earlier chapter covers: it carries a mandate checked at the payer’s bank, which a saved card does not have.

Where it goes wrong

Name the failures first.

Storing the number. The refill job that keeps PANs puts the whole service in scope and leaks the data to anyone who can read the table. Keep the provider’s code, the last four digits and the expiry month.

Retrying everything. Hard declines are retried until the schedule ends and nothing is recovered. Classify by the decline code and stop on a hard one.

Retrying forever. A schedule without a limit never accepts a no, and the schemes may fine the excess. Cap the tries and hand the invoice to a person.

Believing the first retry yield. The mock’s 92% is a property of its random draws. Measure each round on your own data.

A new reference on every run. A restarted job charges twice. Build the reference from patient, cycle and try.

Charging a changed amount without telling the patient. A card has no cap at the bank to stop it. The dispute that follows is one you lose, because the only evidence is a first payment for a different amount.

Treating a failed attempt as money. The mock fills fee_kobo on a failed on-file charge. A failed charge posts nothing and carries no fee in the ledger.

How the books look

A successful renewal posts like any card payment: the provider owes Tallowmere the money until settlement, as the chapter on a card payment end to end showed. A failed renewal posts nothing, and you keep a table of attempts and their reasons, as the direct debit chapter said for refused debits. The lab ends on a check that ties them: the provider’s settlement for the next day has a gross figure, and it equals the 1,000 first payments plus every renewal your job counted, to the kobo.

LAB Save a card, bill 1,000 subscribers for four months, and measure what each retry recovers ~45 MIN
YOU NEEDPython 3.9 or later (standard library only)labs/finance with the data generated (python3 generate.py, then python3 cards.py)Two terminalsNo Docker, no packages

You work in labs/finance. Every step is Python run from that folder against the mock provider. The key sk_test_owoleaf_mock is its fixed test key. There is no sqlite3 program in the steps. Mock state is seeded and shared by the steps, so the numbers below match if you start the provider fresh and run steps 1 to 3 in order. The provider draws declines from a seeded random generator, so the numbers depend on the history of calls it has served: restart it with --fresh and run steps 1 to 3 once, in order, and the output is identical every time. Repeat a step on the same running provider and you get nearby numbers.

1. Start the provider, save a card and charge it. In a first terminal:

cd labs/finance
python3 generate.py          # skip if data/finance.sqlite exists
python3 cards.py             # skip if the cards table exists
python3 mock_provider.py --fresh

In a second terminal, run this. It makes the first charge with the patient present, keeps the returned code, and then renews with it, with no card number.

cd labs/finance
python3 - <<'PY'
import datetime as dt, json, urllib.error, urllib.request

BASE, KEY = "http://127.0.0.1:8101", "sk_test_owoleaf_mock"

def call(method, path, body=None, headers=None):
    h = {"Authorization": f"Bearer {KEY}", "Content-Type": "application/json", **(headers or {})}
    data = json.dumps(body).encode() if method == "POST" else None
    req = urllib.request.Request(BASE + path, data=data, headers=h, method=method)
    try:
        with urllib.request.urlopen(req) as r:
            return r.status, json.load(r), dict(r.headers)
    except urllib.error.HTTPError as e:
        return e.code, json.load(e), dict(e.headers)

AMOUNT = 1_850_000                                    # N18,500: Tallowmere's average refill, in kobo
CUSTOMER = "C0000042"

# 1. The first charge: the patient is at the checkout, enters the card, and we ask the provider to keep it.
status, body, _ = call("POST", "/charges", {
    "reference": "TALLOW-FIRST-0001", "amount_kobo": AMOUNT, "customer_ref": CUSTOMER,
    "card_number": "4084084084080001", "save_card": True, "exp_month": "2027-02"})
charge = body["charge"]
print("first charge:", status, charge["status"], "| card_last4", charge["card_last4"])
print("authorization:", json.dumps(charge["authorization"]))
print("does the response hold the card number?", "4084084084080001" in json.dumps(body))
code = charge["authorization"]["authorization_code"]

def renew(ref, billing_date=None, customer=CUSTOMER, headers=None):
    req = {"reference": ref, "amount_kobo": AMOUNT, "customer_ref": customer, "authorization_code": code}
    if billing_date:
        req["billing_date"] = billing_date
    return call("POST", "/charges", req, headers)

# 2. The renewals: no card number, no patient. billing_date says which day this charge is for.
for label, day in (("December 2026", "2026-12-01"), ("February 2027 (the expiry month)", "2027-02-01"), ("March 2027", "2027-03-01")):
    status, body, _ = renew("TALLOW-REF-" + day, day)
    c = body["charge"]
    print(f"on file, {label:<32} -> {c['status']:<8} {c['gateway_response']:<13} decline_code={c.get('decline_code')}")

# 3. Three ways a renewal call goes wrong in your own code.
status, body, _ = renew("TALLOW-REF-2026-12-01", "2026-12-01")
print(f"same reference again            -> HTTP {status} {body['error']}; first charge was {body['charge']['status']}")
status, body, _ = renew("TALLOW-REF-OTHER-CUSTOMER", customer="C0000043")
print(f"someone else's code             -> HTTP {status} {body['error']}")
first = renew("TALLOW-REF-KEYED", "2026-12-01", headers={"Idempotency-Key": "refill-C0000042-2026-12"})
again = renew("TALLOW-REF-KEYED", "2026-12-01", headers={"Idempotency-Key": "refill-C0000042-2026-12"})
print(f"same Idempotency-Key twice      -> HTTP {first[0]} then HTTP {again[0]}, Idempotent-Replayed: {again[2].get('Idempotent-Replayed')}, same charge id: {first[1]['charge']['id'] == again[1]['charge']['id']}")

# 4. Test card 0007: saved with an expiry at the end of THIS month.
status, body, _ = call("POST", "/charges", {"reference": "TALLOW-FIRST-0007", "amount_kobo": AMOUNT, "customer_ref": CUSTOMER,
                                            "card_number": "4084084084080007", "save_card": True})
auth = body["charge"]["authorization"]
print("card 0007 saved, expires", auth["exp_month"])
code = auth["authorization_code"]
today = dt.datetime.now(dt.timezone(dt.timedelta(hours=1))).date()
next_month = (today.replace(day=1) + dt.timedelta(days=32)).replace(day=1)
for label, day in (("this month", today), ("next month", next_month)):
    c = renew("TALLOW-REF-0007-" + day.isoformat(), day.isoformat())[1]["charge"]
    print(f"card 0007, billed {label:<10} -> {c['status']:<8} {c['gateway_response']}")
PY
first charge: 200 success | card_last4 0001
authorization: {"authorization_code": "AUTH_ba8408e4ae", "card_last4": "0001", "exp_month": "2027-02", "reusable": true}
does the response hold the card number? False
on file, December 2026                    -> success  Approved      decline_code=None
on file, February 2027 (the expiry month) -> success  Approved      decline_code=None
on file, March 2027                       -> failed   Expired card  decline_code=expired_card
same reference again            -> HTTP 409 duplicate_reference; first charge was success
someone else's code             -> HTTP 400 invalid_authorization
same Idempotency-Key twice      -> HTTP 200 then HTTP 200, Idempotent-Replayed: true, same charge id: True
card 0007 saved, expires 2026-11
card 0007, billed this month -> success  Approved
card 0007, billed next month -> failed   Expired card

The authorisation code is different on every run. The response never contains the card number: the provider holds it, you hold the code. A renewal in the card’s expiry month succeeds, and the month after answers expired_card. The same reference again is a 409 that returns the first charge, someone else’s code is refused, and a repeated Idempotency-Key replays the first answer with the same charge id. Card 0007 is saved with an expiry at the end of the current month, so a charge billed next month fails. The dates in step 4 come from today’s date in West Africa Time (UTC+1), the provider’s own clock, so the line card 0007 saved, expires ... shows the month you run it in (2026-11 when this was written, on 14 November 2026). The two lines after it are the same in every month: this month succeeds and next month fails.

2. Enrol 1,000 subscribers. The script takes each customer’s newest card from the lab’s own cards table, keeps only cards that outlast the first renewal, makes a first payment for each with save_card, and stores the codes in your own subscriptions.sqlite. It starts by resetting the provider.

python3 - <<'PY'
import json, sqlite3, urllib.error, urllib.request
from collections import Counter

BASE, KEY = "http://127.0.0.1:8101", "sk_test_owoleaf_mock"
AMOUNT = 1_850_000                                    # N18,500 a month, in kobo
FIRST_RENEWAL = "2026-12"                             # cards that expire before the first renewal are not enrolled

def call(method, path, body=None):
    h = {"Authorization": f"Bearer {KEY}", "Content-Type": "application/json"}
    data = json.dumps(body).encode() if method == "POST" else None
    req = urllib.request.Request(BASE + path, data=data, headers=h, method=method)
    try:
        with urllib.request.urlopen(req) as r:
            return json.load(r)
    except urllib.error.HTTPError as e:
        return json.load(e)

call("POST", "/admin/reset", {})                      # an empty provider
call("POST", "/admin/faults", {"decline_rate": 0.0})

# Each customer's newest card in the lab's own data: a token (card_ref) and an expiry month, never a number.
lab = sqlite3.connect("data/finance.sqlite")
rows = lab.execute("""
    SELECT c.ref, k.exp_month FROM customers c JOIN cards k ON k.customer_id = c.id
    WHERE k.id = (SELECT id FROM cards WHERE customer_id = c.id ORDER BY first_used_at DESC, id DESC LIMIT 1)
      AND k.exp_month >= ?
    ORDER BY c.id LIMIT 1000""", (FIRST_RENEWAL,)).fetchall()

repeat = lab.execute("""
    WITH s AS (SELECT ROW_NUMBER() OVER (PARTITION BY a.card_id ORDER BY t.created_at, t.id) AS nth
               FROM card_attempts a JOIN transactions t ON t.id = a.transaction_id WHERE t.status = 'succeeded')
    SELECT SUM(nth > 1), COUNT(*) FROM s""").fetchone()
print(f"successful card top-ups on a card Owoleaf had already seen: {repeat[0]} of {repeat[1]}")

subs = sqlite3.connect("subscriptions.sqlite")        # your own table: the provider's code is all you keep
subs.executescript("""DROP TABLE IF EXISTS subscribers;
    CREATE TABLE subscribers (customer_ref TEXT PRIMARY KEY, authorization_code TEXT NOT NULL,
                              exp_month TEXT NOT NULL, amount_kobo INTEGER NOT NULL)""")
paid = 0
for ref, exp in rows:
    r = call("POST", "/charges", {"reference": f"RX-ENROL-{ref}", "amount_kobo": AMOUNT, "customer_ref": ref,
                                  "card_number": "4084084084080001", "save_card": True, "exp_month": exp})["charge"]
    subs.execute("INSERT INTO subscribers VALUES (?,?,?,?)", (ref, r["authorization"]["authorization_code"], exp, AMOUNT))
    paid += AMOUNT if r["status"] == "success" else 0
subs.commit()

print(f"enrolled {len(rows)} subscribers; first month collected {paid} kobo")
print("card expiry months in the next billing window:")
by_month = Counter(exp for _, exp in rows)
for m in ("2026-12", "2027-01", "2027-02", "2027-03"):
    print(f"  {m}: {by_month[m]:>3} cards expire at the end of the month")
print(f"  later: {sum(n for m, n in by_month.items() if m > '2027-03'):>3}")
print("stored per subscriber:", subs.execute("SELECT * FROM subscribers LIMIT 1").fetchone())
PY
successful card top-ups on a card Owoleaf had already seen: 8360 of 10280
enrolled 1000 subscribers; first month collected 1850000000 kobo
card expiry months in the next billing window:
  2026-12:  21 cards expire at the end of the month
  2027-01:  25 cards expire at the end of the month
  2027-02:  26 cards expire at the end of the month
  2027-03:  27 cards expire at the end of the month
  later: 901
stored per subscriber: ('C0000001', 'AUTH_3a7cfc8748', '2027-04', 1850000)

The first line is the reason to save cards: 8,360 of the 10,280 successful card top-ups in Owoleaf’s data used a card it had already seen. 99 subscribers have a card that expires in the four months. The last one of them, in March, only fails in April, outside the window. The code AUTH_... differs on your machine.

3. Bill four months and replay the schedules. One pass bills everyone on four due dates with up to three retries, on days 2, 5 and 9, but only after a soft decline. It sets the provider’s decline_rate to 8% for the pass and back to zero at the end. Then it replays schedules of 0 to 3 retries from the log, retries the expired cards on purpose, and checks the total against the provider’s settlement. It takes about 30 seconds.

python3 - <<'PY'
import datetime as dt, json, sqlite3, urllib.error, urllib.request

BASE, KEY = "http://127.0.0.1:8101", "sk_test_owoleaf_mock"
CYCLES = ["2026-12-01", "2027-01-01", "2027-02-01", "2027-03-01"]   # the monthly due dates
RETRY_DAYS = [0, 2, 5, 9]                                           # round 0 is the due date; retries come 2, 5 and 9 days later
DECLINE = [0.08, 0.08, 0.08, 0.08]                                  # chance a charge is declined, by round (the mock draws it afresh each time)
HARD = {"expired_card"}                                             # declines a retry cannot change

def call(method, path, body=None):
    h = {"Authorization": f"Bearer {KEY}", "Content-Type": "application/json"}
    data = json.dumps(body).encode() if method == "POST" else None
    req = urllib.request.Request(BASE + path, data=data, headers=h, method=method)
    try:
        with urllib.request.urlopen(req) as r:
            return json.load(r)
    except urllib.error.HTTPError as e:
        return json.load(e)

subs = {ref: (auth, amount) for ref, auth, amount in sqlite3.connect("subscriptions.sqlite").execute(
    "SELECT customer_ref, authorization_code, amount_kobo FROM subscribers")}

# One pass with the most generous schedule (three retries). log[(ref, due)] is what happened, one letter per
# attempt: S success, F soft decline (insufficient funds), H hard decline (expired card).
log, hard_cases, sent, collected = {}, [], 0, 0
active = set(subs)
for due in CYCLES:
    pending = sorted(active)                                        # everyone still subscribed is due today
    for rnd, offset in enumerate(RETRY_DAYS):
        call("POST", "/admin/faults", {"decline_rate": DECLINE[rnd]})
        day = (dt.date.fromisoformat(due) + dt.timedelta(days=offset)).isoformat()
        still = []
        for ref in pending:
            auth, amount = subs[ref]
            c = call("POST", "/charges", {"reference": f"RX-{ref}-{due}-t{rnd}", "amount_kobo": amount, "customer_ref": ref,
                                          "authorization_code": auth, "billing_date": day})["charge"]
            sent += 1
            letter = "S" if c["status"] == "success" else ("H" if c.get("decline_code") in HARD else "F")
            log[(ref, due)] = log.get((ref, due), "") + letter
            if letter == "S":
                collected += amount
            elif letter == "F":
                still.append(ref)                                   # only a soft decline is worth another try
            else:
                hard_cases.append((ref, due))
        pending = still
    for ref in pending:                                             # retries used up
        active.discard(ref)
    active -= {ref for ref, d in hard_cases if d == due}            # card expired: a person must ask for a new card
call("POST", "/admin/faults", {"decline_rate": 0.0})
print(f"one pass: {sent} charge calls, {collected} kobo collected, {len(hard_cases)} hard declines")

def replay(max_retries):
    """What a schedule with at most max_retries would have done, read off the log. Valid only while
    a decline does not depend on how many times or when you asked, which is true of this mock."""
    live = set(subs)
    retries = got = 0
    lapsed = {"declined": 0, "card expired": 0}
    for due in CYCLES:
        for ref in sorted(live):
            seen = log[(ref, due)][: max_retries + 1]
            retries += len(seen) - 1
            if seen[-1] == "S":
                got += subs[ref][1]
            else:
                live.discard(ref)
                lapsed["card expired" if seen[-1] == "H" else "declined"] += 1
    return retries, got, len(live), lapsed

print()
print("what each round of the pass achieved:")
print(f"{'round':>5} {'days after due':>14} {'charges':>8} {'paid':>6} {'paid %':>7} {'₦ per charge sent':>18}")
for rnd, offset in enumerate(RETRY_DAYS):
    sent_r = sum(1 for s in log.values() if len(s) > rnd)
    paid_r = sum(1 for s in log.values() if len(s) > rnd and s[rnd] == "S")
    print(f"{rnd:>5} {offset:>14} {sent_r:>8} {paid_r:>6} {100 * paid_r / sent_r:>6.1f}% {'₦' + format(paid_r * 1850000 / sent_r / 100, ',.0f'):>18}")

print()
print(f"{'retries allowed':>15} {'retries sent':>12} {'collected':>13} {'active':>7} {'lost: declined':>15} {'lost: expired':>14} {'churn':>6}")
for k in range(4):
    retries, got, live, lapsed = replay(k)
    print(f"{k:>15} {retries:>12} {'₦' + format(got // 100, ','):>13} {live:>7} {lapsed['declined']:>15} "
          f"{lapsed['card expired']:>14} {100 * (len(subs) - live) / len(subs):>5.1f}%")

# What a loop that retries every decline would do with the expired cards. These are real calls.
blind_paid = 0
for ref, due in hard_cases:
    for rnd in (1, 2, 3):
        day = (dt.date.fromisoformat(due) + dt.timedelta(days=RETRY_DAYS[rnd])).isoformat()
        c = call("POST", "/charges", {"reference": f"RX-BLIND-{ref}-{due}-t{rnd}", "amount_kobo": subs[ref][1], "customer_ref": ref,
                                      "authorization_code": subs[ref][0], "billing_date": day})["charge"]
        blind_paid += c["status"] == "success"
print()
print(f"retrying the {len(hard_cases)} expired cards three times each: {3 * len(hard_cases)} calls, {blind_paid} paid")

# The check that closes the loop: what the provider will pay out for today's captures.
today = dt.datetime.now(dt.timezone(dt.timedelta(hours=1))).date()
gross = call("GET", f"/settlements?date={today + dt.timedelta(days=1)}")["gross_kobo"]
enrolled = len(subs) * 1_850_000
print(f"provider settlement gross {gross} = enrolment {enrolled} + renewals {collected}: {gross == enrolled + collected}")
PY
one pass: 4232 charge calls, 7142850000 kobo collected, 72 hard declines

what each round of the pass achieved:
round days after due  charges   paid  paid %  ₦ per charge sent
    0              0     3933   3585   91.2%            ₦16,863
    1              2      276    255   92.4%            ₦17,092
    2              5       21     19   90.5%            ₦16,738
    3              9        2      2  100.0%            ₦18,500

retries allowed retries sent     collected  active  lost: declined  lost: expired  churn
              0            0   ₦59,514,500     695             240             65  30.5%
              1          275   ₦70,559,000     908              21             71   9.2%
              2          297   ₦71,317,500     926               2             72   7.4%
              3          299   ₦71,428,500     928               0             72   7.2%

retrying the 72 expired cards three times each: 216 calls, 0 paid
provider settlement gross 8992850000 = enrolment 1850000000 + renewals 7142850000: True

Read it from the top. Round 0 pays 91.2% of the charges sent. Round 1 sends 276 charges and 255 are paid. Rounds 2 and 3 send 21 and 2. With no retry, 30.5% of subscribers are lost. One retry takes that to 9.2%, two to 7.4% and three to 7.2%. The remaining 72 are the expired cards, which retrying three times each (216 calls) did not move. The last line closes the books: the provider’s settlement gross for the next day equals 1,000 first payments plus the renewals the script counted.

Change one line of step 3. A payer who was short on the first try is likely to be short again, so set the decline chance for retried charges to 50%:

DECLINE = [0.08, 0.5, 0.5, 0.5]

Do not restart the provider. In the same provider process that ran steps 1 to 3 from a fresh start, run step 2 again, then the changed step 3. The output is:

one pass: 4369 charge calls, 6968950000 kobo collected, 72 hard declines

what each round of the pass achieved:
round days after due  charges   paid  paid %  ₦ per charge sent
    0              0     3874   3511   90.6%            ₦16,767
    1              2      291    154   52.9%             ₦9,790
    2              5      137     70   51.1%             ₦9,453
    3              9       67     32   47.8%             ₦8,836

retries allowed retries sent     collected  active  lost: declined  lost: expired  churn
              0            0   ₦58,275,000     670             266             64  33.0%
              1          287   ₦64,583,500     795             135             70  20.5%
              2          425   ₦67,987,500     861              67             72  13.9%
              3          495   ₦69,689,500     893              35             72  10.7%

retrying the 72 expired cards three times each: 216 calls, 0 paid
provider settlement gross 8818950000 = enrolment 1850000000 + renewals 6968950000: True

Round 1 now pays 52.9% and returns about ₦9,790 per charge sent. Three retries leave 10.7% churn where independent draws left 7.2%, and each extra round recovers less. Now decide what an attempt may cost before the retry stops paying for itself, and what your own data would need to show before you trusted either table. Then add a pre-expiry reminder to the script: skip the charge for subscribers on the watch list and count what the reminder would have to achieve to remove the 72.

ARTEFACT Write the recurring-billing retry and card-update policy ~50 MIN
YOU PRODUCERecurring-billing retry and card-update policy

Template

# Recurring-billing retry and card-update policy: <product>
Owner (billing PM) · Engineer · Version · Date
Approvers: <head of payments>, <compliance> · Decision needed by <date>: <the decision>

## 1. What we store
Per customer: <token or provider code>, <last four digits>, <expiry month>, <time and wording of consent>.
Never stored: <card number, security code>. Where it lives and who can read it: <...>

## 2. Retry schedule by decline reason
| Reason | Class (soft/hard) | Retry days after the due date | Limit | After the limit |
|---|---|---|---|---|

## 3. When we stop and ask the customer
<The trigger, who contacts the customer, how, and what they are asked to do.>

## 4. Customer messages
<Before the charge · After a soft decline · Card needs updating. Each states amount, date, last four digits.>

## 5. How we measure success
<Measure, baseline, target, review date. What we compare against.>

## 6. How this could be wrong
<One assumption, and the number that would show it is wrong.>

## 7. Out of scope and open questions
<...>
WORKED EXAMPLE

At a real company a billing PM writes this with an engineer, and the head of payments and compliance sign it. Tallowmere has no payments department: Osagie writes it with Bukola, and the person who looks after the shop’s money signs.

Refill billing policy. Owner: Osagie · Engineer: Bukola · Version 1 · 20 November 2026. Decision needed by 4 December 2026: switch the schedule on for January.

1. Stored. Per patient: the provider’s authorisation code, the last four digits, the expiry month, and the time and wording of consent. No card number is kept.

2. Schedule. Last month 27 of 300 renewals at ₦18,500 were declined: 11 expired cards and 16 insufficient funds.

Reason Class Retry days after due Limit
insufficient_funds Soft 2 and 5 Two retries
expired_card Hard Never None

The limit of two is our choice, not a scheme rule. In the lab, 276 first retries paid 255 (92.4%), about ₦17,092 per charge sent, and churn fell from 30.5% to 9.2%. A second round sent 21 and took it to 7.4%. Retrying 72 expired cards paid none.

3. Stop and ask. After the second failed retry, or on any hard decline, the job stops. Osagie’s team asks the patient for a new card, and the invoice stays open.

4. Messages. Before a changed charge, after a first decline, and to request a new card. Each names the amount and the last four digits only.

5. Success. Share of declined renewals paid within two retries, and ₦ recovered per charge sent. Baseline: last month’s 27 of 300 declined (9.0%). Recovery has no baseline, so January’s attempts table sets it. Review on 1 February 2027.

6. Wrong if. The lab draws declines independently and left 7.4% churn after two retries. Its break, with a 50% chance of a repeat decline, paid 52.9% on the first retry and left 13.9% churn after two. If our first retry pays near 53%, two retries are too few.

7. Out of scope. Account updaters and provider choice.

Now you

A 30-person meal-kit company in Port Harcourt (unnamed) bills 2,000 households ₦12,000 a month on saved cards. It keeps the provider’s code, the last four digits and the expiry month, and has never retried a decline. Its first-month report shows 160 soft declines and 40 expired cards. Assume, and say you assume, that a retry on a soft decline pays as often as the lab’s break table shows: 52.9% on the first retry, then 51.1% and 47.8%. Scale the lab’s 99 cards expiring in four months from 1,000 subscribers to 2,000 households to size the card-update watch list, and state that as an assumption. Write the full policy, with a retry limit you can defend from the break table’s churn, not the clean one. Say who writes it and who signs it. The head of payments and compliance read it, and it supports one decision: whether to switch the retry schedule on at the next billing cycle.

Self-check

DECIDE

Tallowmere's refill job stores card numbers, retries every decline nightly for ten nights, and loses patients to declines each month. Bukola can rebuild it in a month. About 11 of last month's 27 declines were expired cards. A provider offers saved cards through its own code, and an account updater costs extra. Which plan do you choose?

READING
  1. DOC
    EMV Payment Tokenisation Specification: Technical Framework EMVCo, 2021

    The card industry's own framework for network tokens: the token service, token domains and the Payment Account Reference. Read the overview and the lifecycle sections to see what a token can be limited to. This build saw the publications listing only through search summaries, so confirm the current version.

  2. DOC
    Tokenization Guidelines Information Supplement PCI Security Standards Council, 2011

    The Council's advice on how tokenisation affects the scope of a merchant's card data environment. Read what makes a token safe and where it does not shrink scope. It is advisory and from 2011, and this build did not read the PDF.

  3. DOC
    Processing of e-mandates for recurring transactions Reserve Bank of India, 2022

    A comparison from another regulator: a per-transaction ceiling on recurring card payments without extra authentication. Read it for how a rule can bound a pull. It is India's rule and not Nigeria's, and later directions are reported that this build did not read.

  4. DOC
    Recurring Charges Paystack, 2026

    A vendor's design for saved authorisations: the reusable flag and the charge-authorisation call. Compare its fields with the lab's. It is a vendor's description of its own product and not a scheme rule.

  5. POST
    How to avoid excessive retries penalties PayPal, 2026

    A vendor's account of Visa's decline categories and retry caps. Read it for the vocabulary of hard and soft declines and what a penalty looks like. It is a vendor's claim, its figure differs from other sources, and it is not Visa's rulebook.

  6. DOC
    Visa Account Updater overview Visa, 2026

    Visa's developer page for the service that tells merchants a card on file was reissued. Read what it covers and how a merchant enrols. This build saw it through search summaries only, so confirm its current terms.

All companies and people in these examples are fictional. Any resemblance to a real business or person is unintended.

RECALL CARDS Tap to flip. They join your review deck when you mark the lesson complete.
NEXT: A ledger at scale: hot accounts, balances, sharding →