WORKINGCHAPTER 08

Integrating a payment provider: charges, verification, webhooks

The provider knows whether the money arrived. Your job is to ask it, listen to it, and never take anyone else's word for it

50 MINPAYMENTSUPDATED 2026-11-14
PREDICT

Tallowmere's handler receives a signed charge.success webhook for order TALLOW-1042, ₦18,500, and credits the customer's wallet. Two seconds later the same event arrives again, with the same event id and a valid signature. What should the handler do?

An integration with a payment provider is four conversations, and each has a different trust level. Most of the bugs in a first integration come from treating one conversation as if it were another.

The four conversations

You meet the same four in every provider, under different names. The names in this chapter are the mock provider’s, from the lab. The shapes carry over.

Conversation Who starts it What it tells you How far to trust it
The charge call (POST /charges) Your server The provider’s immediate answer: success, failed or pending Good when it arrives. It may never arrive: the charge can succeed and the response be lost
The browser’s return The customer’s browser Whatever is in the address the customer’s browser lands on Not at all. The customer controls it. Use it only to show a “we are checking” page
The webhook The provider’s server, to a URL you gave it An event: something changed on a charge Only after you check the signature, and only as a prompt to look
The verification call (GET /charges/{reference}) Your server The charge’s state and amount right now, from the provider’s own record The best evidence you can get. It is the provider speaking, on a connection you opened

The rule that follows is short. Money state comes from the provider’s servers and nowhere else, and you confirm it by asking. The charge response and the webhook are both fast paths. The verification call is the check that lets you act on either.

A card payment, as the previous chapter showed, goes through authorisation, capture, clearing and settlement. A provider hides most of that behind one word, success, which in the mock means authorised and captured. Nothing in this chapter changes the fact that cash arrives a day later: crediting a customer’s wallet or releasing an order on success means you accept the provider’s claim on the money, as the earlier chapter’s card_clearing account records it.

Tallowmere’s serverPayment provider1 POST /charges (reference = order id, amount in kobo)pending, success, or an answer that never arrives2 signed event: charge.success (can arrive twice)3 check the signature on the raw bytes4 GET /charges/{reference}status and amount, from the provider’s record5 compare with the order, then credit once per referenceThe browser’s return is not in this picture: it decides nothing.

Creating a charge

A charge request carries four things that matter: who is paying, how much, a reference, and the card or other instrument. In the lab, the body is reference, amount_kobo, customer_ref and card_number, sent to POST /charges with the secret key in an Authorization: Bearer header.

Three habits make the rest of the integration possible.

Choose the reference yourself, and create the order first. The reference is how every later message names this payment. If the provider invents it, a lost response leaves you with an order and no way to ask about it. If you choose it, derived from your own order id, you can always ask the provider “what happened to TALLOW-1042?”. The mock returns 409 for a reused reference, which protects you from creating two charges for one reference. It does not protect you from creating two references for one order, which is a different bug, taught in the next chapter, Idempotency and moving money exactly once.

Send the amount as integer kobo. ₦18,500 is 1850000. The mock refuses anything that is not an integer of at least 10,000 kobo. The money chapter covers why floats never touch money. In an integration the practical point is that the amount you sent, the amount in the webhook and the amount in the verification must all be compared as integers.

Read three outcomes, not two. A charge is success, failed or pending. Test card 0003 returns pending and, after five seconds in the lab, succeeds. Test card 0004 goes pending and then fails. Pending means the provider is waiting for something, such as the customer’s one-time password. Code that treats “not success” as failure cancels orders that were about to be paid.

And a fourth thing, which the lab makes you live with. Test card 0005 charges the card and then answers with an HTTP 500. The money is taken, the response says error. If your order flow decides from the response alone, it records a failed order for a customer who has paid. The charge, not the response, is the fact.

Webhooks

A webhook is an HTTP request that the provider makes to your server when something happens: a charge succeeds, fails, or is refunded. You give the provider a URL. It sends a POST with a JSON body describing an event, and it keeps sending until you answer with a 2xx status.

In the lab, a webhook carries these headers:

Header What it holds
X-Mock-Signature The hex HMAC-SHA512 of the raw body, keyed with the secret key
X-Mock-Event-Id The event’s id, such as evt_75454f28a44d4936. The same event has the same id every time
X-Mock-Attempt Which delivery attempt this is, starting at 1

The event types are charge.success, charge.failed and refund.processed. The body has an id, a type, a created_at and the data of the charge.

Four properties of delivery shape every handler. They are all visible in the lab.

It is a push, so it can be late. The mock waits half a second before the first attempt. A real provider’s delay is not yours to set. Your order flow must be happy to see the webhook arrive before, after or long after the customer’s browser returns.

It is at least once, so it repeats. If your server answers with anything other than 2xx, or does not answer, the provider sends the event again. The mock retries after 2 s, then 4 s, 8 s and so on, for up to six attempts. A provider may also send a delivery twice when it did receive your answer. Real providers publish their own schedules, and they differ: Paystack’s webhook page, as search results summarised it, says live-mode failures are retried every three minutes for four tries and then hourly for 72 hours, and test-mode failures hourly for ten hours; an older version of the docs gives a different test-mode windowas of 2026-11. That is a vendor’s claim, read from a search summary, not from the page itself. The lesson is not the figure but the shape: retries last hours, so an outage on your side does not lose events, and a duplicate can arrive long after the first delivery.

It can arrive out of order. Event 2 may reach you before event 1 for the same charge. A handler that overwrites the order’s state with whatever arrives last can move an order from paid back to pending. Make states move one way, and when in doubt, ask the provider.

It can be dropped. The mock’s webhook_drop_rate loses attempts in transit, and a provider’s retries stop eventually. A system that only ever listens will, one day, miss an event. This is why the verification call exists as more than a safety check: it is also how you find charges whose webhooks never came. A reconciliation job, the subject of a later chapter, does it at scale.

The webhook delivery lesson lets you replay these failures against a handler before you write your own.

▶ SIMULATION
PAYMENT PROVIDER · outbox
evt_1: not sent yet
evt_2: not sent yet
GET /charges/ch_1 → none
OWOLEAF RECEIVER · up
Zainab's wallet = ₦5,000
ch_1 here: none
seen ids: —
—
ATTACKER
waiting
✓ only events the provider signed move money✓ each event id moves money at most once✓ ch_1 only moves none → succeeded → refunded✓ Zainab's wallet never below ₦0
SCHEDULE
01[PROVIDER]PROVIDER: charge.succeeded evt_1 (ch_1, ₦50,000) → 503, receiver down
02[PROVIDER]PROVIDER: refund.succeeded evt_2 (ch_1) → 503, receiver down
03[OWOLEAF]OWOLEAF: receiver back up, an hour later
04[PROVIDER]PROVIDER: retry: refund.succeeded evt_2 arrives first
05[PROVIDER]PROVIDER: retry: charge.succeeded evt_1
06[PROVIDER]PROVIDER: evt_1 again: its 200 did not reach the provider in time
07[ATTACKER]ATTACKER: POST charge.succeeded ch_9, ₦200,000, no valid signature
Start of naive receiver scenario. 7 steps.
app.post('/webhooks/provider', async (req, res) => {
  const e = req.body;                    // trusts whatever JSON arrives
  if (e.type === 'charge.succeeded') await wallet.credit(e.charge, e.amount);
  if (e.type === 'refund.succeeded') await wallet.debit(e.charge, e.amount);
  await slowAccountingSync(e);           // provider times out, retries
  res.sendStatus(200);
});

Watch the invariant strip. The naive receiver breaks on the duplicate, the out-of-order refund and the forged event. The fix that holds verifies, dedupes and then refetches the charge from the provider. The sim dedupes by event id. The lab below keys on the charge reference, which also covers one charge described by several events.

Verifying a webhook’s signature

Your webhook URL is a public address. Anyone who learns it can POST a body that looks like charge.success. The signature is how you tell the provider’s requests from everyone else’s.

A signature scheme here is an HMAC, short for hash-based message authentication code, defined in RFC 2104, an Informational document from February 1997 by Krawczyk, Bellare and Canetti, which describes a mechanism for checking with a shared secret key that exchanged information has not been alteredas of 2026-11. The provider computes HMAC(secret, body) and sends the result in a header. You compute the same thing over the bytes you received, with the same secret, and compare. If you get the same value, the body is unchanged and the sender held the secret. The hashing lesson shows why a plain hash would not do: anyone can compute a hash, and only a key holder can compute an HMAC.

Three details cause most failed verifications.

Sign the raw bytes. Read Content-Length bytes from the request and compute the HMAC on them before parsing. If you parse the JSON and print it again, spacing, key order and number formats can change, and one different byte gives a different HMAC. Vendors’ pages repeat this warning. Stripe’s webhook page, as search results summarised it, tells the receiver to verify with the raw payload, the Stripe-Signature header and the endpoint’s signing secret, to return a 2xx quickly before heavier work, and warns that any manipulation of the raw body causes verification to failas of 2026-11. Providers differ in details, so test your verifier against the provider you use and do not assume.

Match the algorithm. The mock uses HMAC-SHA512 and a hex digest. Paystack’s page is summarised as describing an x-paystack-signature header holding an HMAC SHA512 of the payload keyed with the secret keyas of 2026-11, while Stripe’s header is a different shape, carrying a timestamp and a signatureas of 2026-11. A verifier written for one provider fails every delivery from another, and fails quietly: you see 401s and no explanation. Check the provider’s docs for the algorithm, the encoding and the header name.

Compare in constant time. Use hmac.compare_digest, not ==. A plain comparison stops at the first different character, and the time it takes can leak how many leading characters were right. The lab’s receiver uses compare_digest.

Now name what a valid signature does not prove. It does not say the event is new: a captured body and its signature can be sent again and will verify. It does not say you have not seen it before. It does not say the amount matches your order. Some schemes add a timestamp to the signed content so that you can reject old deliveries: the Standard Webhooks specification, as search results summarised it, defines three headers (a message id, a timestamp and a signature), with HMAC-SHA256 as the default scheme and the option of an asymmetric signatureas of 2026-11. The mock has no timestamp, so in the lab you will see an old body replayed and accepted. That is what the handler’s own checks are for.

Verification: asking before you credit

After the signature check, do not credit from the body. Call GET /charges/{reference}, using the reference from the event, and read the provider’s record. Then compare, as integers, three things with your own order: the charge’s status is success, its amount_kobo equals the order’s amount, and the reference belongs to an order you created and have not yet marked paid.

This costs one HTTP call per event, and it buys four protections.

  1. A stale or out-of-order event cannot move money. You read the current state, not the state at the time of the event.
  2. A leaked or guessed signing key does not let someone invent payments, because a made-up event names a charge the provider has no record of.
  3. A bug in the event’s body, such as a different amount, is caught before it reaches the ledger.
  4. Your code does not depend on the exact shape of the event payload, which providers change.

One provider’s docs describe this step. Paystack’s Verify Payments page, as search results summarised it, says to read the transaction’s status from inside the data object of the verification response and not from the top-level status, which reports only whether the API call itself workedas of 2026-11. Guarding against giving value twice is the next section’s subject.

The mock’s verification also answers for the 10,680 card fundings in the generated ledger, found by their external_ref, which is useful when you want to see what an old charge looks like. For a charge made through the mock, it returns the live record.

Crediting once

Everything so far can run twice. The signature check can pass twice, and the verification will say success twice. The last step, the credit, must be the step that is safe to repeat.

The reliable way is to let the database say no. In the lab, the credit is one statement:

INSERT OR IGNORE INTO credits (reference, customer_ref, amount_kobo) VALUES (?, ?, ?)

credits.reference is a primary key. The first insert adds a row and the statement reports one row changed. Every later insert for the same reference changes nothing. The handler reads the count: one means “credit the wallet”, zero means “already done, answer 200”. There is no separate “have I seen this?” query, which would have a gap between the question and the write, and two deliveries arriving together could both get the answer “no”. This is the same single-step discipline that the lessons on check-then-act and idempotency show failing without it.

The key is the charge’s reference, not the event id. The event id is useful, and the lab logs it, but a provider can describe one charge with several events, and your promise to the customer is “one credit per charge”. In a real wallet, the insert and the ledger posting, from module 1’s double-entry chapter, happen in one database transaction, so that a crash cannot leave a credit row without its entries or entries without a credit row.

Answer 2xx quickly. The provider only needs to know that you have received the event. Do anything slow, such as emailing the customer or telling the dispatch desk, after you answer, from a queue. And answer 2xx for events you ignore: a 401 for an event type you do not handle makes the provider retry something you will never use.

Where it goes wrong

Name the failures first. Each looks like a working integration until the day it does not.

Trusting the redirect. Tallowmere’s first version. Use the browser’s return to show a page that says “checking your payment”, and let the verified webhook, or a verification call made from the server, mark the order paid.

Deciding from the charge response alone. Card 0005 is the case: charged, answered 500. A flow that cancels the order on a 500 will have taken the money and told the customer it failed. Treat a 500 on a charge as “unknown”: ask the provider by reference before deciding. Retrying the call with a new reference is worse, and the next chapter explains why.

Parsing before verifying. The signature fails for correct bodies, and a developer “fixes” it by disabling the check. Keep the bytes as they arrived.

Comparing with ==, or against the wrong digest. The first leaks timing. The second makes every delivery fail, and the same developer disables the check. Test your verifier with a body you signed yourself, and with a body with one byte changed.

Crediting on a valid signature alone. It proves who sent the bytes. It does not prove that the amount is right, that the charge exists, or that you have not already acted.

Doing the work before answering. If the handler takes longer than the provider’s timeout, the provider retries while you are still working, and two copies of the work run at once. Record the event, answer, then work.

Logging the secret. The webhook secret and the API key are the same string in the mock, and in some providers they are the same key too. Logs, error pages and screenshots that contain it let anyone sign events. Keep it in the environment, rotate it when it may have leaked, and treat a leak as a payment incident. The lab uses a fixed test key; a live key never goes in code.

Having only one path. A webhook that never arrived leaves an order awaiting payment for ever. Alongside the receiver, run a job that looks for orders still awaiting payment after a few minutes and asks the provider about each reference. It is the same verification call, from a clock instead of an event.

LAB Write a webhook receiver, charge test cards, and break it three ways ~45 MIN
YOU NEEDPython 3.9 or later (standard library only)labs/finance with the data generated (python3 generate.py)Three terminalsNo Docker, no packages

You work in labs/finance. Terminal 1 runs the provider. Terminal 2 runs your receiver. Terminal 3 runs the commands. Every script is standard-library Python. The files you write go in a work folder so that the lab’s own files stay clean. The lab’s keys, headers and limits are invented and labelled so.

1. Write the receiver, and start both services. In terminal 3, create the receiver. It is about 40 lines: it reads the raw bytes, checks the signature in constant time, asks the provider about the charge, compares the amount with the order, and credits once.

cd labs/finance
python3 generate.py          # skip if data/finance.sqlite exists
mkdir -p work && cd work
cat > shop.py <<'PY'
import hashlib, hmac, json, sqlite3, urllib.request
from http.server import BaseHTTPRequestHandler, HTTPServer

KEY = b"sk_test_owoleaf_mock"
PROVIDER = "http://127.0.0.1:8101"
db = sqlite3.connect("shop.sqlite", check_same_thread=False, isolation_level=None, timeout=10)
db.executescript("""
CREATE TABLE IF NOT EXISTS orders (reference TEXT PRIMARY KEY, customer_ref TEXT, amount_kobo INTEGER, state TEXT);
CREATE TABLE IF NOT EXISTS deliveries (id INTEGER PRIMARY KEY, event_id TEXT, attempt TEXT, raw BLOB, sig TEXT, verdict TEXT);
CREATE TABLE IF NOT EXISTS credits (reference TEXT PRIMARY KEY, customer_ref TEXT, amount_kobo INTEGER);""")

def provider_says(reference):
    req = urllib.request.Request(f"{PROVIDER}/charges/{reference}", headers={"Authorization": "Bearer " + KEY.decode()})
    try:
        with urllib.request.urlopen(req, timeout=5) as r:
            return json.load(r)["charge"]
    except Exception:
        return None

class Hook(BaseHTTPRequestHandler):
    def do_POST(self):
        raw = self.rfile.read(int(self.headers.get("Content-Length", 0)))   # the exact bytes sent
        sig = self.headers.get("X-Mock-Signature", "")
        good = hmac.compare_digest(hmac.new(KEY, raw, hashlib.sha512).hexdigest(), sig)
        event_id, attempt = self.headers.get("X-Mock-Event-Id", "-"), self.headers.get("X-Mock-Attempt", "-")
        verdict, status = "bad signature", 401
        if good:
            event = json.loads(raw)
            ch = event["data"]
            verdict, status = f"ignored {event['type']}", 200
            if event["type"] == "charge.success":
                order = db.execute("SELECT customer_ref, amount_kobo FROM orders WHERE reference = ?", (ch["reference"],)).fetchone()
                real = provider_says(ch["reference"])
                if not order or not real or real["status"] != "success" or real["amount_kobo"] != order[1]:
                    verdict = "NOT credited: order or provider record does not match"
                elif db.execute("INSERT OR IGNORE INTO credits VALUES (?,?,?)", (ch["reference"], order[0], order[1])).rowcount:
                    db.execute("UPDATE orders SET state = 'paid' WHERE reference = ?", (ch["reference"],))
                    verdict = "credited"
                else:
                    verdict = "already credited"
        db.execute("INSERT INTO deliveries (event_id, attempt, raw, sig, verdict) VALUES (?,?,?,?,?)", (event_id, attempt, raw, sig, verdict))
        print(f"{event_id} attempt {attempt}: {verdict}", flush=True)
        self.send_response(status); self.send_header("Content-Length", "0"); self.end_headers()

    def log_message(self, *args):
        pass

HTTPServer(("127.0.0.1", 9000), Hook).serve_forever()
PY

Terminal 1, from labs/finance: start the provider with its webhooks pointed at your receiver.

python3 mock_provider.py --fresh --quiet --webhook-url http://127.0.0.1:9000/hook

Terminal 2, from labs/finance/work: start the receiver.

rm -f shop.sqlite
python3 shop.py

Terminal 1 prints mock_provider on http://127.0.0.1:8101 secret sk_test_owoleaf_mock webhooks -> http://127.0.0.1:9000/hook. Terminal 2 prints nothing and waits. Each delivery is logged in deliveries with its raw bytes, so you can inspect or replay it later.

2. Place orders, charge two test cards, and watch the order become paid. This script creates the order first, as the chapter said, then charges it. For one order it prints the charge call’s answer and then watches the order’s state until the webhook marks it paid. Run it in terminal 3.

cat > order.py <<'PY'
import json, secrets, sqlite3, sys, time, urllib.error, urllib.request

KEY = {"Authorization": "Bearer sk_test_owoleaf_mock", "Content-Type": "application/json"}
db = sqlite3.connect("shop.sqlite", timeout=10)
last4, count = sys.argv[1], int(sys.argv[2]) if len(sys.argv) > 2 else 1

def place_order(last4):
    ref = "TALLOW-" + secrets.token_hex(4)
    db.execute("INSERT INTO orders VALUES (?,?,?, 'awaiting_payment')", (ref, "C0000042", 1_850_000))
    db.commit()                                    # the order exists before the charge does
    body = json.dumps({"reference": ref, "amount_kobo": 1_850_000, "customer_ref": "C0000042",
                       "card_number": "411111111111" + last4}).encode()
    try:
        with urllib.request.urlopen(urllib.request.Request("http://127.0.0.1:8101/charges", body, KEY, method="POST")) as r:
            answer = f"HTTP {r.status}, charge {json.load(r)['charge']['status']}"
    except urllib.error.HTTPError as e:
        answer = f"HTTP {e.code}, {json.load(e)['error']}"
    return ref, answer

orders = [place_order(last4) for _ in range(count)]
if count == 1:
    ref, answer = orders[0]
    print(f"charge call: {answer}")
    seen, end = None, time.time() + 20
    while time.time() < end:
        state = db.execute("SELECT state FROM orders WHERE reference = ?", (ref,)).fetchone()[0]
        if state != seen:
            print(f"+{20 - (end - time.time()):4.1f}s order is {state}")
            seen = state
        if state == "paid":
            break
        time.sleep(0.2)
else:
    print(f"placed {count} orders")
PY
python3 order.py 0003
python3 order.py 0005
charge call: HTTP 200, charge pending
+ 0.0s order is awaiting_payment
+ 5.8s order is paid
charge call: HTTP 500, internal_error
+ 0.0s order is awaiting_payment
+ 0.6s order is paid

Terminal 2 shows one line for each (your event ids differ):

evt_75454f28a44d4936 attempt 1: credited
evt_4c84ffd68ac149ac attempt 1: credited

Card 0003 answers pending, and the order stays unpaid for the provider’s five seconds, then the charge.success webhook arrives, your handler asks the provider, and the order is paid. Card 0005 is the lost response: the call answered with a 500 and the customer was charged all the same. The order still became paid, 0.6 seconds later, because the webhook carried the fact the response did not. A shop that decided from the response alone would have cancelled it.

3. Make the provider repeat itself. Set the duplicate rate to 0.5 at run time, place ten orders on the always-succeeds card, wait for the deliveries, then count what your handler saw and what it did. Run this in terminal 3.

cat > report.py <<'PY'
import sqlite3

db = sqlite3.connect("shop.sqlite")
q = lambda sql: db.execute(sql).fetchall()
print("deliveries by verdict:", dict(q("SELECT verdict, COUNT(*) FROM deliveries GROUP BY verdict")))
print("distinct events:", q("SELECT COUNT(DISTINCT event_id) FROM deliveries")[0][0])
print("orders by state:", dict(q("SELECT state, COUNT(*) FROM orders GROUP BY state")))
n, total = q("SELECT COUNT(*), SUM(amount_kobo) FROM credits")[0]
print(f"wallet credits: {n}, {total} kobo")
PY
curl -s -X POST localhost:8101/admin/faults -d '{"webhook_dup_rate": 0.5}' > /dev/null
python3 order.py 0001 10
sleep 9
python3 report.py
placed 10 orders
deliveries by verdict: {'already credited': 9, 'credited': 12}
distinct events: 12
orders by state: {'paid': 12}
wallet credits: 12, 22200000 kobo

The 12 orders are the two from step 2 and these ten. They produced 12 distinct events and 21 deliveries, so nine deliveries were repeats, and your handler answered every one with 200 and credited nothing for them. The duplicate count is random: yours will differ, and a repeat can itself be repeated (in the run quoted here one event arrived three times). What does not vary is the last two lines: one credit per order, 12 × 1,850,000 = 22,200,000 kobo, ₦222,000.

4. Tamper with a body, replay a body, and forge an event. This script takes one real delivery your receiver saved, and sends three things to the receiver: the original, replayed; the same body with one byte changed and the old signature; and a made-up charge.success for an order that was never charged, signed correctly with the key, as someone who had leaked it would.

cat > tamper.py <<'PY'
import hashlib, hmac, json, sqlite3, urllib.error, urllib.request

KEY = b"sk_test_owoleaf_mock"
db = sqlite3.connect("shop.sqlite", timeout=10)

def post(raw, sig, label):
    req = urllib.request.Request("http://127.0.0.1:9000/hook", raw, {"X-Mock-Signature": sig, "X-Mock-Event-Id": "evt_by_hand", "X-Mock-Attempt": "1"}, method="POST")
    try:
        with urllib.request.urlopen(req) as r:
            code = r.status
    except urllib.error.HTTPError as e:
        code = e.code
    print(f"{label}: receiver answered {code}")

raw, sig = db.execute("SELECT raw, sig FROM deliveries WHERE verdict = 'credited' ORDER BY id LIMIT 1").fetchone()
post(raw, sig, "1. the original body, replayed")
i = raw.index(b"1850000")
flipped = raw[:i] + b"9" + raw[i + 1:]               # 1850000 becomes 9850000: one byte
post(flipped, sig, "2. one byte changed, old signature")
forged = json.dumps({"id": "evt_forged", "type": "charge.success", "data": {"reference": "TALLOW-FORGED1", "amount_kobo": 1850000}}).encode()
db.execute("INSERT INTO orders VALUES ('TALLOW-FORGED1', 'C0000042', 1850000, 'awaiting_payment')")
db.commit()
post(forged, hmac.new(KEY, forged, hashlib.sha512).hexdigest(), "3. a made-up event, correctly signed")
print("order TALLOW-FORGED1 is", db.execute("SELECT state FROM orders WHERE reference = 'TALLOW-FORGED1'").fetchone()[0])
PY
python3 tamper.py
python3 report.py
1. the original body, replayed: receiver answered 200
2. one byte changed, old signature: receiver answered 401
3. a made-up event, correctly signed: receiver answered 200
order TALLOW-FORGED1 is awaiting_payment
deliveries by verdict: {'NOT credited: order or provider record does not match': 1, 'already credited': 10, 'bad signature': 1, 'credited': 12}
distinct events: 13
orders by state: {'awaiting_payment': 1, 'paid': 12}
wallet credits: 12, 22200000 kobo

Three lessons in four lines. The replay verified, because a valid body keeps its signature, and was harmless only because of the uniqueness rule: it counts under already credited. The one-byte change failed the signature and got a 401, so the receiver never parsed it. The forged event passed the signature, since it was signed with the right key, and the receiver still did not credit it: the provider’s record for TALLOW-FORGED1 does not exist, so the verification found nothing. The credits are still 12 and 22,200,000 kobo.

Stop the receiver with Ctrl-C in terminal 2, and set the duplicate rate back to 0 with curl -s -X POST localhost:8101/admin/faults -d '{"webhook_dup_rate": 0}' > /dev/null. In terminal 3 run python3 order.py 0001. It charges a card whose webhook has nowhere to go. Count to ten, then start python3 shop.py again in terminal 2 (without deleting shop.sqlite). Then run this to see how the provider tried:

python3 - <<'PY'
import json, urllib.request
req = urllib.request.Request("http://127.0.0.1:8101/webhooks/deliveries", headers={"Authorization": "Bearer sk_test_owoleaf_mock"})
d = json.load(urllib.request.urlopen(req))["deliveries"]
last = d[-1]["event_id"]
for x in d:
    if x["event_id"] == last:
        print(x["attempt"], x["sent_at"][11:19], x["http_status"], x["outcome"])
PY

Expected, with your own clock times: attempts 1, 2 and 3 failed with error: URLError and no HTTP status, two, four and eight seconds apart, and attempt 4, about fifteen seconds after the charge, was delivered with status 200. In the quoted run:

1 11:08:13 None error: URLError
2 11:08:15 None error: URLError
3 11:08:19 None error: URLError
4 11:08:27 200 delivered

The order script printed +14.8s order is paid, and your receiver logged attempt 4: credited. Nothing was lost, because the provider kept trying. Now think about the handler’s own failure. In shop.py, provider_says returns None when the provider cannot be reached, and the verdict is NOT credited, yet the receiver still answers 200, so the provider stops retrying. Is that right for an event you could not verify? Decide, and say why. (The answer the chapter favours: a 5xx, so the provider tries again, and the timed job as a second net.)

ARTEFACT Write the go-live readiness checklist ~45 MIN
YOU PRODUCEGo-live readiness checklist for a payment-provider integration

Template

# Go-live readiness: <provider> integration, <company>
Written by <engineer> · Signs: <head of payments> · Date · Launch date <date>

## Verdict
<Ready / ready with named exceptions / not ready>, because <one sentence>.

## Checklist
| Area | What must be true | Evidence (link, output or screenshot) | Status | Owner, date |
|---|---|---|---|---|
| Keys and environments | Live key only in the environment, never in code or logs; test and live kept apart; rotation known | | | |
| Webhook signature | Verified on the raw bytes, in constant time; tampered body refused | | | |
| Verify before value | Status and amount in kobo checked with the provider before any credit | | | |
| Retries and idempotency | One credit per reference under repeats; provider failures lead to a retry | | | |
| Refunds and disputes | A refund event and a dispute notice reach a named person and a ledger entry | | | |
| Monitoring and alerts | An alert for each failure that costs money, with who is paged | | | |
| Rollback | How to switch off, what happens to payments in flight, who decides | | | |

## What this checklist cannot see
<Providers, cards, volumes and failures not tested>

## Open items and the decision
<Each open item, its owner and date; what you ask the signer to decide>
WORKED EXAMPLE

At a company with a payments team, an engineer writes this checklist and the head of payments signs it before launch. Tallowmere has no such role, so Ibiere writes it and the person who owns the shop’s money signs.

Go-live readiness: card integration, Tallowmere. Written by Ibiere · Signs: the owner of the shop’s money · 20 November 2026 · Launch 4 December

Verdict: ready with named exceptions. Hold the launch until refunds and alerts exist. The receiver passed every lab test.

Area Evidence Status Owner, date
Keys and environments Lab uses the public test key sk_test_owoleaf_mock; no live key issued yet Open Ibiere, 27 Nov
Webhook signature tamper.py line 2: one byte changed, old signature, receiver answered 401 Done Ibiere
Verify before value tamper.py line 3: signed made-up event answered 200, order TALLOW-FORGED1 stayed awaiting_payment. Card 0005: charge call HTTP 500, order still paid 0.6 s later Done Ibiere
Retries and idempotency Step 3: 12 events, 21 deliveries, 12 credits, 22,200,000 kobo (₦222,000). But the receiver answers 200 when provider_says returns None Open: change to 5xx Ibiere, 27 Nov
Refunds and disputes Lab has a refund.processed event; I ran no refund Open, blocks launch Ibiere, 2 Dec
Monitoring and alerts None written Open, blocks launch Ibiere, 2 Dec
Rollback Stopping the receiver lost nothing: in the break step the order was paid 14.8 s after the charge, on attempt 4. Nobody is yet named to flip it Open Signer to name, 27 Nov

What this cannot see: one mock provider, ten orders at a time, no real card networks. A real provider’s retry schedule is in its docs, which I have not read. The rollback line is wrong if a real provider stops retrying before we are back.

Decision for the signer: approve launch on 4 December if keys, refunds and alerts are closed by 2 December; otherwise move the date.

Now you

A month on, Owoleaf, at 60 people, will accept card top-ups through a new payment-provider integration, and launch is next Friday. You are the engineer. Run this chapter’s lab on your own copy and use what it prints: the credits and their total (the number of duplicate deliveries differs from run to run), the 401 on the changed byte, the forged event that was not credited, and the 500 on card 0005 that still ended paid. Each top-up in the lab is ₦18,500. The card processor pays Owoleaf one business day after a top-up (T+1), and chargeback debits arrive in the settlement file it sends. Payments ops chases the processor and finance books or disputes each row. Assume the on-call engineer can switch top-ups off with a feature flag in about two minutes. Nobody has yet tested a refund, a dispute notice or an alert. Write the checklist, with a verdict. The head of payments will read it and decide whether to launch on Friday, launch to a share of customers, or hold.

Self-check

DECIDE

Ibiere has a week to finish Tallowmere's checkout. Onyinye's support desk needs orders marked paid within seconds, because riders are waiting at the Ibadan counter. The provider's webhooks usually arrive in under two seconds but sometimes take minutes, and twice in testing a webhook never came. What does Ibiere make the trigger for 'paid'?

READING
  1. DOC
    Webhooks (Paystack) Paystack, 2026

    A Nigerian provider's own description of events, the signature header and retries. Read it for how one real provider names the pieces you built in the lab. It is a vendor's design, and its retry schedule is the vendor's claim, so compare it with the mock's.

  2. DOC
    Verify Payments (Paystack) Paystack, 2026

    The vendor's own description of verifying a transaction, with the warning about reading the status from the right place in the response. Read it beside the chapter's verification section.

  3. DOC
    Receive Stripe events in your webhook endpoint Stripe, 2026

    A second vendor's version of the same job, with a different header and a timestamp in the signature. Read the sections on verifying signatures and on quick 2xx responses. Skip the dashboard steps, which change often.

  4. DOC
    Standard Webhooks specification Standard Webhooks project, 2026

    An open specification for the headers and signing of webhooks, with a message id and timestamp that let a receiver reject replays and repeats. Read it for what the lab's mock leaves out. Check whether your provider follows it.

  5. DOC
    RFC 2104: HMAC: Keyed-Hashing for Message Authentication Krawczyk, Bellare and Canetti, 1997

    The definition of the HMAC every webhook scheme here relies on. Read the introduction and the section on keys. Skip the implementation notes unless you write a hash function; use your language's library.

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

RECALL CARDS Tap to flip. They join your review deck when you mark the lesson complete.
NEXT: Idempotency and moving money exactly once →