Notify your app
By the end of this track you can write a small service that charges, stores every event and notifies your app.
0/6 finished
Step 1
The idea
When a payment becomes final, POST it to your app's webhook URL, signed with HMAC-SHA256 over "<timestamp>.<body>", and retry with backoff. Your app rejects signatures older than five minutes.
Step 2
How it works
The signature
Sign "<timestamp>.<body>" with a secret shared with your app, using HMAC-SHA256. Send the timestamp and signature as headers.
import hmac, hashlib, json, timebody = json.dumps(event, separators=(",", ":"))ts = str(int(time.time()))sig = hmac.new(SECRET, f"{ts}.{body}".encode(), hashlib.sha256).hexdigest()headers = {"X-Timestamp": ts, "X-Signature": sig}The app's side
Recompute the signature, compare with hmac.compare_digest, and reject anything older than five minutes so a captured request can't be replayed.
Retries
If the app doesn't answer 2xx, retry after 1, 2, 4, 8… minutes. Include the payment ID so the app can ignore duplicates, just as you did with Daraja's.
Step 3
Common mistakes
- Comparing signatures with ==, which leaks timing.
- Signing a re-serialised body instead of the bytes you send.
Go deeper
What should your app do with a tampered body or an old timestamp?
Answer in your own words first.
Show the answerHide the answer
Reject it.