Sub topic 11
Webhooks and asynchronous status updates
This chapter assumes you know the payment state machine, idempotency keys, and the transactional outbox from earlier chapters. It also assumes basic HTTP and SQL. It covers how a payment system receives status changes from PSPs and how it reports them to merchants.
Why status arrives asynchronously
A synchronous API response often cannot say whether a payment succeeded. The cause may be a timeout, a 3-D Secure challenge the customer must finish, a bank that takes minutes to answer, or a bank transfer that settles days later. In these cases the PSP returns a pending status and reports the outcome later.
A webhook is an HTTP request that one system sends to a URL registered by another system when an event happens. A payment platform uses webhooks in two directions:
- Inbound: the PSP calls your service to report
authorized,captured,failed,refunded, ordispute_opened. - Outbound: your service calls the merchant's endpoint to report the same facts about the merchant's payments.
Each direction has the same hazards. The network can drop a delivery, the sender can retry it, two events can arrive in the wrong order, and anyone can send a forged request to a public URL.
Receiving PSP webhooks safely
Handle every inbound request in the same four steps.
- Verify authenticity. PSPs sign the body with a shared secret, usually with HMAC-SHA256. Verify the signature against the raw bytes you received, not a re-serialized JSON object. Compare with a constant-time function, and reject old timestamps to limit replay.
- Deduplicate. Store each event under the PSP's event ID.
- Acknowledge fast. Return
2xxonce the event is durably stored. Do the real work afterward. PSPs treat slow responses as failures and retry, which multiplies the load. - Process asynchronously. A worker applies the event to the payment.
import hashlib
import hmac
import time
def verify_signature(secret: bytes, timestamp: str, body: bytes,
signature: str, tolerance_seconds: int = 300) -> bool:
"""Check an HMAC-SHA256 signature over '<timestamp>.<raw body>'."""
try:
sent_at = int(timestamp)
except ValueError:
return False
if abs(time.time() - sent_at) > tolerance_seconds:
return False
signed_payload = timestamp.encode() + b"." + body
expected = hmac.new(secret, signed_payload, hashlib.sha256).hexdigest()
return hmac.compare_digest(expected, signature)
secret = b"whsec_test"
body = b'{"id":"evt_1","type":"payment.captured"}'
ts = str(int(time.time()))
sig = hmac.new(secret, ts.encode() + b"." + body, hashlib.sha256).hexdigest()
print(verify_signature(secret, ts, body, sig)) # True
print(verify_signature(secret, ts, body + b" ", sig)) # FalseDeduplication uses the same trick as the payment idempotency key. The database decides atomically whether an event is new.
CREATE TABLE webhook_events (
provider TEXT NOT NULL,
event_id TEXT NOT NULL,
payload JSONB NOT NULL,
received_at TIMESTAMPTZ NOT NULL DEFAULT now(),
processed_at TIMESTAMPTZ,
PRIMARY KEY (provider, event_id)
);
INSERT INTO webhook_events (provider, event_id, payload)
VALUES (:provider, :event_id, :payload)
ON CONFLICT (provider, event_id) DO NOTHING
RETURNING event_id;If no row is returned, the event is a duplicate. Still answer 200. An error response would make the PSP keep retrying an event you already have.
Duplicates and out-of-order events
Deduplicating by event ID is not enough. Delivery order is not guaranteed, so payment.captured can arrive before payment.authorized. Your state machine decides what to do with each event:
- Event matches the current state or is behind it. The payment has already moved past it. Mark the event processed and change nothing.
- Event is ahead of the current state. A step is missing. Leave the event unprocessed and retry it after a short delay. The earlier event usually arrives within seconds.
- Event contradicts the current state. For example,
capturedarrives for a voided payment. Do not force the transition. Record the event, raise an alert, and send the payment to reconciliation.
The worker should also lock the payment row, for example with SELECT ... FOR UPDATE, so two events for one payment cannot be applied concurrently.
Webhook payloads can be stale, because the data inside may be older than the PSP's current record. For important transitions, many systems treat the webhook as a hint and fetch the payment from the PSP API before changing state.
Polling as a fallback
Webhooks can be lost after the PSP's retries are exhausted, or because your endpoint was down for hours. Run a scheduled job that finds payments stuck in a non-final state, such as created or authorized longer than expected, and queries the PSP for their real status. Feed the result through the same event-processing path. This job also resolves the timeout case from the retries chapter, where you never learned whether the PSP acted.
Sending webhooks to merchants
Your merchants face the same problems, with you as the sender. Build outbound delivery on the transactional outbox. The payment state change and the outbox row commit in one database transaction. A separate dispatcher reads the outbox and posts to the merchant, so no event is lost and no event describes a change that was rolled back.
Delivery rules:
- Sign every request with a per-merchant secret and include a timestamp, using the scheme shown above.
- Include a stable event ID and tell merchants to deduplicate on it. Delivery is at least once, never exactly once.
- Retry with exponential backoff and jitter over hours or days, as in the retries chapter. Treat any non-
2xxresponse and any timeout as a failure. - Set a short request timeout, such as 5 to 10 seconds, so one slow merchant does not block the dispatcher.
- Isolate merchants. Use per-merchant queues or concurrency limits so a failing endpoint cannot delay everyone else.
- Disable or flag endpoints that fail continuously, notify the merchant, and offer a manual replay.
- Keep payloads thin or versioned. Include the event type and object ID, and let merchants fetch the current object through the API when ordering matters.
Common errors
| Mistake | Consequence | Fix |
|---|---|---|
| Parsing JSON before verifying the signature | Signature fails because re-serialization changes the bytes | Verify against the raw body |
| Doing slow work before returning `200` | PSP times out and retries | Store, acknowledge, process later |
| Returning `4xx` or `5xx` for a duplicate | Endless retries | Return `200` |
| Assuming events arrive in order | Payments stuck or wrongly updated | Check state machine, retry early events |
| No fallback polling | Lost events leave payments pending forever | Scheduled status sync |
| One shared outbound queue | One bad merchant delays all | Per-merchant isolation |
Exercise
Your endpoint receives payment.captured for a payment that your database shows as created. The event ID has not been seen before and the signature is valid. What should the worker do, and what happens if the authorized event never arrives?
Show answer
The event is ahead of the current state, so the worker should not apply it and should not discard it. It leaves the event unprocessed and retries after a short delay, because the authorized event usually arrives soon. If it never arrives, the fallback poll queries the PSP for the payment's real status. The PSP should report captured, and the platform then applies the missing transitions in order. If the retries and the poll still cannot resolve the payment, an alert sends it to reconciliation.
Exercise
Why should the inbound endpoint return 200 for a duplicate event instead of an error?
Show answer
The duplicate means you already stored the event. An error response tells the PSP the delivery failed, so it keeps retrying and adds load without any benefit.