Transfers and virtual accounts
A transfer is a push you cannot take back, and a virtual account is a number that tells you who paid. Both end in a message you must treat as a claim, not as money
A distributor pays ₦4,750,000 into its virtual account. The switch sends the inward-credit callback to Crustwell's receiver twice, a second apart, with the same session id and the same valid signature. The receiver verifies the signature and then credits the distributor. What is the distributor's balance afterwards?
A transfer between banks has two ends, and the two ends are different problems. When you send money, you push it and wait for an answer that may not come. When you receive money, someone else pushes it and you hear about it by a message you did not ask for. The first problem is about not paying twice. The second is about not crediting twice, and about knowing whom you are crediting.
This chapter runs on Owoleaf’s lab, a fictional Lagos wallet company, and its mock instant-payment switch. Crustwell is the example company. Every code, limit and fee in the lab is invented and labelled so. The chapter teaches the shape of the work, and the lab checks each piece in numbers.
Push, and what that costs you
A card payment is a pull of sorts: the merchant asks the card’s issuer for the money, and a dispute process exists after the fact (see a card payment end to end). A bank transfer on the instant rail you met in Nigeria’s rails is a push. The sender’s side decides, sends, and the beneficiary’s bank credits the account. The beneficiary cannot say no. If the account number was wrong, the only remedy is to ask the stranger’s bank to return the money, and that depends on goodwill and on rules you will meet in a later chapter on payment states and refunds.
Everything in this chapter follows from that. A push has to be checked before it leaves, because afterwards it is nearly irrevocable. And a push that you receive has to be accepted exactly once, because the sender’s bank has already moved the money and will not do it again for you. (The opposite design, where the receiver pulls under an authority the payer signed, is a direct debit. It has its own chapter in this module.)
Account numbers and name enquiry
An instant transfer is addressed by a bank and an account number. The bank code says which institution to ask. The account number is ten digits.
The CBN’s Revised Standards on the Nigeria Uniform Bank Account Number (NUBAN) for banks and other financial institutions, from 2020, keep the ten-digit customer account number and set out an underlying sixteen-digit identifier that includes the institution’s code, with a check digit computed by a modulus-10 method; search summaries and a mirror of the circular give an effective date of April 2020 and a full-compliance date of March 2021as of 2026-11. That description rests on search summaries, because the CBN’s site could not be opened in this build. Read the document for the exact layout and the algorithm before you write a validator. The idea is what matters here. A check digit is one digit worked out from the others, so that most single-digit typing mistakes and many swaps produce a number that fails the check. A check digit catches typos. It cannot say whose account a valid number is.
The lab’s numbers do not pass such a check, because the generator makes them up: wallets are 9 followed by the customer id in nine digits, and virtual accounts are 8 followed by nine random digits. Do not copy their format into real code.
Name enquiry is the control for the rest. The CBN’s Regulation on Instant (Inter-Bank) Electronic Funds Transfer Services in Nigeria requires the sending entity to offer name enquiry to its customers and the receiving entity to give name enquiry support to the service provider, in order to reduce wrong credits; search summaries add that “instant” means delivery within one minute (60 seconds)as of 2026-11. Summaries also mention a sanction on banks that fail to reverse failed transfers, but the searches did not confirm the reversal deadline, the amount or any settlement timing, so this chapter states none of them. The effective date is given as 2 October 2018 in one source and garbled in another. These are search summaries of a PDF this build could not read.
The regulation makes sure the answer exists. It does not make anyone use it well. Your code gets back a name, and then someone has to compare it with the name they meant to pay. If a person is looking at a screen, that is a person’s job. If a program is paying a supplier from a list, the program must do it, and it has to cope with how Nigerian names appear in bank systems: surname first or last, a middle name present or missing, initials, upper case, and spellings with or without the tone marks of Yoruba or the dotted letters of Igbo. An exact string comparison refuses the right payee. No comparison at all pays the wrong one. The lab’s step 4 uses a middle path: every word of the expected name must appear in the returned name, in any order, after accents are stripped. It is deliberately strict in one direction. A returned name with an extra word passes; a missing word fails, and a human looks at the exception.
Sending: four calls and three answers
An outward transfer on the lab’s switch is four calls.
- Name enquiry,
POST /name-enquiry, with the bank and account number. It answers a response code, the account name and aname_enquiry_refthat ties the money to the name that was shown. - Check the name. Your code, or your user, decides whether this is the intended payee.
- Transfer,
POST /transfers, with apayment_referenceyou choose, thename_enquiry_ref, the sender’s account, the amount in kobo and a narration. It answers a response code and asession_id, the switch’s own identifier for the payment. - Requery,
POST /tsq, bysession_idor by yourpayment_reference: what does the switch say now?
The switch’s answers fall into three groups, and your code must handle all three.
| Answer | Examples (the lab’s codes, illustrative) | What you know | What you do |
|---|---|---|---|
| Yes | 00 approved |
The beneficiary’s bank accepted it | Post the money out of the wallet; you may still see a late return |
| No | 07 invalid account, 13 invalid amount, 61 over the transfer cap, 91 beneficiary bank not available |
Nothing moved | Release any hold; tell the customer; a retry may be safe, with a new decision |
| Not known | 09 in progress, a timeout, no answer |
You do not know | Requery. Never send again until the requery has answered |
The codes are modelled on NIP-style codes and are the mock’s own. The real list comes from NIBSS, and the chapter does not reproduce it. What carries over is the grouping. Every real integration sorts its responses into yes, no and not known, and most of its bugs live in the third group. The idempotency chapter in this module takes the timeout case apart: the payment that succeeded while your client gave up. Here the rule is short. A payment reference is how you ask about a payment you already made, so keep it, and requery before you retry.
What do you post? The lab’s generator records only the final outcome of a payout. A successful payout of ₦125,000 with a ₦50 fee debits the wallet 12,505,000 kobo, credits the settlement account 12,500,000 and credits fee revenue 5,000. A wallet that must stop the customer spending the same money twice also needs a stage before the outcome: move the amount and fee into a holding account when the request is accepted, release it to the settlement account and fee revenue on 00, and return it to the wallet on a no. The lab’s data does not contain this design, so there is nothing to compare it against; the payment-states chapter builds it. If you post only at the end, a customer can start two payouts that each look affordable.
Receiving: why a virtual account
Now the other end. Crustwell wants to know, for every credit that arrives, which distributor paid it. The bank statement gives a narration the payer typed, an amount and a sending bank. The narration is free text. In the generator’s own bank statement the wallet company’s inward credits read NIP INWARD C000…, which is tidy only because the generator wrote it. Real narrations are not.
A virtual account fixes this by moving the identity from the text to the number. You ask for an account number for each customer. The number is real as far as the payer’s bank is concerned: it passes name enquiry, and the payer’s bank shows the name behind it. But it is not a separate account with a balance. It maps to one customer in your ledger, and behind it sits an ordinary account at a bank that holds the pooled money. Whoever pays that number is, by construction, paying that customer.
Two kinds exist in practice. A static account is permanent and belongs to one customer: it suits a distributor who pays many times. A dynamic account is created for one expected payment, usually with an amount and an expiry: it suits a checkout where the shop wants to match one invoice. The lab’s switch makes static accounts only. Providers sell both, and their designs differ in what they require and what they limit. As two labelled vendor claims, Paystack’s documentation says its dedicated virtual accounts are for registered Nigerian businesses that have completed its go-live process, and, in a search summary of its support pages, that a business has a limit of 1,000 virtual accounts to assign to customersas of 2026-11, and Flutterwave’s documentation describes dynamic accounts as single-use, with a default life of one hour in a search summary, and static accounts as permanent and reusable, with creation of a static account asking for a customer’s BVN or NIN (older pages mention only the BVN)as of 2026-11. These are vendors describing their own products. Check the current pages before you design around any of it, and note that the chapter recommends neither.
What a virtual account does not tell you matters as much. It identifies the payer. It does not identify the invoice. A distributor can pay ₦4,750,000 against invoice 4471 and ₦4,750,000 against invoice 4480 in the same hour, or pay half, or pay twice by mistake. Allocating a credit to invoices is accounts receivable work. The ledger’s job is to record, once, that this customer paid this much at this time, and to keep the allocation separate. Money that arrives with no match is exactly what the reconciliation chapter calls an unapplied credit.
There is also the question of whose account sits behind the number. In the lab, Owoleaf is institution P01 on the switch, which is a simplification. The CBN’s 2019 Circular and Regulation for the Operation of Indirect Participants in the Payment System, in force from November 2019 according to search summaries, says that indirect participants settle their payment obligations through a direct participating bank, and summaries add that this is only one direct participating bank per payment scheme at a timeas of 2026-11. That description rests on news coverage and excerpts, because the CBN’s PDF could not be read here. In practice a company that is not itself a direct participant reaches the rail through a bank, and the number it hands to a payer is often in that bank’s range. Who holds the pooled money and who is liable if that holder fails are questions for the wallet and licence chapters, and for your contract. They are not hidden by the fact that the number looks like yours.
The callback: verify, confirm, credit once
When money lands on the number, the switch tells you. In the lab it POSTs an inward.credit callback to a URL you gave it at start-up. The body carries the session_id, the account number, the customer, the amount in kobo and the sending bank. A header, X-Switch-Signature, carries a hex HMAC-SHA256 of the raw body, keyed with a secret you and the switch share. (HMAC and why the body must be the raw bytes are in the hashing and signatures lesson, and the same pattern for a card provider is in this module’s chapter on integrating a provider.)
A receiver for this does four things, in this order.
Verify the signature, against the raw bytes, in constant time. Compute the HMAC of exactly what arrived, not of a parsed and re-serialised object, and compare with hmac.compare_digest, not == (the reason is in the timing attack lesson). A bad signature gets a 401 and is ignored.
Confirm the claim. A signed callback says the switch sent this. The same discipline you used for a card provider applies: before you credit, ask the switch for its record of that session, with the requery, and check that it says successful, inward, for the same amount and the same account. If the requery itself fails, answer with a non-2xx status so the switch tries again later. Confirmation is cheap compared with the cost of one wrong credit.
Credit once per session id. The session_id is the switch’s own identifier for the payment. Make it the primary key of your credits table and write the credit with one statement that fails or does nothing if the key exists. Do not do this as a read followed by a write. A read followed by a write is check-then-act: two copies of the same callback, handled on two threads, can both read “not seen” before either writes. A uniqueness constraint makes the database enforce it, whatever your code does. This is the key idea of idempotency applied to the receiving side: the sender’s retry is a fact of life, and the receiver turns “at least once” into “exactly once” by remembering what it has done.
Answer 2xx only after the credit is durable. A 2xx tells the switch to stop. Send it after the row is committed, and send it for a duplicate too: “already credited” is a success from the switch’s point of view. A non-2xx reply makes the switch retry. In the lab it makes five attempts in all, waiting twice as long before each retry, from a base of two seconds (2, 4, 8 and 16 seconds), so the last attempt comes about 30 seconds after the first. After that the callback is gone.
The key must be the session id, and nothing else. The tempting alternative is a natural key: “customer and amount, because the same customer will not pay the same amount twice.” Distributors do. Two real payments of ₦800,000 for two invoices are then collapsed into one credit, and the receiver reports success both times. The lab’s last step makes you do it. A duplicate key stops duplicates only when it is the identifier the sender assigns to the event, not a guess about its content.
When the callback never comes
Callbacks are best effort. The receiver was being deployed, the network dropped, or the switch exhausted its retries. The payer’s bank has moved the money all the same, and the distributor will say, truthfully, that they paid.
So the callback cannot be the record. The record is the switch’s transfer report, which lists every transfer for a day, and its daily position, which sums them. Run a catch-up job: read the day’s successful inward transfers from the report and credit any session id that has no credit yet. It must use the same once-only write as the callback handler, so that a late callback and the catch-up job can both run without double-crediting. Then compare totals. The credits you hold for the day must equal the switch’s inward figure. When they do not, the difference is a list of session ids, and each one is either a callback you missed or a payment you chose not to credit. That comparison is the first small piece of the reconciliation chapter’s work.
Where it goes wrong
- Crediting on the callback alone. A forged message with a valid-looking body is rejected by the signature, but a genuine duplicate, replay or out-of-order message is not. Confirm with the switch and key on the session id.
- Treating “no answer” as “no”. The payment may have succeeded. Requery by reference before sending again.
- Trusting the name on the screen. Name enquiry shows a name, and a person has to read it. A program that does not compare names pays whoever owns the number.
- Natural keys for deduplication. Customer and amount, or amount and day, merge real payments.
- Floats and naira. Callbacks carry integer kobo. A callback amount of 4750000 is 4,750,000 kobo, which is ₦47,500, not ₦4,750,000. Keep kobo in code and write naira only for people (see money in software).
- One number for everything. Reusing a virtual account across customers destroys the attribution it exists to provide. Issue one per payer and keep the mapping.
- Forgetting the money has not reached you. A credit callback says the switch accepted a payment; the net settlement between banks still happens later. The wallet is credited on a promise, which is the float problem you met in the card chapter, and the settlement chapter in this module covers it.
You work in labs/finance. The first terminal runs the switch and the second runs your receiver. Every other step is a Python script run from the same folder, so the lab needs no sqlite3 program. Session ids, account numbers and references come from the switch’s random stream: yours will differ from the ones quoted, in digits only.
1. Start the switch, write the client and the receiver, and start the receiver. In the first terminal:
cd labs/finance
python3 generate.py # skip if data/finance.sqlite exists
python3 mock_switch.py --callback-url http://127.0.0.1:9000/switchSave this as sw.py. It is a small client the later steps share.
"""A small client for the mock switch, shared by the lab steps."""
import json
import urllib.error
import urllib.request
BASE = "http://127.0.0.1:8102"
KEY = {"Authorization": "Bearer sw_test_owoleaf_mock", "Content-Type": "application/json"}
def call(method, path, body=None, headers=None, timeout=10):
data = json.dumps(body).encode() if body is not None else None
req = urllib.request.Request(BASE + path, data=data, method=method, headers=dict(KEY, **(headers or {})))
try:
with urllib.request.urlopen(req, timeout=timeout) as r:
return r.status, json.load(r)
except urllib.error.HTTPError as e:
return e.code, json.load(e)Save this as switch_receiver.py. Read it before you run it: the table is the design, and credit is the door.
"""Receive the switch's inward-credit callbacks and credit each session_id once.
Run: python3 switch_receiver.py (listens on http://127.0.0.1:9000/switch)
"""
import hashlib
import hmac
import json
import sqlite3
import urllib.request
from http.server import BaseHTTPRequestHandler, HTTPServer
SECRET = b"sw_test_owoleaf_mock" # the callback HMAC key and the API key are the same mock string
SWITCH = "http://127.0.0.1:8102"
DB = "data/receiver.sqlite"
db = sqlite3.connect(DB, check_same_thread=False)
db.execute("""CREATE TABLE IF NOT EXISTS credits (
session_id TEXT PRIMARY KEY, -- the switch's id for the payment: one credit per value
customer_ref TEXT NOT NULL,
account TEXT NOT NULL,
amount_kobo INTEGER NOT NULL CHECK (amount_kobo > 0))""")
db.commit()
def requery(session_id):
"""Ask the switch what it holds for this session (the same call as a payout's status query)."""
req = urllib.request.Request(
SWITCH + "/tsq", data=json.dumps({"session_id": session_id}).encode(), method="POST",
headers={"Authorization": "Bearer " + SECRET.decode(), "Content-Type": "application/json"})
with urllib.request.urlopen(req, timeout=5) as r:
return json.load(r)
def confirmed(claim):
"""A callback is a claim. Credit only what the switch's own record agrees with."""
rec = requery(claim["session_id"])
return (rec.get("status") == "successful" and rec.get("direction") == "inward"
and rec.get("amount_kobo") == claim["amount_kobo"]
and rec.get("beneficiary_account") == claim["account_number"])
def credit(claim):
"""True if this call credited the wallet, False if the session was already credited."""
cur = db.execute("INSERT OR IGNORE INTO credits VALUES (?,?,?,?)",
(claim["session_id"], claim["customer_ref"], claim["account_number"], claim["amount_kobo"]))
db.commit()
return cur.rowcount == 1
class Hook(BaseHTTPRequestHandler):
def log_message(self, *a):
pass
def reply(self, code, text):
print(f"{code} {text}", flush=True)
self.send_response(code)
self.send_header("Content-Length", "0")
self.end_headers()
def do_POST(self):
raw = self.rfile.read(int(self.headers.get("Content-Length") or 0))
want = hmac.new(SECRET, raw, hashlib.sha256).hexdigest()
if not hmac.compare_digest(want, self.headers.get("X-Switch-Signature", "")):
return self.reply(401, "bad signature: ignored")
claim = json.loads(raw)
if claim.get("type") != "inward.credit":
return self.reply(200, f"{claim.get('type')}: not for this receiver")
try:
if not confirmed(claim):
return self.reply(200, f"session {claim['session_id'][-6:]}: switch does not confirm it; not credited")
except OSError:
return self.reply(503, "could not requery the switch: ask again later")
if credit(claim):
self.reply(200, f"credited {claim['amount_kobo']} kobo to {claim['customer_ref']} "
f"(session ...{claim['session_id'][-6:]}, attempt {self.headers.get('X-Switch-Attempt')})")
else:
self.reply(200, f"session ...{claim['session_id'][-6:]} already credited: nothing to do "
f"(attempt {self.headers.get('X-Switch-Attempt')})")
if __name__ == "__main__":
print("receiver on http://127.0.0.1:9000/switch", flush=True)
HTTPServer(("127.0.0.1", 9000), Hook).serve_forever()In the second terminal:
cd labs/finance
python3 switch_receiver.pyThe switch prints mock_switch on http://127.0.0.1:8102 institution P01 key sw_test_owoleaf_mock callbacks -> http://127.0.0.1:9000/switch, and the receiver prints receiver on http://127.0.0.1:9000/switch. The receiver opens data/receiver.sqlite and creates one table, credits, whose primary key is the switch’s session id.
2. Give three distributors a virtual account each. Crustwell’s distributors are three of the lab’s merchant customers. The script asks for a virtual account for each, runs a name enquiry on it as a payer’s bank would, and compares with the enquiry on an ordinary wallet number.
python3 - <<'PY'
import sqlite3
from sw import call
db = sqlite3.connect("data/finance.sqlite")
distributors = [r[0] for r in db.execute("SELECT ref FROM customers WHERE kind = 'merchant' ORDER BY id LIMIT 3")]
for ref in distributors:
_, va = call("POST", "/virtual-accounts", {"customer_ref": ref})
_, ne = call("POST", "/name-enquiry", {"bank_code": "P01", "account_number": va["account_number"]})
print(f"{ref}: virtual account {va['account_number']} at {va['bank_code']}, "
f"enquiry {ne['response_code']} {ne['account_name']}, kyc_tier {ne.get('kyc_tier')}")
_, ne = call("POST", "/name-enquiry", {"bank_code": "P01", "account_number": "9000000042"})
print(f"wallet 9000000042: enquiry {ne['response_code']} {ne['account_name']}, kyc_tier {ne.get('kyc_tier')}")
PYC0000002: virtual account 8585738843 at P01, enquiry 00 OWOLEAF/C0000002, kyc_tier None
C0000030: virtual account 8730699660 at P01, enquiry 00 OWOLEAF/C0000030, kyc_tier None
C0000042: virtual account 8610846881 at P01, enquiry 00 OWOLEAF/C0000042, kyc_tier None
wallet 9000000042: enquiry 00 OWOLEAF/C0000042, kyc_tier 3The switch gives a KYC tier only for a wallet number, so the three virtual accounts show kyc_tier None while the wallet 9000000042, which belongs to the same customer as the third account, shows tier 3. The numbers begin with 8, the mock’s mark for a virtual account, and the account name is the customer’s reference after OWOLEAF/: that is the name the payer’s bank would show. The mapping from number to customer lives in the switch. Your own system should keep it too.
3. Pay into a virtual account, with a duplicate callback, then forge two. The script pays ₦4,750,000 (475,000,000 kobo) into the first distributor’s number and asks the switch to send the callback twice. It then reads what the switch sent and what your receiver credited, and sends the receiver two forged messages directly. The second forgery is signed correctly with the shared secret, but names a session the switch never saw.
python3 - <<'PY'
import hashlib
import hmac
import json
import sqlite3
import time
import urllib.error
import urllib.request
from sw import call
# 1. Distributor C0000002 pays invoice 4471, ₦4,750,000, from another bank. The switch sends the callback twice.
_, out = call("POST", "/admin/inward", {"account_number": "8585738843", "amount_kobo": 475_000_000,
"sender_bank": "B03", "narration": "INV 4471 LAGOS WEST", "duplicate_callback": True})
print("inward:", out["response_code"], out["account_name"], "session", out["session_id"])
time.sleep(3)
_, cb = call("GET", "/callbacks")
print("callbacks:", [(c["session_id"][-6:], c["attempt"], c["http_status"]) for c in cb["callbacks"]])
db = sqlite3.connect("data/receiver.sqlite")
print("credits:", db.execute("SELECT customer_ref, amount_kobo, substr(session_id, -6) FROM credits").fetchall())
# 2. Two forged callbacks sent straight to the receiver.
def post(body, signature):
req = urllib.request.Request("http://127.0.0.1:9000/switch", data=body, method="POST",
headers={"X-Switch-Signature": signature})
try:
return urllib.request.urlopen(req).status
except urllib.error.HTTPError as e:
return e.code
forged = json.dumps({"type": "inward.credit", "session_id": "1" * 30, "account_number": "8585738843",
"customer_ref": "C0000002", "amount_kobo": 999_999_999}).encode()
print("wrong signature:", post(forged, "00" * 32))
signed = hmac.new(b"sw_test_owoleaf_mock", forged, hashlib.sha256).hexdigest()
print("right signature, session the switch never saw:", post(forged, signed))
print("credits after both:", db.execute("SELECT COUNT(*), SUM(amount_kobo) FROM credits").fetchone())
PYinward: 00 OWOLEAF/C0000002 session 816371564513788379217218842407
callbacks: [('842407', 1, 200), ('842407', 1, 200)]
credits: [('C0000002', 475000000, '842407')]
wrong signature: 401
right signature, session the switch never saw: 200
credits after both: (1, 475000000)Two callbacks for one session id, both answered 200, and one credit of 475,000,000 kobo, which is ₦4,750,000. The receiver’s terminal shows why: the first line says credited 475000000 kobo to C0000002 (session ...842407, attempt 1) and the second says already credited: nothing to do, followed by 401 bad signature: ignored and session 111111: switch does not confirm it; not credited. The wrong signature never reaches the credit. The correctly signed forgery passes the signature, because anyone holding the secret can sign, and is stopped by the requery: the switch holds no such session. That is why the receiver confirms as well as verifies. Your session digits will differ.
4. Pay out: name enquiry, name check, transfer, requery. Save this as payout.py. It pays from the wallet of C0000042 (9000000042) to an account at the invented bank B03, forces the outcome with X-Mock-Force, requeries by your own reference, and prints the legs you would post. It also tests its own name check on four pairs of names.
"""Pay out from a wallet: name enquiry, name check, transfer, requery, and the legs to post."""
import secrets
import re
import unicodedata
from generate import payout_fee
from sw import call
SENDER = "9000000042" # wallet of C0000042, a merchant
def tokens(name):
"""Lower-case words with accents and punctuation removed, so Ọlájídé and OLAJIDE agree."""
plain = unicodedata.normalize("NFKD", name).encode("ascii", "ignore").decode()
return {w for w in re.split(r"[^a-z]+", plain.lower()) if len(w) > 1}
def same_person(expected, returned):
"""Every word we expect must appear in the returned name, in any order. Initials are ignored."""
return tokens(expected) <= tokens(returned)
def payout(bank, account, amount_kobo, force=None, expected="HOLDER"):
_, ne = call("POST", "/name-enquiry", {"bank_code": bank, "account_number": account})
if ne["response_code"] != "00":
return f"name enquiry {ne['response_code']} ({ne['response_message']}): nothing sent"
if not same_person(expected, ne["account_name"]):
return f"name enquiry returned {ne['account_name']!r}, expected {expected!r}: nothing sent"
ref = "PAYOUT-" + secrets.token_hex(4).upper()
_, t = call("POST", "/transfers", {"payment_reference": ref, "name_enquiry_ref": ne["name_enquiry_ref"],
"sender_account": SENDER, "amount_kobo": amount_kobo, "narration": "SUPPLIER PAYMENT"},
headers={"X-Mock-Force": force} if force else None)
_, q = call("POST", "/tsq", {"payment_reference": ref})
fee = payout_fee(amount_kobo)
legs = ("debit wallet %d, credit settlement_bank %d, credit fee_revenue %d" % (amount_kobo + fee, amount_kobo, fee)
if q["status"] == "successful" else "post nothing: no money left")
return (f"{ref}: transfer {t['response_code']} {t['status']}, requery {q['response_code']} {q['status']} "
f"-> {legs}")
if __name__ == "__main__":
print("names:")
for exp, got in [("Adebayo Oluwaseun", "OLUWASEUN ADEBAYO TUNDE"), ("Ọlájídé Bello", "BELLO OLAJIDE"),
("Chinedu Okafor", "OKAFOR CHINEDU"), ("Chinedu Okafor", "OKAFOR CHIDI")]:
print(f" {exp!r} vs {got!r}: {same_person(exp, got)}")
print("payouts:")
print(" ", payout("B03", "0123456781", 12_500_000, "success"))
print(" ", payout("B03", "0123456781", 12_500_000, "bank_down"))
print(" ", payout("B03", "0123456780", 12_500_000, "success"))
print(" ", payout("B03", "0123456781", 12_500_000, "success", expected="Chinedu Okafor"))python3 payout.pyThen compare with a payout in the generated books and ask the switch about it.
python3 - <<'PY'
import sqlite3
from sw import call
db = sqlite3.connect("data/finance.sqlite")
t = db.execute("""SELECT id, amount_kobo, fee_kobo, external_ref, counterparty_bank FROM transactions
WHERE kind = 'payout_nip' AND status = 'succeeded' ORDER BY id LIMIT 1""").fetchone()
print(f"transaction {t[0]}: amount {t[1]}, fee {t[2]}, to {t[4]}")
for code, direction, kobo in db.execute("""SELECT a.code, e.direction, e.amount_kobo FROM entries e
JOIN accounts a ON a.id = e.account_id WHERE e.transaction_id = ? ORDER BY e.id""", (t[0],)):
print(f" {direction:<6} {code:<16} {kobo:>9}")
_, q = call("POST", "/tsq", {"session_id": t[3]})
print("requery:", q["response_code"], q["status"], q["direction"], q["source"])
rev = db.execute("SELECT external_ref FROM transactions WHERE kind = 'payout_nip' AND status = 'reversed' ORDER BY id LIMIT 1").fetchone()
print("a payout the bank returned, requeried:", call("POST", "/tsq", {"payment_reference": rev[0]})[1]["status"])
PYnames:
'Adebayo Oluwaseun' vs 'OLUWASEUN ADEBAYO TUNDE': True
'Ọlájídé Bello' vs 'BELLO OLAJIDE': True
'Chinedu Okafor' vs 'OKAFOR CHINEDU': True
'Chinedu Okafor' vs 'OKAFOR CHIDI': False
payouts:
PAYOUT-E9F2C410: transfer 00 successful, requery 00 successful -> debit wallet 12505000, credit settlement_bank 12500000, credit fee_revenue 5000
PAYOUT-D5994A3E: transfer 91 failed, requery 91 failed -> post nothing: no money left
name enquiry 07 (Invalid account): nothing sent
name enquiry returned 'HOLDER B03-6781', expected 'Chinedu Okafor': nothing sent
transaction 4: amount 2986911, fee 2500, to B21
debit wallet:764 2989411
credit settlement_bank 2986911
credit fee_revenue 2500
requery: 00 successful outward generated_ledger
a payout the bank returned, requeried: reversedThe name check passes a reordered name, a name with tone marks and dots against its plain-letter form, and an extra word, and refuses a different name. The references are random. The first payout ends 00: 12,500,000 kobo is ₦125,000, the illustrative fee band above ₦50,000 is ₦50, which is 5,000 kobo, and the wallet is debited 12,505,000 kobo, which is ₦125,050. The second is forced to 91: the bank is unavailable, nothing moved, and you post nothing. The account ending in 0 does not exist at the pseudo banks, so the name enquiry answers 07 and no transfer is sent. The fourth is stopped by your own check, because HOLDER B03-6781 is not Chinedu Okafor. The generated payout posts the same three legs as your first one: 2,986,911 + 2,500 = 2,989,411 kobo. The switch recognises generated payouts by their reference (source: generated_ledger), and reports one the bank later returned as reversed.
5. Lose a callback, then repair it. Stop the receiver with Ctrl+C in its terminal. Shorten the switch’s retry wait so the five attempts take about eight seconds, not thirty, pay into the second distributor’s number, and read the callback attempts. Save catch_up.py first.
"""Credit every inward payment in the switch's report that has no credit yet."""
import datetime as dt
from sw import call
from switch_receiver import credit, db
WAT = dt.timezone(dt.timedelta(hours=1))
today = dt.datetime.now(WAT).date().isoformat()
_, report = call("GET", "/transfers?date=" + today + "&status=successful")
inward = [t for t in report["transfers"] if t["direction"] == "inward"]
missing = 0
for t in inward:
claim = {"session_id": t["session_id"], "account_number": t["beneficiary_account"],
"customer_ref": t["beneficiary_name"].split("/")[1], "amount_kobo": t["amount_kobo"]}
if credit(claim):
missing += 1
print(f"caught up: {t['amount_kobo']} kobo to {claim['customer_ref']} (session ...{t['session_id'][-6:]})")
print(f"{len(inward)} inward payments in the report, {missing} were missing, "
f"{db.execute('SELECT COUNT(*) FROM credits').fetchone()[0]} credits now")python3 - <<'PY'
import time
from sw import call
call("POST", "/admin/faults", {"retry_base_s": 0.5}) # five attempts in about 8 seconds, not 30
_, out = call("POST", "/admin/inward", {"account_number": "8730699660", "amount_kobo": 120_000_000,
"sender_bank": "B09", "narration": "INV 4480"})
print("inward:", out["response_code"], out["account_name"], "session", out["session_id"])
time.sleep(10)
_, cb = call("GET", "/callbacks")
for c in cb["callbacks"][-5:]:
print("callback attempt", c["attempt"], "->", c["http_status"], c["outcome"])
PYStart the receiver again (python3 switch_receiver.py in the second terminal), then run the catch-up job twice and compare the receiver’s credits with the switch’s daily position.
python3 catch_up.py
python3 catch_up.py
python3 - <<'PY'
import sqlite3
from sw import call
_, s = call("GET", "/settlement")
db = sqlite3.connect("data/receiver.sqlite")
credited, = db.execute("SELECT SUM(amount_kobo) FROM credits").fetchone()
print(f"switch report: inward {s['inward_kobo']}, outward {s['outward_kobo']}, net {s['net_kobo']}")
print(f"receiver: credited {credited}; difference {s['inward_kobo'] - credited}")
PYinward: 00 OWOLEAF/C0000030 session 122900104205970536254359167590
callback attempt 1 -> None error: URLError
callback attempt 2 -> None error: URLError
callback attempt 3 -> None error: URLError
callback attempt 4 -> None error: URLError
callback attempt 5 -> None error: URLError
caught up: 120000000 kobo to C0000030 (session ...167590)
2 inward payments in the report, 1 were missing, 2 credits now
2 inward payments in the report, 0 were missing, 2 credits now
switch report: inward 595000000, outward 12500000, net 582500000
receiver: credited 595000000; difference 0Nobody was listening, so the payment of ₦1,200,000 produced five failed deliveries and then silence. The catch-up job finds it in the switch’s report, credits it, and on its second run finds nothing missing: the same once-only write protects it. The switch’s position for the day is inward 475,000,000 + 120,000,000 = 595,000,000 kobo, minus the one outward payout of 12,500,000 (the 91 payout never counted), a net of 582,500,000 kobo, or ₦5,825,000. Your credits equal the inward figure, a difference of zero.
Break the key. Stop the receiver and copy switch_receiver.py to broken_receiver.py. In the copy, change DB to data/broken.sqlite and replace the CREATE TABLE statement with this one, which makes “this customer, this amount” the rule for what counts as a duplicate:
db.execute("""CREATE TABLE IF NOT EXISTS credits (
session_id TEXT NOT NULL,
customer_ref TEXT NOT NULL,
account TEXT NOT NULL,
amount_kobo INTEGER NOT NULL CHECK (amount_kobo > 0),
PRIMARY KEY (customer_ref, amount_kobo))""")Start broken_receiver.py and pay ₦800,000 (80,000,000 kobo) twice into the third distributor’s number, 8610846881, with two separate POST /admin/inward calls and different narrations. Then sum what the switch says arrived and what the receiver holds. In the run for this chapter the receiver credited 80,000,000 kobo once, and its second line said already credited: nothing to do for a payment that had never been credited. The switch’s report listed 160,000,000 kobo inward for that number. The receiver answered 200 both times, so the switch will not retry, and the catch-up job from step 5 would skip the payment for the same reason. Someone finds the ₦800,000 difference only by comparing totals. Put the key back on session_id, and explain why the right key is the identifier the sender assigned to the event.
Template
# Virtual-account matching rules: <company>
Author (operations) · Engineer · Approver (finance controller) · Version · Date
## Purpose and scope
<What this spec decides. What it leaves out: invoice allocation, refunds, disputes.>
## Matching rules, applied in this order
1. <Rule: what is checked, what passes, what happens on a fail>
2. <...>
## What counts as unmatched
| Case | Definition (testable) | Example | Goes to |
|---|---|---|---|
| Duplicate | <...> | <...> | <...> |
| Unknown account | <...> | <...> | <...> |
| Wrong amount | <...> | <...> | <...> |
## Exceptions queue
| Type | Owner (role) | Time limit | If the limit passes |
|---|---|---|---|
## What the customer is told
| Case | Message, in plain words | Sent by | When |
|---|---|---|---|
## Daily check
<Which totals are compared, who looks, what difference triggers action.>
## How this could be wrong
<One way, and what would show it.>
## Assumptions and open questions
- <...>
## Sign-off
Approved by <finance controller>, <date> WORKED EXAMPLE
At a real company the operations lead writes this with an engineer, and the finance controller signs it. Here Mnena, in accounts receivable at Crustwell, writes it with Babatunde. The controller approves it.
Header. Crustwell virtual-account matching rules. Author Mnena. Engineer Babatunde. Approver: finance controller. Version 1, 20 November 2026.
Scope. Not covered: invoice allocation, refunds, disputes.
Rules, in order. 1. The signature must verify and the switch must confirm the session, or nothing is credited and the case goes to Babatunde. 2. If the session id has a credit already, do nothing and answer 200: a duplicate. The lab’s ₦4,750,000 callback sent twice produced one credit of ₦4,750,000. 3. The account number must be a virtual account in our mapping. The customer comes from the number, never from the narration. 4. The amount is credited to that customer, whatever it is.
Unmatched. A duplicate is the same session id, nothing else. Two payments of ₦800,000 with different session ids are two payments: the lab’s broken key collapsed them and lost ₦800,000. An unknown account is a signed, confirmed credit whose number is not in the mapping. A wrong amount is a credit that accounts receivable cannot match to any open invoice: it is credited and flagged, not rejected.
Queue. Unknown account: Mnena’s team, 1 working day, then the controller. Wrong amount: accounts receivable, 2 working days. Unconfirmed session: Babatunde, same day. These limits are assumptions.
Customer told, by accounts receivable. Payment received: ‘We have received ₦4,750,000 and recorded it on your account. We will match it to your invoices within 2 working days.’ Wrong amount: the same, plus ‘It does not match one invoice; tell us which to apply it to.’ Unknown account: ‘We are checking a payment to this number.’ Duplicate: nothing.
Daily check. The day’s credits equal the switch’s inward figure. The lab’s day read ₦5,950,000 on both sides, a difference of zero.
Could be wrong. If a distributor pays for two accounts from one transfer, rule 3 credits the wrong customer. Complaints would show it.
Now you
It is a month after Tallowmere, the online pharmacy in Ibadan, began selling to clinics on account. Each clinic has its own virtual account, and you lead operations. You write the matching rules and exceptions procedure with an engineer, and the finance controller will approve them.
Three things happened in the month. A clinic paid ₦350,000 against an invoice of ₦420,000. A callback arrived twice for one payment, and the receiver answered 200 both times. A payment landed on a number Tallowmere had retired when a clinic changed owner. Use your own lab run for the examples: the second distributor and its virtual account (the chapter’s was C0000030, account 8730699660, and your digits will differ), the ₦1,200,000 payment whose callback was lost and then caught up, and the day’s inward position of ₦5,950,000 (595,000,000 kobo).
The controller decides whether the rules and the time limits go live before the next month’s invoices are sent.
Self-check
Crustwell deploys a new release of Babatunde's receiver at 14:05. For 40 minutes it answers 503, and the switch exhausts its retries on 11 inward payments. Distributors have paid, the warehouse is waiting, and Mnena's team sees no credits. Babatunde can restore the receiver now. What does he do about the missing credits?
- DOC Regulation on Instant (Inter-Bank) Electronic Funds Transfer Services in Nigeria (CBN, 2018) Central Bank of Nigeria, 2018
The regulator's own text on name enquiry and the one-minute definition of instant. Read the sections on the duties of sending and receiving entities, and on reversal of failed transfers, which this chapter does not summarise. Its account rests on search summaries, so check each claim and the effective date here.
- DOC Revised Standards on Nigeria Uniform Bank Account Number (NUBAN) for Banks and Other Financial Institutions (CBN, 2020) Central Bank of Nigeria, 2020
The standard for the account number and its check digit. Read it for the layout of the identifier and the worked check-digit example before you write a validator. It was not read in this build, so every detail here comes from search summaries.
- DOC Circular and Regulation for the Operation of Indirect Participants in the Payment System (CBN, 2019) Central Bank of Nigeria, 2019
The rule on who may settle for a company that is not itself a participant in the payment system. Read it to see what your partner bank must do and what you must not claim. Not read in this build; the summary in the chapter comes from news coverage and excerpts.
- DOC Dedicated Virtual Accounts (Paystack documentation) Paystack, 2026
One vendor's design for virtual accounts, labelled as a vendor claim. Read how accounts are assigned to a customer and how a payment is reported. Skip the pricing and the limits, which change; check the current page before you rely on any of it.
- DOC Virtual Accounts (Flutterwave developer documentation) Flutterwave, 2026
A second vendor's design, labelled as a vendor claim. Read it beside the Paystack page to see where static and dynamic accounts differ in what they require. The comparison is the point, not a recommendation. Pages differ between API versions, so note which one you read.
- DOC RFC 2104: HMAC: Keyed-Hashing for Message Authentication Krawczyk, Bellare and Canetti, 1997
The construction behind both the callback signature and the card provider's. Read the introduction and the definition of HMAC in the first few pages. Skip the implementation notes unless you write your own hash code, which you should not.
- DOC hmac: Keyed-Hashing for Message Authentication (Python documentation) Python Software Foundation, 2026
The standard library reference for the module your receiver uses. Read the entry for compare_digest, which says why to use it and not == for a signature check. The link is the documentation's canonical page for current Python 3; version numbers in details may change.
All companies and people in these examples are fictional. Any resemblance to a real business or person is unintended.