WORKINGCHAPTER 17

Direct debit and mandates

A pull payment needs permission first. Get the mandate, the cap and the retry rule right, and the bank's refusal codes tell you what to do next; get them wrong and you collect twice or never

50 MINPAYMENTSUPDATED 2026-11-14
PREDICT

A mandate is active, capped at ₦50,000 and set to monthly. Tallowmere sends a debit of ₦18,500, then a second debit of ₦18,500 with a different reference, a minute later on the same day. The payer's account holds enough for both. What does the lab's switch answer to the second debit?

Push and pull

Every payment you met in module 1 was a push. The payer decides, gives an instruction, and the money moves with it: a NIP transfer, a card tap, a wallet top-up. The payer is present and is the authority for each payment.

A pull works the other way round. The payee starts the payment, and the payer’s bank releases the money because the payer gave permission earlier. Direct debit is the standard pull. So is a standing instruction a lender uses, and so is a card saved for later charges, which the later chapter on card-on-file and recurring payments covers in depth. Nigeria’s rails shows where each sits among the other rails.

Push Pull
Who starts it The payer The payee (the biller)
Authority for each payment The payer’s instruction now A mandate the payer gave earlier
The payer’s bank checks The payer’s identity and funds The mandate, its limits, and the funds
Risk the payee carries Little: the money arrives or the transfer fails The payer can run out of funds, revoke, or dispute
Risk the payer carries Paying the wrong account Being charged more or more often than agreed
Fits One-off and urgent payments Instalments, subscriptions, repeat bills

Pull payments exist because the payer would otherwise have to remember to push the same payment every month, and many forget. The cost is that the payee now acts alone, and the payer’s protection has to be built into the mandate and the rules around it.

What a mandate is

A mandate is the payer’s standing permission, held at the payer’s bank, for one named collector to take money from one named account within limits. Three parties are involved. The biller (also called the originator or creditor) is Tallowmere, which collects. The payer is the patient. The payer’s bank holds the account and decides whether to release each debit. The biller’s bank, or its provider, sends the debits.

In the lab’s switch, Owoleaf is the biller and POST /mandates takes these fields:

Field What it limits Example in the lab
reference The biller’s own id for the mandate. Used once TALLOW-MND-0001
payer_bank, payer_account Whose money, and where it sits B03, 2100000011
max_amount_kobo The most one debit may take 5,000,000 kobo, which is ₦50,000
frequency How often the payer expects debits: once, weekly, monthly or variable monthly
start_date, end_date When the permission begins and ends today, and a year on
customer_ref The biller’s own customer C0000042

Design the cap with care. Too low and a legitimate refill is refused with 61. Too high and the permission is wider than the payer understood, which is a complaint waiting for a bad month. A sound rule is the largest amount you expect, plus a margin you can explain to the payer in one sentence. Tallowmere’s refills run from ₦9,500 to ₦42,000, so a ₦50,000 cap leaves ₦8,000 above the largest refill, and the patient is told the figure.

The payer must authorise the mandate at their own bank. A mandate that the biller has created but the payer has not authorised is pending_authorisation, and it collects nothing.

The CBN’s Regulation for Direct Debit Scheme in Nigeria, 2018 (revised), is the latest version that search results show, and it uses the word “biller” where the 2010 guidelines used “originator”. Search summaries of it say the payer must sign a mandate to take part; that the payer’s bank must obtain the payer’s authority, on paper or electronically, before it activates the mandate; that a request to authenticate a mandate is handled within three business days, after which the mandate is treated as activated unless the payer’s bank declines it; that the payer’s bank may not ask the payer to confirm again at the point of each debit; that the biller’s bank accepts cancellation of a mandate only from the biller; and that a payer may claim through their own bank if a debit succeeds after cancellation. This build could not open the CBN’s site, so these points rest on search summaries, and the searches could not confirm that the 2018 Regulation is still the current textas of 2026-11. Read the Regulation itself before relying on any of it.. Read the Regulation itself before relying on any of it.

The lab’s authorisation is a single call that stands in for the payer’s bank. In a real scheme the steps are the scheme’s own, and they differ by bank. The lab also lets the payer’s bank revoke an active mandate. Who may cancel a real mandate, and where, is set by the scheme’s rules: the summary above has the biller’s bank accepting cancellation only from the biller, so check the text before you design a cancellation flow.

The life of a mandate

A mandate has a state, and each debit is checked against it. Name the states before the failures.

pending_authorisationactiverevokedexpiredcancelledrejectedpayer authorisespayer rejectspayer revokesend date passesbiller cancelsbiller cancelsThick box: the only state that accepts debits, and only from its start date to its end date.

Only an active mandate, inside its dates, accepts a debit. Pending, rejected, revoked, cancelled, expired and not-yet-started all answer 63. The mock keeps these as one outcome because that is what the biller needs to act on: this mandate cannot be used. The biller then asks why, by reading the mandate (GET /mandates/{id}) or by listening for the callback.

Two things in the picture matter in practice. Revoke and cancel are different people. In the lab the payer’s bank can revoke, and the biller may not even be told until the next debit fails. The biller cancels its own mandate when the service ends. A patient who stops the refills should have the mandate cancelled by Tallowmere, so that no later debit is attempted by mistake. Expiry is silent. Nothing changes a mandate’s stored state when its end_date passes. The switch works out expired whenever the mandate is read, and the debit fails 63. A collector that does not track end dates learns of them from a refusal.

A debit and its codes

A debit is one pull: POST /debits with the mandate id, a reference and an amount in kobo. The switch checks, in order, whether the reference was used before, whether the mandate exists and is active, whether the amount is within the cap, whether the payer’s bank is up, and whether the payer’s account can cover it. Every attempt is recorded and called back to the biller, successful or not.

Code Meaning Whose problem What the collector does
00 Approved. Money arrives as an inward credit Nobody’s Post it. Mark the invoice paid
51 Insufficient funds The payer’s balance, today Wait for a later day. Retry a limited number of times
61 Over the mandate’s cap The mandate does not allow this amount Never retry. Ask for a larger mandate, or split by agreement
63 Mandate not active The mandate’s state or dates Do not retry blindly. Read the mandate: pending or not yet started changes by itself, the rest needs a person
91 Payer’s bank not available The bank’s availability, today Retry soon, with a new reference: the attempt is recorded, so the old one answers 26. The lab’s collector does not handle it
26 Duplicate: the reference was used Your code Read the first attempt’s outcome. Do not treat it as a new result
07 Invalid account (at creating the mandate) The details you were given Correct the details, with the payer’s help

Read the “whose problem” column first. A 51 may change by tomorrow, so another try is reasonable. A 61 will not change however long you wait, and a 63 changes only when the mandate does (the payer authorises it, or its start date arrives, which a callback or a read tells you). Both describe the mandate, not the payer’s balance, so a blind nightly retry is wasted traffic. These codes are the lab’s, modelled on NIP-style codes. They are illustrative, and the real schemes publish their own lists.

One code needs more care. On a 26, the answer carries the first attempt’s status. In the lab, a reused reference for a debit that succeeded answers 26 and status: successful. The code is 26, not 00, and the collector must not post the amount a second time. This is the same discipline as an idempotency key, which the chapter on idempotency and moving money exactly once teaches in full and the lesson on idempotency lets you break. A reference makes a repeat safe. It also means a legitimate retry after a 51 must have a new reference.

What the switch does not check

The switch is a model of the other bank, and the other bank checks only some things. The lab’s step 3 shows what it leaves to you.

Frequency is yours. The mock enforces once (a second debit after a success answers 63) and treats weekly, monthly and variable as labels. The cap is per debit: the switch does not add up a month’s debits against it. Two debits on the same day, with two references, are both approved. Whatever your real scheme enforces, a collector that sends the monthly debit twice because a job ran twice will take the money twice, and the payer’s bank may have no way to know you meant once. Store when each invoice was last collected and refuse to send a second debit for it. An invoice id, used in the reference, makes the duplicate hit 26.

The payer’s notice is yours. The mock sends no message to the payer. Before a debit, and especially one that differs from the last, the payer should be told the amount and the date.

UK Direct Debit, as a comparison: GoCardless, a payments vendor whose description is a vendor’s claim and not the scheme’s text, says customers must be told in advance of each payment, that a payer who claims a payment taken in error is refunded by their own bank first, and that the bank then recovers the money from the collector through an indemnity claimas of 2026-11. In India, the Reserve Bank of India’s notification of 16 June 2022 on processing e-mandates for recurring transactions lets a recurring card, wallet or UPI payment go ahead without additional authentication up to ₹15,000 per transaction, and requires additional authentication above that and when the mandate is registered. News reports describe a consolidated framework in 2026 that keeps the ₹15,000 threshold; this build did not read that text, so check the RBI’s current frameworkas of 2026-11. Neither is Nigeria’s rule. They show what other schemes put around a pull: an advance notice, a threshold for extra authentication, and a refund path that runs through the payer’s own bank.

For Nigeria this search found no source for a notice period to the payer, so the chapter states none. Nor does it state how long a payer must give to cancel: lender guides give figures, and none was checked against the CBN’s text.

The Nigerian schemes, in outline

Two instruments carry most pull payments in Nigeria. The first is the direct debit scheme. Search summaries of NIBSS’s page say NIBSS Direct Debit (NDD) is a web-based electronic mandate library, which holds the mandate instructions that subscribers give to billers and institutionsas of 2026-11. The mandate lives in one shared place and every participating bank can check a debit against it. Aggregator and lender guides describe an electronic mandate (an e-mandate) being activated when the payer authenticates at their bank. Lendsqr, a lending-software vendor whose description is a vendor’s claim, says most banks need the payer to send a small transfer, usually ₦50, to a designated NIBSS e-mandate activation account from the account on the mandate, and that the mandate activates once the transfer completes. Other vendors’ documents show a ₦100 token in some cases, and the vendors give different activation timesas of 2026-11. The method, the amount and the account differ by provider and bank, and this build could not read NIBSS’s own documents. Take them from the scheme’s current documents and your provider.

The second is the Global Standing Instruction, used by lenders. The CBN’s Operational Guidelines on Global Standing Instruction (GSI) for individuals, circular FPRD/DIR/GEN/CIR/07/056 of July 2020, are limited to recovering loans from individuals, treat the GSI as a last resort for the creditor bank, and have NIBSS run the operation for banks using customers’ Bank Verification Numbersas of 2026-11. Those points rest on search summaries of the circular. A circular of January 2022 appears in search results, and sources disagree on whether it amended the guidelines or circulated them again. The loan products chapter in the Lending course shows the same rail on the loan side, as the repayment rail of two of Owoleaf’s products. A direct debit is a mandate for one named biller over one named account. A GSI is a standing instruction that reaches a defaulting borrower’s accounts across banks. They solve different problems, and a lender chooses between them for its reasons.

Representment, taking a second attempt at the same debit, is where this build could confirm least. Search summaries of the 2017 guidelines, which appear in results as an exposure draft of January 2017 with the final text not confirmed, say a biller’s bank may not use direct debit to recover arrears after a fixed payment fails, with an exception for re-presentment or where the biller had told the payeras of 2026-11. The 2010 guidelines are older; the 2017 text says it supersedes them, and the 2018 Regulation came after. This build could not open any of them and could not find the exact limit on re-presentment, so it states none. The lab’s collector retries a 51 up to twice. That is the lab’s policy for teaching, and it may be more than the current rules allow. Set your own limit from the current text, never from the lab.

Retries and their limits

Name the failure first. A retry is not free. Each attempt on a 51 is another refused debit, and the payer may see it. What a refusal costs the payer or the biller is set by the banks and the scheme, so check it before you plan a retry. A collector that retries daily without limit never accepts a no.

A good retry rule has four parts, and the lab’s collector has all of them.

First, only retry what can change. A 51 can change tomorrow. A 61, and a 63 from a revoked, cancelled, rejected or expired mandate, cannot, so they stop the collector at once and go to a person. A 91 is the payer’s bank being unavailable, which also passes, so it deserves a retry soon. The lab’s collector sends it to a person, to keep the rule short; adding it is a one-line change to decide.

Second, cap the number of tries. The lab allows the first try and two retries, three attempts in all, one per day.

Third, every retry is a new reference. The first attempt used TALLOW-REFILL-C-try1. Sending it again returns 26 and tries nothing. The next day’s attempt is TALLOW-REFILL-C-try2, a new debit. The reference carries the try number, so a log shows the full history of one invoice.

Fourth, stop in a way a person can pick up. After the last try, the invoice goes to Ufuoma’s queue with the codes it received. A phone call that starts “your account was short on three days” is better than one that starts “we could not collect”.

The lab’s last experiment shows the limit of this idea. With 30% of debits refused 51 at random, retries recover 28 of 100 orders, almost exactly what independent draws predict. A real payer who was short on the first is likely to be short on the second, because the reason is the same. So the recovery from a retry in your own data will be lower than the mock’s. Measure it per day, by cohort, before you pay for the attempts.

Where it goes wrong

Name the failures first, because each of them looks like success on the dashboard.

Debiting before the mandate is active. The mandate is created and the collector runs the same minute. Every debit answers 63. The fix is to wait for the mandate’s mandate.active callback, or read its state, before the first debit.

Treating a revoked mandate as a one-off fault. The payer closed the mandate at their bank. Ten nightly retries of 63 reach a payer’s bank that already told you no. Stop at the first 63, read the mandate, and ask the payer for a new one.

Debiting more than the mandate allows. A refill rises from ₦42,000 to ₦60,000 and the cap is ₦50,000. Every attempt answers 61. The patient was never asked about the new price. Ask for a bigger mandate with the patient’s agreement. Splitting one invoice into two debits under the cap, without telling the patient, avoids the code and defeats its purpose.

Collecting twice. A job that crashes after sending and restarts sends again, with a new reference built from a timestamp. Both debits succeed, because the mock does not know your schedule. Build the reference from the invoice, so the second send is a 26.

Posting a 26 as a new success. The duplicate answer carries the first attempt’s status. Read the code, not only the status.

Losing the attempt. A refused debit moves no money, so a ledger that records only money records nothing. Keep an attempt table that records every debit and its code, as the mock does with GET /debits. Without it you cannot say how many tries an invoice has had, and the retry limit cannot hold.

Treating a callback as optional. The mock calls back every debit and mandate change, signed with HMAC-SHA256, as it did for inward credits. Verify the signature, as the chapter on transfers and virtual accounts teaches for callbacks, and act on mandate.revoked at once, not at the next failed debit.

How the books look

A successful debit is an inward credit. In the lab it counts in the switch’s settlement position (inward_kobo), and for Tallowmere it clears a claim. When the refill is invoiced, Tallowmere records what the patient owes. When the debit succeeds, the posting is, in kobo:

Account Direction Amount Why
bank debit 1,850,000 ₦18,500 arrived in the bank account
receivable:patient credit 1,850,000 The claim on the patient is cleared

Debits equal credits. This follows the rule you saw in module 1: a failed attempt has no entries, and a posted transaction balances. A 51, a 61 and a 63 post nothing. The attempt log records them instead.

The check at the end is a reconciliation. In step 4 the collector paid ₦40,800.00 across two orders, 4,080,000 kobo, and the switch’s inward_kobo rose by exactly 4,080,000. If those two numbers differ, either a debit was collected that your books do not know about (a lost callback, say) or one your books show was never collected. Find which before anything else is posted.

The mock models none of the lifecycle after a successful debit. A payer who disputes a debit, a bank that returns one, and a refund of a collected amount are all outside the lab. The UK comparison above shows that a real scheme has them, and a collector has to handle a collected debit that comes back later.

Who uses it, and the other pull rail

Subscription businesses, utilities, insurers and schools use direct debit for the same reason as Tallowmere: payments that repeat, at a known size, from a payer who would rather not remember. Lenders use it to collect instalments, where the payer’s refusal is a credit signal and not only a collection problem. The Lending course’s chapter on loan products puts the repayment rail among the choices that shape a loan.

A card saved for later charges is the other pull rail. It also works on the payer’s earlier consent, it also meets a decline, and it fails differently: an expired card, a stale token, a payer who changed banks. The chapter on card tokenisation, card-on-file and recurring payments in module 3 teaches it fully. The question to ask of either rail is the same. What did the payer agree to, who can check that agreement on each payment, and which refusals can still change?

LAB Create, authorise and revoke a mandate, read every refusal code, and write a collector that retries only a 51 ~40 MIN
YOU NEEDPython 3.9 or later (standard library only)labs/finance with the data generated (python3 generate.py)Three terminalsNo Docker, no packages

You work in labs/finance. Every step is Python run from that folder against the mock switch. The key sw_test_owoleaf_mock is the switch’s fixed test key. There is no sqlite3 program in the steps. Mandate ids are drawn from a seeded stream, so they repeat on a fresh switch and differ if you start it without --fresh.

1. Start the switch and a receiver. In a first terminal, start the switch with a callback address. --fresh deletes the switch’s earlier state.

cd labs/finance
python3 generate.py          # skip if data/finance.sqlite exists
python3 mock_switch.py --fresh --callback-url http://127.0.0.1:9000/switch

In a second terminal, start a receiver. It checks the HMAC-SHA256 signature of every callback, as your own service would, and answers 401 to a bad one.

cd labs/finance
python3 - <<'PY'
import hashlib, hmac, json
from http.server import BaseHTTPRequestHandler, HTTPServer

KEY = b"sw_test_owoleaf_mock"

class Receiver(BaseHTTPRequestHandler):
    def log_message(self, *args):
        pass

    def do_POST(self):
        raw = self.rfile.read(int(self.headers.get("Content-Length") or 0))
        want = hmac.new(KEY, raw, hashlib.sha256).hexdigest()
        ok = hmac.compare_digest(want, self.headers.get("X-Switch-Signature", ""))
        body = json.loads(raw)
        print(f"{body['type']:<16} {body['mandate_id']}  code={body.get('response_code', '-'):<2}  "
              f"ref={body.get('reference', '-')}  signature={'ok' if ok else 'BAD'}", flush=True)
        self.send_response(200 if ok else 401)   # a bad signature is never acknowledged
        self.end_headers()

HTTPServer(("127.0.0.1", 9000), Receiver).serve_forever()
PY
(the second terminal prints nothing until a callback arrives; step 2 sends eight)

The receiver keeps running. The switch’s first line is mock_switch on http://127.0.0.1:8102 institution P01 key sw_test_owoleaf_mock callbacks -> http://127.0.0.1:9000/switch.

2. Walk one mandate through its life. In a third terminal, create a ₦50,000 monthly mandate, try to debit it before it is authorised, authorise it, then send every kind of debit the switch can refuse. The script starts by resetting the switch, so you can run it again.

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

BASE, KEY = "http://127.0.0.1:8102", "sw_test_owoleaf_mock"

def call(method, path, body=None, force=None):
    headers = {"Authorization": f"Bearer {KEY}", "Content-Type": "application/json"}
    if force:
        headers["X-Mock-Force"] = force
    data = json.dumps(body).encode() if method == "POST" else None
    req = urllib.request.Request(BASE + path, data=data, headers=headers, 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", {})                       # start from an empty switch
today = dt.date.today()
mandate = call("POST", "/mandates", {
    "reference": "TALLOW-MND-0001", "payer_bank": "B03", "payer_account": "2100000011",
    "max_amount_kobo": 5_000_000, "frequency": "monthly",
    "start_date": today.isoformat(), "end_date": (today + dt.timedelta(days=365)).isoformat(),
    "customer_ref": "C0000042"})
mid = mandate["mandate_id"]
print(f"create       -> code {mandate['response_code']}, status {mandate['status']}, payer {mandate['payer_name']}, cap {mandate['max_amount_kobo']}")

def debit(label, ref, amount, force=None):
    d = call("POST", "/debits", {"mandate_id": mid, "reference": ref, "amount_kobo": amount}, force)
    print(f"{label:<12} -> code {d['response_code']} ({d['response_message']}), status {d.get('status', '-')}")

debit("before auth", "TALLOW-DD-0001", 1_850_000)
print(f"authorise    -> status {call('POST', f'/admin/mandates/{mid}/authorise', {})['status']}")
debit("within cap", "TALLOW-DD-0002", 1_850_000)
debit("over cap", "TALLOW-DD-0003", 6_000_000)
debit("empty payer", "TALLOW-DD-0004", 1_850_000, force="nsf")
debit("bank down", "TALLOW-DD-0005", 1_850_000, force="bank_down")
debit("reused ref", "TALLOW-DD-0002", 1_850_000)
print(f"revoke       -> status {call('POST', f'/admin/mandates/{mid}/revoke', {})['status']}")
debit("after revoke", "TALLOW-DD-0006", 1_850_000)

print("GET /debits")
for d in call("GET", f"/debits?mandate_id={mid}")["debits"]:
    print(f"  {d['reference']}  {d['amount_kobo']:>9}  {d['response_code']}  {d['status']}")
s = call("GET", "/settlement")
print(f"settlement   -> inward {s['inward_kobo']}, outward {s['outward_kobo']}, net {s['net_kobo']}")

print("payer account that does not exist, and a mandate reference used twice")
bad = call("POST", "/mandates", {"reference": "TALLOW-MND-0002", "payer_bank": "B03", "payer_account": "2100000010",
                                 "max_amount_kobo": 5_000_000, "frequency": "monthly"})
print(f"  account ending 0 -> code {bad['response_code']} ({bad['response_message']})")
again = call("POST", "/mandates", {"reference": "TALLOW-MND-0001", "payer_bank": "B03", "payer_account": "2100000011",
                                   "max_amount_kobo": 5_000_000, "frequency": "monthly"})
print(f"  same reference   -> code {again['response_code']} ({again['response_message']}), status {again['status']}")
PY
create       -> code 00, status pending_authorisation, payer HOLDER B03-0011, cap 5000000
before auth  -> code 63 (Mandate not active), status failed
authorise    -> status active
within cap   -> code 00 (Approved or completed successfully), status successful
over cap     -> code 61 (Transfer limit exceeded), status failed
empty payer  -> code 51 (Insufficient funds), status failed
bank down    -> code 91 (Beneficiary bank not available), status failed
reused ref   -> code 26 (Duplicate record), status successful
revoke       -> status revoked
after revoke -> code 63 (Mandate not active), status failed
GET /debits
  TALLOW-DD-0001    1850000  63  failed
  TALLOW-DD-0002    1850000  00  successful
  TALLOW-DD-0003    6000000  61  failed
  TALLOW-DD-0004    1850000  51  failed
  TALLOW-DD-0005    1850000  91  failed
  TALLOW-DD-0006    1850000  63  failed
settlement   -> inward 1850000, outward 0, net 1850000
payer account that does not exist, and a mandate reference used twice
  account ending 0 -> code 07 (Invalid account)
  same reference   -> code 26 (Duplicate record), status revoked

A debit before authorisation answers 63; once authorised, ₦18,500 (1,850,000 kobo) is approved with 00. ₦60,000 is over the ₦50,000 cap (61). X-Mock-Force: nsf stands for a payer whose account is empty (51), and bank_down for the payer’s bank being unavailable (91). Reusing TALLOW-DD-0002 answers 26 and carries the first attempt’s status, successful, which is the trap described above. After the revoke, 63 again. GET /debits lists six attempts, not seven: the 26 is not an attempt, so it is not recorded. Only the one approved debit counts in /settlement: 1,850,000 kobo. An account ending in 0 does not exist at the pseudo banks (07), and reusing a mandate reference returns the existing mandate with its status.

In the receiver’s terminal, the callbacks arrive in order:

debit.failed     MD7294919105  code=63  ref=TALLOW-DD-0001  signature=ok
mandate.active   MD7294919105  code=-   ref=-  signature=ok
debit.success    MD7294919105  code=00  ref=TALLOW-DD-0002  signature=ok
debit.failed     MD7294919105  code=61  ref=TALLOW-DD-0003  signature=ok
debit.failed     MD7294919105  code=51  ref=TALLOW-DD-0004  signature=ok
debit.failed     MD7294919105  code=91  ref=TALLOW-DD-0005  signature=ok
mandate.revoked  MD7294919105  code=-   ref=-  signature=ok
debit.failed     MD7294919105  code=63  ref=TALLOW-DD-0006  signature=ok

3. Find what the switch does not check. Each case makes its own mandate and authorises it, then debits. Two cases are about your code, and four are about the dates and states in the diagram.

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

BASE, KEY = "http://127.0.0.1:8102", "sw_test_owoleaf_mock"

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

today = dt.date.today()
day = lambda n: (today + dt.timedelta(days=n)).isoformat()
n = 0

def new_mandate(freq, start, end, account):
    global n
    n += 1
    m = call("POST", "/mandates", {"reference": f"TALLOW-X-{n:04d}", "payer_bank": "B05", "payer_account": account,
                                   "max_amount_kobo": 5_000_000, "frequency": freq, "start_date": start, "end_date": end,
                                   "customer_ref": "C0000042"})
    call("POST", f"/admin/mandates/{m['mandate_id']}/authorise", {})
    return m["mandate_id"]

def debit(mid, ref, amount=1_850_000):
    return call("POST", "/debits", {"mandate_id": mid, "reference": ref, "amount_kobo": amount})["response_code"]

m = new_mandate("monthly", day(0), day(365), "2200000021")
print(f"monthly mandate, two debits the same day, two references: {debit(m, 'TALLOW-Y-0001')} then {debit(m, 'TALLOW-Y-0002')}")

m = new_mandate("once", day(0), day(365), "2200000031")
print(f"once mandate, two debits: {debit(m, 'TALLOW-Y-0003')} then {debit(m, 'TALLOW-Y-0004')}")

m = new_mandate("monthly", day(7), day(365), "2200000041")
print(f"mandate that starts in a week, debit today: {debit(m, 'TALLOW-Y-0005')}")

m = new_mandate("monthly", day(-30), day(-1), "2200000051")
print(f"mandate that ended yesterday: status {call('GET', f'/mandates/{m}')['status']}, debit: {debit(m, 'TALLOW-Y-0006')}")

m = new_mandate("monthly", day(0), day(365), "2200000061")
c = call("POST", f"/mandates/{m}/cancel", {})
print(f"biller cancels an active mandate: status {c['status']}, debit: {debit(m, 'TALLOW-Y-0007')}")

pending = call("POST", "/mandates", {"reference": "TALLOW-X-0099", "payer_bank": "B05", "payer_account": "2200000071",
                                      "max_amount_kobo": 5_000_000, "frequency": "monthly"})
r = call("POST", f"/admin/mandates/{pending['mandate_id']}/reject", {})
print(f"payer's bank rejects a pending mandate: status {r['status']}, debit: {debit(pending['mandate_id'], 'TALLOW-Y-0008')}")
PY
monthly mandate, two debits the same day, two references: 00 then 00
once mandate, two debits: 00 then 63
mandate that starts in a week, debit today: 63
mandate that ended yesterday: status expired, debit: 63
biller cancels an active mandate: status cancelled, debit: 63
payer's bank rejects a pending mandate: status rejected, debit: 63

The monthly mandate is debited twice on one day, with two references, and both are approved: the switch does not know what month it is. A once mandate refuses the second debit. A mandate that starts in a week refuses today’s debit, an expired one reads expired and refuses it, and a cancelled or rejected one refuses it too. All five refusals are the one code 63: the code says the mandate cannot be used, and the state says why.

4. Write the collector. Five of Tallowmere’s monthly refills are due. Order A’s payer has funds. B’s has none on days 0 and 1 and funds on day 2. C never has funds. D is ₦60,000 on a mandate capped at ₦50,000. E’s mandate was revoked. The collector retries only a 51, at most twice, on later days, with a new reference for each try. The X-Mock-Force: nsf header stands in for the payer’s real balance, because the mock has no accounts behind its debits.

python3 - <<'PY'
import json, urllib.error, urllib.request

BASE, KEY = "http://127.0.0.1:8102", "sw_test_owoleaf_mock"
MAX_RETRIES = 2                      # our policy for a 51; the mock does not enforce it
CAP = 5_000_000                      # every mandate allows up to N50,000 a debit

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

# Tallowmere's monthly refills: (order, amount in kobo, first day the payer's account can cover it)
orders = [("A", 1_850_000, 0), ("B", 2_230_000, 2), ("C", 1_200_000, None), ("D", 6_000_000, 0), ("E", 950_000, 0)]
mandate, attempts, result = {}, {}, {}
for i, (order, amount, funded) in enumerate(orders):
    m = call("POST", "/mandates", {"reference": f"TALLOW-REFILL-{order}", "payer_bank": "B07",
                                   "payer_account": f"230000008{i + 1}", "max_amount_kobo": CAP, "frequency": "monthly"})
    mandate[order] = m["mandate_id"]
    call("POST", f"/admin/mandates/{m['mandate_id']}/authorise", {})
call("POST", f"/admin/mandates/{mandate['E']}/revoke", {})        # patient E closed the mandate at their bank

def decide(code, tries):
    if code == "00":
        return "paid"
    if code == "51" and tries <= MAX_RETRIES:
        return "retry"                                              # only a 51 is worth another day
    return "stop"                                                   # 61, 63, 91 and a 51 out of retries go to a person

before = call("GET", "/settlement")["inward_kobo"]
open_orders = {o: a for o, a, _ in orders}
funded_from = {o: f for o, _, f in orders}
for day in range(MAX_RETRIES + 1):
    for order in list(open_orders):
        tries = len(attempts.setdefault(order, [])) + 1
        empty = funded_from[order] is None or day < funded_from[order]   # stands in for the payer's real balance
        d = call("POST", "/debits", {"mandate_id": mandate[order], "reference": f"TALLOW-REFILL-{order}-try{tries}",
                                     "amount_kobo": open_orders[order]}, "nsf" if empty else None)
        attempts[order].append(d["response_code"])
        verdict = decide(d["response_code"], tries)
        print(f"day {day}  order {order}  {open_orders[order]:>8}  code {d['response_code']}  {verdict}")
        if verdict != "retry":
            result[order] = verdict
            del open_orders[order]

print()
collected = 0
for order, amount, _ in orders:
    paid = result[order] == "paid"
    collected += amount if paid else 0
    print(f"order {order}: {' '.join(attempts[order]):<9} -> {'collected' if paid else 'to a person'}")
after = call("GET", "/settlement")["inward_kobo"]
sent = sum(len(a) for a in attempts.values())
naive = sum(len(attempts[o]) if result[o] == "paid" else MAX_RETRIES + 1 for o, _, _ in orders)
print(f"collected {collected} kobo; settlement inward rose by {after - before}")
print(f"requests sent {sent}; a loop that retried every refusal up to {MAX_RETRIES} times would have sent {naive}")
again = call("POST", "/debits", {"mandate_id": mandate["C"], "reference": "TALLOW-REFILL-C-try1", "amount_kobo": 1_200_000})
print(f"order C, first reference sent again: code {again['response_code']}, status {again['status']}")
PY
day 0  order A   1850000  code 00  paid
day 0  order B   2230000  code 51  retry
day 0  order C   1200000  code 51  retry
day 0  order D   6000000  code 61  stop
day 0  order E    950000  code 63  stop
day 1  order B   2230000  code 51  retry
day 1  order C   1200000  code 51  retry
day 2  order B   2230000  code 00  paid
day 2  order C   1200000  code 51  stop

order A: 00        -> collected
order B: 51 51 00  -> collected
order C: 51 51 51  -> to a person
order D: 61        -> to a person
order E: 63        -> to a person
collected 4080000 kobo; settlement inward rose by 4080000
requests sent 9; a loop that retried every refusal up to 2 times would have sent 13
order C, first reference sent again: code 26, status failed

Nine requests, not thirteen: D and E were each sent once, because 61 and 63 are not retried, and C was sent three times, the first try plus two retries. Order B was recovered on day 2. Orders C, D and E, ₦12,000, ₦60,000 and ₦9,500 (the amounts 1,200,000, 6,000,000 and 950,000 kobo), went to a person with their codes. Of ₦122,300 due, ₦40,800 was collected, which is 33.4%. The 4,080,000 kobo the collector counted equals the rise in the switch’s inward_kobo, so the collector and the switch agree. Sending C’s first reference again answered 26 with status failed: the old reference carries the old outcome and tries nothing.

Let the switch refuse debits at random and see how much a retry recovers. This script sets debit_nsf_rate to 0.3, then runs 100 orders of ₦1,000 through the same three-attempt rule, and sets the rate back to zero.

python3 - <<'PY'
import json, urllib.error, urllib.request

BASE, KEY = "http://127.0.0.1:8102", "sw_test_owoleaf_mock"

def call(method, path, body=None):
    headers = {"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=headers, 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/faults", {"debit_nsf_rate": 0.3})            # 30% of debits answer 51, drawn afresh each time
m = call("POST", "/mandates", {"reference": "TALLOW-BREAK-MND", "payer_bank": "B09", "payer_account": "2400000019",
                               "max_amount_kobo": 5_000_000, "frequency": "variable"})["mandate_id"]
call("POST", f"/admin/mandates/{m}/authorise", {})
first = recovered = given_up = 0
for i in range(100):
    for attempt in range(3):                                      # the first try and two retries
        code = call("POST", "/debits", {"mandate_id": m, "reference": f"TALLOW-BRK-{i:03d}-{attempt}",
                                        "amount_kobo": 100_000})["response_code"]
        if code == "00":
            first += attempt == 0
            recovered += attempt > 0
            break
    else:
        given_up += 1
print(f"paid on the first try {first}, recovered by a retry {recovered}, given up {given_up}")
call("POST", "/admin/faults", {"debit_nsf_rate": 0.0})
PY

Expected, if you ran steps 1 to 4 in this order on a freshly started switch: paid on the first try 69, recovered by a retry 28, given up 3. The switch’s random draws are seeded but shared, so a different history gives a nearby result (66, 30 and 4 on a switch that had run nothing else). Independent draws predict about 70, 27 and 3, which the run matches. Now ask whether a real payer behaves this way. A payer who was short on the first of the month is more likely than 30% to be short on the second, because the cause persists, so real retries recover less than the mock’s 28 in 100. Then look at what a retry costs: each recovered order took at least one refused debit first. Decide what share of retries must succeed to be worth sending, and add a counter to the collector so that it reports the recovery rate for each retry day.

ARTEFACT Write the failed-debit procedure and customer notice ~45 MIN
YOU PRODUCEFailed-debit handling procedure with customer notice

Template

# Failed-debit procedure: <business>, version <n>
Author <role> · Approvers <head of operations>, <compliance lead> · Date <date> · Review by <date>
Decision needed: <what the approvers decide, and by when>

## Scope
Covers: <which mandates and which invoices>. Does not cover: <disputes, returned debits, refunds>.

## Mandate states
| State | Accepts debits? | Who moves it there | What we do |
|---|---|---|---|

## What each failure means
| Code | Meaning | Whose problem | Action | Owner |
|---|---|---|---|---|

## Retry rule
Retry only: <codes>. Attempts: <number> in all, one per <interval>. Each attempt has a new reference: <format>.
Assumption to confirm: <the limit, and who checks it against the current rules, by when>.
After the last attempt: <queue, owner, what the person sees>.

## Pause and cancel
Pause (our hold, mandate unchanged) when: <conditions>. Cancel when: <conditions>. Restart needs: <who>.

## Customer notice
<wording for each outcome: amount, reason, what happens next, who to contact>

## How this could be wrong
<one way, and the number or event that would show it>
WORKED EXAMPLE

Ufuoma, who runs collections at Tallowmere, writes this; the head of operations and the compliance lead sign it.

Failed-debit procedure: Tallowmere, version 1. Date 20 November 2026 · Review by 20 February 2027. Decision needed: approve the retry rule and notice before the first debit run.

Mandate states. Only an active mandate, inside its dates, accepts debits. Pending, rejected, revoked, cancelled, expired and not-yet-started all answer 63. Tallowmere cancels when a patient stops refills. The patient’s bank can revoke, and we may learn only when a debit fails.

Failures. From the lab’s five refills, ₦122,300 due. A 51 is the payer’s balance today: order B failed twice and paid on day 2. A 61 is the mandate’s cap: order D, ₦60,000 against ₦50,000, is never retried and Ufuoma asks the patient for a larger mandate. A 63 means read the mandate: order E was revoked, so collection stops at the first 63. A 91 (payer’s bank down) goes to a person.

Retry rule. Retry only a 51: three attempts, one a day, each with a new reference such as TALLOW-REFILL-C-try2. Three is the lab’s teaching policy, so it is an assumption: the compliance lead confirms the limit against the current CBN text before go-live. Order C went 51 51 51 to Ufuoma’s queue. The lab collected ₦40,800 of ₦122,300 (33.4%) in 9 requests, not 13.

Pause and cancel. After a 61 or 63 we pause: a hold in our records, because the switch has no paused state and the mandate stays as it is. Only Ufuoma restarts it. We cancel when the patient stops refills.

Notice (order C). “Your ₦12,000 refill payment could not be collected on three attempts because the account balance was too low each time. Please call Ufuoma’s team on [phone number] or pay by transfer.”

How this could be wrong. With 30% of debits refused at random, the lab recovers 28 of 100 by retry; real payers short on the first day are likelier to be short again. If recovery falls well below that, cut the attempts.

Now you

You run billing for a 12-person clinic in Enugu. Patients on a physiotherapy plan pay ₦45,000 a month by direct debit, each mandate capped at ₦50,000. This month 40 plans are due, and three things happened: a few debits came back 51, the clinic raised the fee to ₦55,000 from next month, and some patients stopped coming without telling you. Your compliance adviser has not yet confirmed a retry limit, so you must state one as an assumption.

Write the procedure and the notice for a 51 and for the fee rise. Use the lab’s step 3 for the states and its step 4 for the codes and the attempt pattern, and say which of its numbers you reuse. The practice manager signs it, and the clinic’s director decides whether to start collecting at ₦55,000 or first ask patients for larger mandates.

Self-check

DECIDE

Tallowmere's refill charges to saved cards fail for 27 of 300 patients each month, and Ufuoma phones each one. Utibe can build a direct debit collector within a month. About a third of the patients have said they would rather pay by transfer than by card, and the rest have not been asked. Which plan do you choose?

READING
  1. DOC
    Regulation for Direct Debit Scheme in Nigeria, 2018 (revised) Central Bank of Nigeria, 2018

    The CBN's own text for the scheme, in the latest version search results show. Read the roles of the biller and the payer's bank, the mandate and cancellation provisions, and what it says on unpaid debits. This chapter's claims about it rest on search summaries, so check each one here and check that it is still in force.

  2. DOC
    Guidelines for the Direct Debit Scheme and Bill Payments in Nigeria (2017) Central Bank of Nigeria, 2017

    The earlier text, which search summaries tie to the wording on arrears and re-presentment; the version in results may be the exposure draft. Read it beside the 2018 Regulation to see what changed, especially on retries and unpaid items. It is not read in this build, so use it to compare, not to quote.

  3. DOC
    Frequently asked questions on the operation of the direct debit scheme Central Bank of Nigeria, 2013

    A plain question-and-answer page from the regulator. Read it for the scheme in everyday words, then check the dated rules above for anything that has changed since 2013. It was not read in this build.

  4. DOC
    Operational Guidelines on Global Standing Instruction (GSI): Individuals Central Bank of Nigeria, 2020

    The lender's other recovery instrument, which reaches a borrower's accounts at other banks. Read the conditions and the last-resort wording to see how it differs from a mandate for one account. Check whether the January 2022 circular changed it.

  5. DOC
    NIBSS Direct Debit (NDD) NIBSS, 2026

    The scheme operator's page for the shared mandate library. Read it for how the scheme describes itself. This build saw it only through search summaries, so confirm the page and its current wording.

  6. DOC
    Direct Debit (Paystack documentation) Paystack, 2026

    A vendor's description of how its API presents mandates and debits to a developer. Read it for the shape of a real integration and compare it with the lab's. It is a vendor's claim about its own product, not the scheme's rules.

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

    A comparison from another regulator: a per-transaction threshold and an additional authentication step around recurring pulls. Read it for what a scheme can require. It is India's rule and not Nigeria's, and news reports describe a later consolidated framework.

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: Project: a wallet with funding, transfers, refunds and daily reconciliation →