Payment states, failures, reversals and refunds
A payment is never 'done' until you know which of its few states it is in. Pending is not failed, successful can still flip, and a refund is a new payment going the other way
In the lab's books, 20,897 outward NIP payouts came back from the switch as successful. About how many were returned to the sender's wallet days later, after Owoleaf had counted them as paid?
An order, a charge and a payout each look like one row with one status column. They are not. Each is a small machine: a few states, a list of legal moves between them, and events from outside that drive the moves. Bugs in this part of payments come from three habits: collapsing two machines into one column, treating an unknown outcome as a failure, and moving money for an event without checking that the move is legal from the current state. The lesson on authorise, capture and refund drew the card machine as a picture. Here you read the machines the lab’s two mocks actually run, in code.
The lab runs on Owoleaf, as in module 1. It stands where Lumora stands in the story: it is the business that takes a card payment, sends a payout and sometimes has to give the money back.
Two machines, and you sit between them
Lumora’s customer paid for airtime, so two things must happen. The card money must be captured, and the airtime must be delivered. Each has its own owner, its own clock and its own failures.
| Machine | Owned by | States it can be in | What can go wrong that the other cannot see |
|---|---|---|---|
| The charge | The payment provider | pending, success, failed | The card is declined, or the customer never completes authentication |
| The airtime top-up (the “vend”) | Lumora’s recharge platform | requested, delivered, failed, unknown | The request times out and nobody knows whether the phone was topped up |
| The order | You | whatever you define | Your own code disagrees with both of the above |
The order is the join. If it has one column, status = 'failed', you cannot tell “card declined, nothing to give back” from “card charged, airtime not delivered, a refund is owed”. Those need opposite actions. The rule that prevents this: keep the provider’s state for the charge in its own field, exactly as reported, keep your own state for the other leg in a second field, and derive the order’s state from the pair. A person reading a row should be able to say what is owed to whom.
Two more rules follow from this, and the rest of the chapter applies them.
First, a machine has legal moves. A charge can go from pending to success. It cannot go from success to pending. If an event asks for an illegal move, do not apply it and do not crash. Log it, keep the state, and look at it later. An out-of-order or repeated webhook then costs nothing.
Second, you need one state the provider does not have: unknown, or awaiting requery. When a call times out, the right state for your record is “I asked, I do not know the answer”, with a time attached, and the exit from it is asking again. A timeout is not a failure. The chapter on idempotency teaches how to make the asking safe; this chapter is about what to record while you wait.
The charge machine
The mock provider has three charge states. A charge is born in one of them and, if it was born pending, moves once.
In the lab you drive all four test cards and watch the sequence each one produces. Card 0001 is born success, 0002 is born failed (“Insufficient funds”), 0003 is born pending (“Awaiting customer authentication”) and later succeeds, and 0004 is born pending and later fails (“Authentication failed”). Those are the whole machine. Real providers have more states. As a vendor example, one provider’s documentation lists a payment object with statuses for needing a payment method, needing customer action, processing, needing capture, cancelled and succeeded, and it says asynchronous methods such as bank debits can sit in processing for days (Stripe’s documentation of its PaymentIntent lifecycle, a vendor description of one provider and not a rule: the statuses requires_payment_method, requires_confirmation, requires_action, processing, requires_capture, canceled and succeeded; search results say processing is used for asynchronous methods that can take up to a few days)as of 2026-11. The names differ and the shape does not: some states are waiting rooms, and a few are final.
What pending demands of you is a refusal. Do not fulfil the order. Do not charge again under a new reference, because the first charge may yet succeed and the customer will be charged twice. Wait for the provider’s charge.success or charge.failed event, and when it arrives, verify it by calling GET /charges/{reference} before you act, as the chapter on integrating a provider shows. Events are hints that something changed. The verification call is the fact.
The payout machine, and the state you add
The mock switch’s outward transfers have four states and several response codes. The code is what the call answered. The status is what the transfer is.
| Status | Response code | Meaning | Final? |
|---|---|---|---|
successful |
00 |
The beneficiary bank accepted it | No: it can become reversed |
failed |
91 (bank not available) |
Nothing moved | Yes |
pending |
09 |
In progress: the answer arrives on requery | No |
reversed |
00 on the requery, status reversed |
It went through and was then returned | Yes |
Compare it with the charge machine. It has one more way to go wrong. A charge that succeeded stays succeeded until a refund, which is a new object. A payout that succeeded can flip to reversed with no action from you, because the beneficiary’s bank returned it. So a successful outward payout is a state, not an ending.
The mock has a fourth thing to teach, which is the case where you get no answer at all. With the header X-Mock-Force: timeout the switch holds the request for 35 seconds. A client that gives up after two seconds has no code and no status. The transfer exists, it is pending, and a few seconds later (45 seconds after the call, in the lab) it becomes successful. If that client had marked the payout failed and sent it again, the customer would have been paid twice. This is the extra state: your record says unknown, and the only legal exit is a requery (POST /tsq) that returns something definite.
The CBN’s Regulation on Instant (Inter-Bank) Electronic Funds Transfer Services in Nigeria is published as a PDF on the CBN’s site. Search summaries describe it as requiring the receiving bank to credit the beneficiary within 60 seconds and, where that is impracticable for security or system reasons, to notify the parties, with pending credits applied within 24 hours. The deadline for returning the money of a failed transfer is where sources disagree: press accounts give 10 minutes in one case and 24 hours in another, and the 2017 exposure draft used 24 hours. Press reports are not the rule. This build could not open the PDF, so every figure here rests on search summaries: read the regulation’s sections on failed transactions before you rely on any of themas of 2026-11.
Those figures are not the mock’s. The mock’s pending_seconds of 10, reverse_seconds of 30 and timeout_hold_s of 35 are illustrative timings chosen so that a lab runs in a minute. Never design to them.
Failure, reversal and refund are three different things
People use the three words loosely. Your code cannot.
A failure means the money never moved, or the attempt was refused before it could. The charge was declined; the transfer answered 91. There is nothing to give back, so the ledger has no entries, as the generator shows: failed attempts carry a reason and no entries.
A reversal means the money did move and the other side returned it, without anyone asking for it. A payout came back from the beneficiary’s bank. It arrives as an event or a changed status, and your side must put the money back where it belongs.
A refund means the money moved and you decide to send it back, usually because the customer asked or because you could not deliver what they paid for. It is a new payment, in the opposite direction, with its own state machine, its own timing and its own bound.
The distinction decides who acts. A failure needs no money movement. A reversal needs one you did not choose, triggered by the other side, which you must accept once. A refund needs one you choose, which you must send once and only up to what was paid. Lumora’s customer, charged for airtime she never received, is owed a refund: the card charge succeeded, the delivery did not, and Lumora chooses to send the money back. A scheme’s dispute process, where the cardholder’s bank takes the money back, is a fourth thing, a chargeback. The lesson on chargebacks shows it, and a module 3 chapter takes it on in full.
A CBN press release of June 2020 on payment channels, as summarised in search results, says that from 8 June 2020 failed on-us ATM transactions (ATMs of the customer’s own bank) are reversed instantly, with manual reversal inside 24 hours if instant reversal fails, and that disputed or failed POS and web transactions are resolved within 72 hours. The Guidelines on Operations of Electronic Payment Channels in Nigeria, a separate PDF on the CBN’s site, appear in one search summary and in one fintech company’s commentary to say 48 hours for POS and web refunds, so sources differ. A CBN exposure draft of October 2025 on ATM operations says it would supersede the ATM requirements of the 2020 Guidelines, and no final version was found. These rest on search summaries, not on the documents’ textas of 2026-11The CBN’s Consumer Protection Regulations (2019) cover complaints handling and redress, and search summaries say an annexure sets the resolution timelines, with penalties for missing them. This build could not read the tableas of 2026-11. The CBN’s own page for customers tells them to allow their bank about two weeks to resolve a complaint before escalating to the CBNas of 2026-11. A revised draft of the regulations was issued for comment in early 2024, and whether it was adopted is unconfirmed, so its periods may differ. Check the current text for who must resolve what, and by when, before you set a refund promise for customers.
Recording a reversal: new rows, never edits
Module 1 taught the rule: entries are movements and balances are derived (double entry for engineers). A reversal tests it. When a payout comes back, you do not delete the payout’s entries and you do not edit them. You post a new transaction whose entries mirror the originals, and you point it at the payout.
The generator does exactly that, and step 4 of the lab prints one pair. Payout 494 moves ₦647.26 for a wallet, with a ₦10.00 fee:
| Transaction | Account | Direction | Amount (kobo) |
|---|---|---|---|
494, payout_nip |
wallet:273 |
debit | 65,726 |
settlement_bank |
credit | 64,726 | |
fee_revenue |
credit | 1,000 | |
632, payout_reversal |
settlement_bank |
debit | 64,726 |
fee_revenue |
debit | 1,000 | |
wallet:273 |
credit | 65,726 |
Each transaction balances: 64,726 + 1,000 = 65,726, on both. Taken together the wallet is back where it started, 65,726 − 65,726 = 0, and fee_revenue has earned nothing. The reversal two days later is a separate row, related_transaction_id points at 494, and it carries the same external_ref, the 30-digit session reference, because a return quotes the original payment’s reference. On the partner bank’s statement the pair appears as NIP OUTWARD debit of 64,726 and, two days later, NIP RETURN credit of 64,726. The statement never mentions the ₦10.00 fee. That is the book-keeping inside Owoleaf: the principal moved at the bank, the fee moved between Owoleaf’s own accounts.
Two details in this are choices the generator made. It returns the fee to the wallet along with the amount. Whether the fee comes back is a product and contract decision, and a different company could keep it. And it changes one thing on the original row: the status column goes from succeeded to reversed. That is a deliberate mutation of a state field, with the money in the new rows. If you ever find yourself editing an entry to fix a reversal, stop. The state may change; the history of movements must not.
The ledger also has a rule to enforce that the data shows. Only a payout that succeeded can be reversed. A failed payout moved nothing, so there is nothing to return. A payout already marked reversed has been returned once. Step 5 of the lab makes you write the function that holds those two rules, and the break shows what happens when you take them out.
Refunds: a new payment, bounded by what was paid
A refund is a request to the provider: send this much of this charge back to the card. The mock models the parts that matter.
A refund is only possible on a charge in success. A request on a failed or pending charge is a 400 with not_refundable. The amount is bounded by what was captured minus what has already been refunded. A request above the bound is a 400. A request with no amount refunds what is left. The refund itself is pending for pending_seconds (5 by default), then processed, and a refund.processed event announces it. Observe one oddity in the lab. The charge’s refunded_kobo rises when the refund is requested, not when it is processed. So the bound is computed over refunds asked for, pending ones included, and a second refund request made while the first is pending is judged against the first. Your own record should work the same way: reserve the amount when you ask.
This is the same bound as the lesson’s rule refunded ≤ captured, here applied to a charge that has three possible amounts in flight: the original, the pending refund and the processed refunds.
The money side follows the card machine from module 1. At capture you debited card_clearing, the claim on the processor. At refund you reduce that claim, because the provider will deduct the refund from your next settlement. Take the lab’s numbers. In the run quoted in step 2, four captures of ₦2,000 each made a day’s gross of 800,000 kobo, and two refunds of 80,000 and 120,000 kobo were processed that day, 200,000 in all. The settlement report gives a fee of 8,000 kobo, which is 1% of 800,000, and a net of 592,000.
Post the refunds when you request them, from the wallet that holds the customer’s money. Then post the settlement:
| When | Account | Direction | Amount (kobo) |
|---|---|---|---|
| Refund requested | wallet (the customer’s balance, a liability) |
debit | 200,000 |
card_clearing |
credit | 200,000 | |
| Next settlement | settlement_bank |
debit | 592,000 |
processing_expense |
debit | 8,000 | |
card_clearing |
credit | 600,000 |
Check both: 200,000 = 200,000, and 592,000 + 8,000 = 600,000. Now check the account: card_clearing was debited 800,000 at capture and credited 200,000 + 600,000 = 800,000 since, so it returns to zero. If you had posted the settlement as a credit of the whole 800,000, the account would be 200,000 below zero, and that gap is the refunds you forgot. The generated ledger has no refunds in it, so this posting is the chapter’s design, not generated data, and it leaves out the funding fee: in the generated ledger a card funding credits the wallet with the amount less a 1.5% fee and credits fee_revenue with the fee. Refunding the whole charge and returning that fee would debit the wallet 197,000 and fee_revenue 3,000 instead of the wallet 200,000. Use it as the pattern.
Look at the fee. The settlement’s fee is still 8,000, the 1% of the gross, and the refunded 200,000 was inside that gross. The mock’s processor keeps its fee on money that was refunded. So a refund costs Owoleaf the amount, and the fee on it, and the fee the customer paid on the way in may or may not come back, depending on a rule you set. That is a modelling choice of the mock and a contract term in real life; as a vendor example, one provider’s documentation says the original processing fees are not returned when you refund (Stripe’s refund documentation, a vendor claim about one provider’s pricing, not a rule: search results say the processing fees from the original payment are not returned to the business on a refund)as of 2026-11. Read your own provider’s contract before you promise a customer a “full refund”.
Applying events safely
Put the pieces together as one routine, and the failures in this chapter each have a place where it refuses.
An event arrives, or you query. Read the current state from your own record. Look up whether the move from that state to the reported one is legal. If it is not, log it and stop. If it is, change the state and post the money in a single database transaction, so that a crash cannot leave the state moved and the entries missing, or the reverse. Key the whole thing on something that appears once per event: the provider’s event id, the switch’s session id, or the original payout’s id for a reversal. A second arrival of the same event then finds the state already moved and does nothing.
That is idempotency, applied to a state machine. The chapter on idempotency and moving money exactly once shows the key on a request; here the same idea sits inside your own write. Webhook delivery is the other half: providers send events at least once, in any order, and the lesson on webhook delivery shows why. Retried requests with timeouts follow the same logic: the lesson on idempotency has the sim.
Where it goes wrong
Name the failures first. Each looks like normal behaviour until the day it costs money.
Treating pending as failed. The customer is told “payment failed” and tries again. The first charge then succeeds. She has paid twice and has two refunds coming. The fix is a state for waiting and a screen that says so.
Treating a timeout as a failure. The same mistake on the payout side: no answer, so the payout is marked failed and sent again. The first one went through. The switch’s duplicate-reference answer, 26, is a net under this, and only if you reused the reference.
One status column for two legs. The order says failed while the money is held. Nothing in the data tells support whether to refund. Keep the provider’s state beside your own.
Counting a successful payout as final. Owoleaf’s reversed payouts come back one to three days later. Any report of “paid out” made before then overstates it by the returns, and any wallet that spent the returned money in the meantime would have gone negative without a ledger that refuses. In the lab’s data that is 98 returns worth ₦2,653,250.62 of principal, and ₦2,375.00 of fees.
A refund bigger than the money. The bound is on the charge, so two support agents each refunding the order total can send twice what was paid. Reserve the amount, and refuse above the bound in the same write.
Forgetting what settlement does to a refund. The processor deducts it from the next payout. The books that credit the whole gross are wrong by exactly the refunds.
Applying a reversal twice. This is the one the lab’s break lets you watch. The books still balance and the wallet is credited twice.
What you can prove, and what you cannot
You can prove that every state change the code applied was legal, that each posted transaction balances, and that a payout has at most one reversal. You cannot prove from your own records that the provider’s state is the one you hold: that needs the verification call, and, for money, the reconciliation chapter. The settlement chapter takes up the timing of the money and the wallets chapter takes up where a refunded customer’s balance may sit. For now: record states as the provider reports them, add one state for “do not know”, move only along legal edges, and post new rows.
You work in labs/finance. Every step is Python run from that folder, against the two mocks and data/finance.sqlite. The mocks’ default timings are what the chapter quotes: the provider resolves a pending charge or refund after 5 seconds, and the switch resolves a pending transfer after 10 seconds, flips a reversed transfer after 30 and holds a timed-out request for 35 (--pending-seconds on either mock, and --reverse-seconds and --timeout-hold-s on the switch, shorten them). Your timings can differ by a second or two, and your references and ids differ from those quoted.
1. Start both mocks and drive the charge machine. In two terminals, start the services on their default ports. Start them fresh, so the numbers in step 2 match:
cd labs/finance
python3 generate.py # skip if data/finance.sqlite exists
python3 mock_provider.py --freshcd labs/finance
python3 mock_switch.py --freshIn a third terminal, run this. It charges ₦2,000 (200,000 kobo) on each of the four test cards, watches the status until it stops changing, and refuses any move the machine does not allow.
cd labs/finance
python3 - <<'PY'
import json, secrets, time, urllib.request, urllib.error
BASE = "http://127.0.0.1:8101"
HDR = {"Authorization": "Bearer sk_test_owoleaf_mock", "Content-Type": "application/json"}
def call(method, path, body=None):
data = json.dumps(body).encode() if body is not None else None
req = urllib.request.Request(BASE + path, data=data, headers=HDR, method=method)
try:
with urllib.request.urlopen(req) as r:
return r.status, json.load(r)
except urllib.error.HTTPError as e:
return e.code, json.load(e)
# The charge machine, as the mock behaves. A charge is born in one of three states.
BORN = {"success", "failed", "pending"}
NEXT = {"pending": {"success", "failed"}, "success": set(), "failed": set()}
for last4, what in (("0001", "approved"), ("0002", "declined"), ("0003", "pending, then approved"), ("0004", "pending, then declined")):
ref = "LUMORA-" + secrets.token_hex(4)
_, body = call("POST", "/charges", {"reference": ref, "amount_kobo": 200_000, "customer_ref": "C0000042",
"card_number": "411111111111" + last4, "metadata": {"order": "airtime"}})
seen, t0 = [body["charge"]["status"]], time.time()
assert seen[0] in BORN
while seen[-1] == "pending" and time.time() - t0 < 15:
time.sleep(1)
_, body = call("GET", "/charges/" + ref)
s = body["charge"]["status"]
if s != seen[-1]:
assert s in NEXT[seen[-1]], f"illegal move {seen[-1]} -> {s}"
seen.append(s)
c = body["charge"]
print(f"card ...{last4} ({what}): {' -> '.join(seen)}; response={c['gateway_response']!r}; paid_at={'set' if c['paid_at'] else 'null'}")
PYcard ...0001 (approved): success; response='Approved'; paid_at=set
card ...0002 (declined): failed; response='Insufficient funds'; paid_at=null
card ...0003 (pending, then approved): pending -> success; response='Approved'; paid_at=set
card ...0004 (pending, then declined): pending -> failed; response='Authentication failed'; paid_at=nullFour cards, three different paths through one small machine. Only pending ever moves, and only once. The assertion never fires, because the mock never makes an illegal move. Yours must hold if a webhook arrives twice or late.
2. Refuse what cannot be refunded, then refund in parts. This script tries a refund on a declined charge and on a pending one, then refunds ₦800 of a ₦2,000 charge, tries to refund more than is left, waits for processed, refunds the rest, reads the provider’s events and reads the next settlement.
python3 - <<'PY'
import datetime as dt, json, secrets, time, urllib.request, urllib.error
BASE = "http://127.0.0.1:8101"
HDR = {"Authorization": "Bearer sk_test_owoleaf_mock", "Content-Type": "application/json"}
def call(method, path, body=None):
data = json.dumps(body).encode() if body is not None else None
req = urllib.request.Request(BASE + path, data=data, headers=HDR, method=method)
try:
with urllib.request.urlopen(req) as r:
return r.status, json.load(r)
except urllib.error.HTTPError as e:
return e.code, json.load(e)
def charge(last4, kobo=200_000):
ref = "LUMORA-" + secrets.token_hex(4)
call("POST", "/charges", {"reference": ref, "amount_kobo": kobo, "customer_ref": "C0000042",
"card_number": "411111111111" + last4, "metadata": {"order": "airtime"}})
return ref
print("1. refunds the machine refuses")
declined, pending = charge("0002"), charge("0003")
for name, ref in (("declined charge", declined), ("pending charge", pending)):
st, b = call("POST", "/refunds", {"reference": ref, "amount_kobo": 50_000})
print(f" refund on a {name}: HTTP {st}, {b['error']}: {b['message']}")
print("2. a partial refund, then the rest")
ref = charge("0001")
st, b = call("POST", "/refunds", {"reference": ref, "amount_kobo": 80_000})
r1 = b["refund"]
_, c = call("GET", "/charges/" + ref)
print(f" refund 1 for 80000: HTTP {st}, status={r1['status']}; charge refunded_kobo already {c['charge']['refunded_kobo']}")
st, b = call("POST", "/refunds", {"reference": ref, "amount_kobo": 150_000})
print(f" refund for 150000 (only 120000 left): HTTP {st}, {b['message']}")
t0 = time.time()
while call("GET", "/refunds/" + r1["id"])[1]["refund"]["status"] != "processed":
time.sleep(1)
print(f" refund 1 processed after about {round(time.time() - t0)} s")
st, b = call("POST", "/refunds", {"reference": ref}) # no amount: refund what is left
print(f" refund of the rest: HTTP {st}, amount_kobo={b['refund']['amount_kobo']}")
st, b = call("POST", "/refunds", {"reference": ref, "amount_kobo": 10_000})
print(f" one more: HTTP {st}, {b['message']}")
print("3. what the provider told us")
time.sleep(7)
_, ev = call("GET", "/events")
for e in ev["events"]:
d = e["data"]
if e["type"] == "refund.processed":
print(f" refund.processed refund {d['id']} for {d['amount_kobo']} on {d['charge_reference']}")
mine = [e["type"] for e in ev["events"] if e["data"].get("reference") == ref]
print(f" events on the charge itself: {mine}")
print("4. the next settlement")
tomorrow = (dt.datetime.now(dt.timezone(dt.timedelta(hours=1))).date() + dt.timedelta(days=1)).isoformat()
_, s = call("GET", "/settlements?date=" + tomorrow)
mock_lines = [l for l in s["lines"] if l["source"] == "mock"]
print(f" gross {s['gross_kobo']} from {len(mock_lines)} captures; fee {s['fee_kobo']}; refunds {s['refunds_kobo']}; net {s['net_kobo']}")
print(f" check: {s['gross_kobo']} - {s['fee_kobo']} - {s['refunds_kobo']} = {s['gross_kobo'] - s['fee_kobo'] - s['refunds_kobo']}")
PY1. refunds the machine refuses
refund on a declined charge: HTTP 400, not_refundable: charge is failed
refund on a pending charge: HTTP 400, not_refundable: charge is pending
2. a partial refund, then the rest
refund 1 for 80000: HTTP 200, status=pending; charge refunded_kobo already 80000
refund for 150000 (only 120000 left): HTTP 400, refundable amount is 120000 kobo
refund 1 processed after about 5 s
refund of the rest: HTTP 200, amount_kobo=120000
one more: HTTP 400, refundable amount is 0 kobo
3. what the provider told us
refund.processed refund rf_d62b9b945a274a64 for 80000 on LUMORA-89528f42
refund.processed refund rf_89576bc31d4c498f for 120000 on LUMORA-89528f42
events on the charge itself: ['charge.success']
4. the next settlement
gross 800000 from 4 captures; fee 8000; refunds 200000; net 592000
check: 800000 - 8000 - 200000 = 592000Only a successful charge can be refunded. The bound counts the pending refund (80,000 already shows as refunded), so asking for 150,000 against 120,000 left is refused. The refund is a separate object with its own events: the charge’s own events do not change. The settlement’s gross of 800,000 is four captures of 200,000 (steps 1 and 2 made four successful charges), the fee is 1% of the gross, 8,000, and the refunds are taken off the payout: 800,000 − 8,000 − 200,000 = 592,000. The fee is not reduced by the refunds. Your gross is different if you made other charges today.
3. Drive the payout machine on the switch. This script makes five transfers with the five forced outcomes, gives up on the timed-out one after two seconds, then requeries every transfer every two seconds and prints each change. It reads the switch’s net position at the start and at the end.
python3 - <<'PY'
import datetime as dt, json, socket, time, urllib.request, urllib.error
BASE = "http://127.0.0.1:8102"
HDR = {"Authorization": "Bearer sw_test_owoleaf_mock", "Content-Type": "application/json"}
def call(method, path, body=None, force=None, timeout=10):
h = dict(HDR, **({"X-Mock-Force": force} if force else {}))
data = json.dumps(body).encode() if body is not None else None
req = urllib.request.Request(BASE + path, data=data, headers=h, method=method)
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)
# The payout machine, as the mock behaves. 09 is "in progress": not a state to give up on.
BORN = {"successful", "failed", "pending"}
NEXT = {"pending": {"successful", "failed"}, "successful": {"reversed"}, "failed": set(), "reversed": set()}
_, ne = call("POST", "/name-enquiry", {"bank_code": "B03", "account_number": "0123456789"})
print(f"name enquiry: {ne['response_code']} {ne['account_name']}")
plan = [("success", 100_000), ("bank_down", 110_000), ("pending", 120_000), ("timeout", 130_000), ("reverse", 140_000)]
refs, born = {}, {}
for force, kobo in plan:
ref = "LUMORA-REFUND-" + force
try:
st, b = call("POST", "/transfers", {"payment_reference": ref, "name_enquiry_ref": ne["name_enquiry_ref"],
"sender_account": "9000000042", "amount_kobo": kobo, "narration": "airtime refund"},
force=force, timeout=2)
print(f"{force:<10} HTTP {st}, code {b['response_code']}, status {b['status']}")
born[force] = b["status"]
except (socket.timeout, TimeoutError, urllib.error.URLError):
print(f"{force:<10} no answer within 2 s: the client has to requery")
born[force] = "pending" # unknown, so treat as in progress
refs[force] = ref
t0 = time.time()
seen = {f: [born[f]] for f in refs}
today = dt.datetime.now(dt.timezone(dt.timedelta(hours=1))).date().isoformat()
def position(label):
_, s = call("GET", "/settlement?date=" + today)
print(f"{label}: outward {s['outward_kobo']}, returned {s['returned_kobo']}, inward {s['inward_kobo']}, "
f"pending {s['pending_kobo']}, net {s['net_kobo']}")
position("position at the start")
def settled(): # nothing in progress, and the reversal has happened
return all(s[-1] != "pending" for s in seen.values()) and seen["reverse"][-1] == "reversed"
while time.time() - t0 < 70 and not settled():
time.sleep(2)
for f, ref in refs.items():
_, q = call("POST", "/tsq", {"payment_reference": ref})
s = q["status"]
if s != seen[f][-1]:
assert s in NEXT[seen[f][-1]], f"illegal move {seen[f][-1]} -> {s}"
seen[f].append(s)
print(f" {round(time.time() - t0):>2} s {f:<10} now {s} (code {q['response_code']})")
position("position at the end")
for f, s in seen.items():
print(f"{f:<10} {' -> '.join(s)}")
PYname enquiry: 00 HOLDER B03-6789
success HTTP 200, code 00, status successful
bank_down HTTP 200, code 91, status failed
pending HTTP 200, code 09, status pending
timeout no answer within 2 s: the client has to requery
reverse HTTP 200, code 00, status successful
position at the start: outward 240000, returned 0, inward 0, pending 250000, net -240000
8 s pending now successful (code 00)
30 s reverse now reversed (code 00)
44 s timeout now successful (code 00)
position at the end: outward 490000, returned 140000, inward 0, pending 0, net -350000
success successful
bank_down failed
pending pending -> successful
timeout pending -> successful
reverse successful -> reversedFive forced outcomes, four different paths. The failed one is final at birth, and the timed-out one has no answer at all until the requery shows successful: a client that had marked it failed and paid again would have paid twice. The reversed one answers 00 and successful, and 30 seconds later the requery says reversed. The position moves with it. At the start, 240,000 is outward (the successful 100,000 and the soon-to-be-reversed 140,000) and 250,000 is pending (120,000 and 130,000). At the end outward is 490,000, which is 100,000 + 120,000 + 130,000 + 140,000, and 140,000 has come back as returned, so the net is 140,000 − 490,000 = −350,000. Owoleaf really paid out 350,000. Counting at the start, you would have said 240,000; counting before the flip, 490,000. Your seconds can differ by one or two.
4. Find the 98 returned payouts in the ledger. Back to Owoleaf’s generated books. This script counts payouts and reversals by status, joins every reversed payout to its return, and prints one pair entry by entry with the partner bank’s statement lines for it.
python3 - <<'PY'
import sqlite3
db = sqlite3.connect("data/finance.sqlite")
q = lambda sql, *a: db.execute(sql, a).fetchall()
naira = lambda k: f"₦{k // 100:,}.{k % 100:02d}"
print("1. payouts by status")
for kind, status, n in q("SELECT kind, status, COUNT(*) FROM transactions WHERE kind IN ('payout_nip','payout_reversal') GROUP BY 1, 2 ORDER BY 1, 2"):
print(f" {kind:<16} {status:<10} {n:>6}")
print("2. each reversed payout and its reversal")
pairs = q("""SELECT p.id, r.id, p.external_ref = r.external_ref, p.amount_kobo = r.amount_kobo, p.fee_kobo = r.fee_kobo,
julianday(substr(r.created_at,1,10)) - julianday(substr(p.created_at,1,10))
FROM transactions p JOIN transactions r ON r.related_transaction_id = p.id
WHERE p.kind = 'payout_nip' AND p.status = 'reversed' AND r.kind = 'payout_reversal'""")
print(f" {len(pairs)} pairs; same reference on {sum(x[2] for x in pairs)}; same amount on {sum(x[3] for x in pairs)}; same fee on {sum(x[4] for x in pairs)}")
days = {}
for x in pairs:
days[int(x[5])] = days.get(int(x[5]), 0) + 1
print(f" days from payout to reversal: {dict(sorted(days.items()))}")
amt, fee = db.execute("SELECT SUM(amount_kobo), SUM(fee_kobo) FROM transactions WHERE kind='payout_reversal'").fetchone()
print(f" returned in all: {amt} kobo of principal ({naira(amt)}) and {fee} kobo of fees ({naira(fee)})")
print("3. one pair, entry by entry")
pid, rid = pairs[0][0], pairs[0][1]
for tid in (pid, rid):
k, st, ref, at = db.execute("SELECT kind, status, external_ref, created_at FROM transactions WHERE id = ?", (tid,)).fetchone()
print(f" transaction {tid}: {k}, status {st}, at {at}")
for code, d, kobo in q("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", tid):
print(f" {d:<6} {code:<16} {kobo:>9}")
print(f" reference {ref}")
for line, vd, d, kobo, narr in q("SELECT line, value_date, direction, amount_kobo, narration FROM bank_statement WHERE reference = ? ORDER BY line", ref):
print(f" statement line {line}: {vd} {d} {kobo} {narr}")
print("4. over every pair: what the wallet and the books ended with")
net_wallet = q("""SELECT SUM(CASE e.direction WHEN 'credit' THEN e.amount_kobo ELSE -e.amount_kobo END)
FROM entries e JOIN accounts a ON a.id = e.account_id
WHERE a.type = 'liability' AND e.transaction_id IN (SELECT id FROM transactions WHERE kind='payout_reversal' OR (kind='payout_nip' AND status='reversed'))""")[0][0]
orig_fee = db.execute("""SELECT SUM(e.amount_kobo) FROM entries e JOIN accounts a ON a.id = e.account_id
JOIN transactions t ON t.id = e.transaction_id
WHERE a.code='fee_revenue' AND t.kind='payout_nip' AND t.status='reversed'""").fetchone()[0]
back_fee = db.execute("""SELECT SUM(e.amount_kobo) FROM entries e JOIN accounts a ON a.id = e.account_id
JOIN transactions t ON t.id = e.transaction_id
WHERE a.code='fee_revenue' AND t.kind='payout_reversal' AND e.direction='debit'""").fetchone()[0]
print(f" wallets' net change over the 98 payouts and 98 reversals: {net_wallet} kobo")
print(f" fee_revenue: credited {orig_fee} on the payouts, debited {back_fee} on the reversals")
PY1. payouts by status
payout_nip failed 995
payout_nip reversed 98
payout_nip succeeded 20799
payout_reversal succeeded 98
2. each reversed payout and its reversal
98 pairs; same reference on 98; same amount on 98; same fee on 98
days from payout to reversal: {1: 42, 2: 28, 3: 28}
returned in all: 265325062 kobo of principal (₦2,653,250.62) and 237500 kobo of fees (₦2,375.00)
3. one pair, entry by entry
transaction 494: payout_nip, status reversed, at 2026-01-21T16:42:14+01:00
debit wallet:273 65726
credit settlement_bank 64726
credit fee_revenue 1000
transaction 632: payout_reversal, status succeeded, at 2026-01-23T16:14:00+01:00
debit settlement_bank 64726
debit fee_revenue 1000
credit wallet:273 65726
reference 137882349175196281217228608476
statement line 404: 2026-01-21 DR 64726 NIP OUTWARD C0000273
statement line 513: 2026-01-23 CR 64726 NIP RETURN
4. over every pair: what the wallet and the books ended with
wallets' net change over the 98 payouts and 98 reversals: 0 kobo
fee_revenue: credited 237500 on the payouts, debited 237500 on the reversalsThere are 98 reversed payouts and 98 reversals, matched one to one by related_transaction_id, with the same reference, amount and fee on each. They come back one, two or three days later. The wallets end with a net change of zero, and the fee Owoleaf earned on those payouts is fully given back. The original payout still has its three entries. Only its status changed. On the statement the pair is a debit and, two days later, a credit of the principal only. The fee never reaches the bank.
5. Post a reversal exactly once. Now write the posting. Run this. It copies the ledger to work/copy.sqlite, and reverse_payout posts a return in one database transaction, only for a payout in the state succeeded.
python3 - <<'PY'
import os, shutil, sqlite3
os.makedirs("work", exist_ok=True)
shutil.copy("data/finance.sqlite", "work/copy.sqlite")
db = sqlite3.connect("work/copy.sqlite")
GUARD = True # the break at the end of the lab turns this off
def wallet_balance(account_id):
return db.execute("""SELECT COALESCE(SUM(CASE direction WHEN 'credit' THEN amount_kobo ELSE -amount_kobo END), 0)
FROM entries WHERE account_id = ?""", (account_id,)).fetchone()[0]
def reverse_payout(payout_id, at):
"""The switch says this payout was returned. Post the return once: money and fee go back to the wallet."""
p = db.execute("""SELECT kind, status, customer_id, amount_kobo, fee_kobo, external_ref, counterparty_bank
FROM transactions WHERE id = ?""", (payout_id,)).fetchone()
if p is None or p[0] != "payout_nip":
return "refused: not a payout"
if GUARD and p[1] != "succeeded": # failed has nothing to return; reversed was returned already
return f"refused: the payout is {p[1]}"
_, _, cid, amount, fee, ref, bank = p
acct = lambda code: db.execute("SELECT id FROM accounts WHERE code = ?", (code,)).fetchone()[0]
with db: # one database transaction: all of it or none of it
cur = db.execute("""INSERT INTO transactions (kind, status, customer_id, amount_kobo, fee_kobo, rail,
external_ref, counterparty_bank, related_transaction_id, created_at)
VALUES ('payout_reversal', 'succeeded', ?, ?, ?, 'nip', ?, ?, ?, ?)""",
(cid, amount, fee, ref, bank, payout_id, at))
tid = cur.lastrowid
wallet = db.execute("SELECT id FROM accounts WHERE code = ?", (f"wallet:{cid}",)).fetchone()[0]
for account, direction, kobo in ((acct("settlement_bank"), "debit", amount), (acct("fee_revenue"), "debit", fee),
(wallet, "credit", amount + fee)):
db.execute("INSERT INTO entries (transaction_id, account_id, direction, amount_kobo, posted_at) VALUES (?,?,?,?,?)",
(tid, account, direction, kobo, at))
db.execute("UPDATE transactions SET status = 'reversed' WHERE id = ?", (payout_id,))
return f"posted transaction {tid}: {amount} + {fee} kobo back to wallet:{cid}"
pid, cid, amount, fee = db.execute("""SELECT id, customer_id, amount_kobo, fee_kobo FROM transactions
WHERE kind = 'payout_nip' AND status = 'succeeded' ORDER BY id LIMIT 1""").fetchone()
wallet = db.execute("SELECT id FROM accounts WHERE code = ?", (f"wallet:{cid}",)).fetchone()[0]
failed = db.execute("SELECT id FROM transactions WHERE kind = 'payout_nip' AND status = 'failed' ORDER BY id LIMIT 1").fetchone()[0]
AT = "2026-06-30T12:00:00+01:00"
print(f"payout {pid}: {amount} kobo and a {fee} kobo fee from wallet:{cid}")
print(f"wallet balance now: {wallet_balance(wallet)}")
print("1st reversal:", reverse_payout(pid, AT))
print(f"wallet balance after: {wallet_balance(wallet)}")
print("2nd reversal:", reverse_payout(pid, AT))
print(f"wallet balance after: {wallet_balance(wallet)}")
print(f"reversal of failed payout {failed}:", reverse_payout(failed, AT))
n = db.execute("SELECT COUNT(*) FROM transactions WHERE kind = 'payout_reversal' AND related_transaction_id = ?", (pid,)).fetchone()[0]
print(f"reversals recorded for payout {pid}: {n}")
db.close()
PY
python3 check.py --db work/copy.sqlitepayout 4: 2986911 kobo and a 2500 kobo fee from wallet:764
wallet balance now: 6689811
1st reversal: posted transaction 83888: 2986911 + 2500 kobo back to wallet:764
wallet balance after: 9679222
2nd reversal: refused: the payout is reversed
wallet balance after: 9679222
reversal of failed payout 85: refused: the payout is failed
reversals recorded for payout 4: 1
accounts by type (debit-positive kobo): {'asset': 17358041800, 'equity': -5000000000, 'expense': 110590267, 'income': -221779821, 'liability': -12246852246}
settlement_bank in ledger 17,192,633,500 kobo; on the statement 17,192,741,324 kobo
6 skipped: no answers/breaks.csv beside the database (looked for .../labs/finance/work/answers/breaks.csv)
OK: all invariants holdThe first call posts one transaction and the wallet gains 2,986,911 + 2,500 = 2,989,411 kobo (6,689,811 + 2,989,411 = 9,679,222). The second call finds the payout already reversed and does nothing, and a failed payout is refused. Invariants 1 to 5 hold. Check 6, the comparison with the bank statement, is skipped because the answer key is not beside the copy (your skipped line names the full path on your machine, where the chapter shows ...). The statement has no NIP RETURN line for your reversal either, because the bank’s side has not happened: finding that gap is the reconciliation chapter’s job.
Set GUARD = False in the script, delete work/copy.sqlite and run it again with the same call sequence, then check.py. The second reversal is now posted: the wallet goes to 12,668,633, which is 9,679,222 + 2,989,411, and the payout has two reversals. The failed payout is also “reversed”, and its reversal credits wallet 1,146 with 382,884 kobo (381,884 + 1,000) that was never taken. check.py prints FAIL with 2. 0 failed transactions have entries; 1 posted ones have none, which catches the failed payout’s changed status, a status with no money behind it, but not the credit. It says nothing about the double return or the credit, because the two reversals each balance and each points at a payout marked reversed. Only a query that groups reversals by their payout finds it: SELECT related_transaction_id, COUNT(*) FROM transactions WHERE kind = 'payout_reversal' GROUP BY 1 HAVING COUNT(*) > 1 returns [(4, 2)]. Add that query to your own checks. The guard stops the money going out twice; the query tells you the day the guard stops working.
Template
# Refund and reversal policy: <product>
Author (PM) · With finance · Signed by <head of operations> and <finance controller> · Date · Review date
## Scope
Covers: <payment types>. Does not cover: <chargebacks, ...>
## State map
| Machine | State | Legal next states | Final? | Refund allowed? |
|---|---|---|---|---|
Unknown / awaiting requery: <how long, who requeries, what exits it>
## Who may refund
| Role | From which states | Up to (kobo and ₦) | Needs approval above |
|---|---|---|---|
The bound: <captured minus all refunds requested, pending ones included>
## Preventing partial and duplicate refunds
<Reserve when asked. Key: <order id + request id>. Refuse above the bound in the same write.>
## What each person sees
| State | Customer sees | Support sees | Next action and owner |
|---|---|---|---|
## Exceptions
| Case | Who approves | Evidence recorded | Time limit |
|---|---|---|---|
## How this could be wrong
<One way, and what would show it>
## Decision needed
<From whom, by when> WORKED EXAMPLE
At Lumora Mobile, the product manager for airtime writes this policy with Garba. The head of operations and the finance controller sign it, and Ifeoluwa checks the state map against the order service. Dated 20 November 2026, review in six months.
Scope. Card purchases of airtime in the app. Chargebacks are not covered.
State map. The charge is pending, success or failed, as the provider reports it. Only pending moves, once, to success or failed. The vend is requested, delivered, failed or unknown. A refund is pending, then processed, and is allowed only from a charge in success.
Who may refund. The bound is the ₦2,000 captured minus every refund already requested. In the lab a ₦800 refund (80,000 kobo) was pending and the charge already showed 80,000 refunded, so a request for 150,000 kobo was refused: only 120,000 was left. Assumption for the signatories to set: an agent may refund up to ₦2,000 per order, a finance operations lead above that.
Duplicates. The amount is reserved when requested, keyed on order and request id, and refused above the bound in the same write.
What people see. Vend unknown: the customer sees “We are checking your airtime”, support sees the charge and the vend side by side. No refund until the platform confirms failure.
Exceptions. A refund on a pending charge is not allowed. Anything else goes to Garba, with the evidence recorded.
Money. In the lab’s day, four captures of ₦2,000 and ₦2,000 of refunds gave a gross of ₦8,000, a fee of ₦80 and a net of ₦5,920. The mock’s fee was not reduced by the refunds, so there each refund cost its amount and the fee on it. Check Lumora’s own contract.
How this could be wrong. If late deliveries after a timeout are common, the unknown wait is too short. A count of orders refunded and then delivered would show it.
Decision needed. Signatures on the agent limit and the exception route, from both signatories, before the next sprint starts.
Now you
A month on, Ojaline’s support team refunds buyers from a screen. Cards are captured when a parcel is dispatched from the warehouse. Last week two agents each refunded part of the same ₦2,000 order, and the finance team could not say which of them was allowed to. You are the product manager. Write the refund and reversal policy for card orders with Ojaline’s finance lead.
Use the lab’s step 2 output: the 400 not_refundable on a declined or pending charge, the 80,000 refund that showed at once, the 150,000 refused because 120,000 was left, and the settlement line (gross 800,000, fee 8,000, refunds 200,000, net 592,000). State your own refund limits as assumptions. Say what you cannot see, such as whether the buyer’s bank has already opened a dispute.
Your reader is Ojaline’s head of operations and its finance controller. It supports their decision to sign the limits and the exception route.
Self-check
Lumora's app charged ₦2,000 by card for airtime, the charge shows success at the provider, and the call to the recharge platform timed out. Ifeoluwa can change the app and the order service this sprint. Garba wants every unpaid-for order refunded automatically, but a few of the timed-out vends do turn out to have reached the phone. What should the order service do with a captured charge whose airtime status is unknown?
- DOC Regulation on Instant (Inter-Bank) Electronic Funds Transfer Services in Nigeria (CBN, 2018) Central Bank of Nigeria, 2018
The CBN's own text for instant transfers. Read the provisions on credit within 60 seconds, failed transactions and erroneous transfers, and check the figures the chapter took from search summaries. Skip the sections on licensing. Press coverage of the circular differs on the reversal window, so trust only the text.
- DOC Guidelines on Operations of Electronic Payment Channels in Nigeria (CBN, 2020) Central Bank of Nigeria, 2020
Read the sections on POS, mobile POS and web acceptance for how disputed or failed transactions are handled and the timelines for them. Summaries of the guidelines and of the CBN's press release on them give different figures for POS and web refunds, so read the text. A CBN draft of October 2025 would supersede its ATM provisions, so check the current status.
- DOC Press release on payment channels (CBN, 2020) Central Bank of Nigeria, 2020
The CBN's June 2020 announcement of the revised timelines for failed ATM, POS and web transactions. Read it next to the guidelines themselves, because search summaries of the two give different figures for POS and web refunds. Short, so read all of it.
- DOC CBN Consumer Protection Regulations (2019) Central Bank of Nigeria, 2019
The CBN's rules on complaints handling and redress. Read the complaints sections for who must acknowledge, respond and resolve, and in what time. Secondary sources disagree on the resolution window, so read the text. A revised draft was issued for comment in early 2024; check whether it was adopted.
- DOC The PaymentIntent lifecycle (Stripe documentation) Stripe, 2026
One provider's payment lifecycle, with the statuses and which moves are allowed. Read it to see a larger machine than the mock's, with the same ideas of waiting states and final ones. It is a vendor's design, so treat the names as an example, not a standard.
- DOC Payment status updates (Stripe documentation) Stripe, 2026
How a provider tells you the state changed: webhooks, and when to fetch the object yourself. Read it alongside the chapter's rule that events are hints and the verification call is the fact. Skip the front-end sections.
- DOC Refund and cancel payments (Stripe documentation) Stripe, 2026
A vendor's refund rules: partial refunds, refund statuses and what happens to fees. Read it for the shape of a refund as its own object. The fee treatment is that vendor's pricing, not a rule, so check your own provider's contract.
All companies and people in these examples are fictional. Any resemblance to a real business or person is unintended.