A Payment Flow: Intents, Webhooks, Refunds and Events That Arrive Out of Order
Integrate a card payment flow with a simulated provider: create and confirm a payment, handle decline and extra-authentication outcomes, refund part of it, keep your order state in step using sequence numbers, and prove that event order does not change the result.
In this lesson you will
- Follow the intent, confirm and webhook flow
- Never handle raw card data
- Keep order state correct when events arrive out of order
- Reconcile your records with the provider’s
About 28 minutes
Taking Noor’s first real payment
A payment is the integration where mistakes cost real money, so it is worth being precise about its shape. Modern providers use a payment intent: the shop creates an intent for an amount and a currency, which records the intention to collect that money, with an idempotency key so that a retry cannot create two. The customer’s card details are entered in a form or fields that belong to the provider, and the shop receives only a token that stands for the card. The shop then confirms the intent with the token, and the provider answers with a status: succeeded, failed because the card was declined, or requires_action, when the bank wants extra authentication such as a code. Final results arrive again as webhook events, and the shop treats the events, not the HTTP reply of the confirmation, as the record of what happened.
Never handle raw card numbers in your own servers. Doing so brings your system into the scope of the card industry’s security standard, PCI DSS, with heavy obligations. Using the provider’s hosted fields and tokens keeps card data out of your systems, and check the current PCI requirements with your provider. Events can arrive late, twice and in the wrong order: a refund event may reach you before the payment event, because the two were sent through different paths. The remedy starts with a sequence number on each event for an intent. A tempting rule is to apply an event only if its number is higher than the last one applied, and to ignore older ones, but it silently loses events that arrive late. A sturdier rule keeps every event under its sequence number, ignores a duplicate, and derives the order state by replaying the kept events in sequence order, so that the state is the same whatever the arrival order. That is a property that can be tested by trying every order, and the lesson does.
| Step | Call or event | Result |
|---|---|---|
| 1 | POST /intents (idempotency key) | requires_confirmation |
| 2 | POST /intents/{id}/confirm with a token | succeeded, failed or requires_action |
| 3 | Webhook payment.succeeded | Order becomes paid |
| 4 | POST /refunds | Partial or full refund |
| 5 | Webhook refund.created | Order becomes partially refunded or refunded |
import json, threading, itertools, urllib.request, urllib.error, hmac, hashlib
# ---- the provider (simulated) ----
intents, refunds, events, keys = {}, [], [], {}
def emit(intent_id, kind, **data):
events.append({"id": "evt_%d" % (len(events) + 1), "intent": intent_id, "seq": 1 + sum(1 for e in events if e["intent"] == intent_id), "type": kind, **data})
class Pay:
def create(self, key, amount, cur):
if key in keys: return keys[key]
i = {"id": "pi_%d" % (len(intents) + 1), "amount": amount, "currency": cur, "status": "requires_confirmation", "refunded": 0}
intents[i["id"]] = i; keys[key] = i; return i
def confirm(self, iid, token):
i = intents[iid]
i["status"] = {"tok_ok": "succeeded", "tok_declined": "failed", "tok_3ds": "requires_action"}[token]
if i["status"] == "succeeded": emit(iid, "payment.succeeded", amount=i["amount"])
if i["status"] == "failed": emit(iid, "payment.failed")
return i
def refund(self, iid, amount):
i = intents[iid]
if i["status"] != "succeeded" or i["refunded"] + amount > i["amount"]: return None
i["refunded"] += amount; refunds.append({"intent": iid, "amount": amount}); emit(iid, "refund.created", amount=amount); return i
P = Pay()
# ---- the shop: two ways to keep order state from events ----
class NaiveOrder: # ignores any event older than the last one applied
def __init__(self, amount): self.amount, self.state, self.last_seq, self.refunded = amount, "pending", 0, 0
def apply(self, e):
if e["seq"] <= self.last_seq: return False
self.last_seq = e["seq"]
if e["type"] == "payment.succeeded": self.state = "paid"
elif e["type"] == "refund.created":
self.refunded += e["amount"]; self.state = "refunded" if self.refunded == self.amount else "partially_refunded"
return True
@property
def view(self): return (self.state, self.refunded, self.last_seq)
class Order: # keeps every event by sequence number, derives the state from them in order
def __init__(self, amount): self.amount, self.events = amount, {}
def apply(self, e):
if e["seq"] in self.events: return False # a duplicate delivery
self.events[e["seq"]] = e; return True
@property
def view(self):
state, refunded = "pending", 0
for seq in sorted(self.events):
e = self.events[seq]
if e["type"] == "payment.succeeded": state = "paid"
elif e["type"] == "payment.failed": state = "failed"
elif e["type"] == "refund.created":
refunded += e["amount"]; state = "refunded" if refunded == self.amount else "partially_refunded"
return (state, refunded, max(self.events, default=0))
a = P.create("order-1", 4200, "EUR"); again = P.create("order-1", 4200, "EUR")
print("same idempotency key returns the same intent:", a is again, "| intents on the provider:", len(intents))
print("confirm with tok_ok ->", P.confirm(a["id"], "tok_ok")["status"])
b = P.create("order-2", 1500, "EUR"); print("confirm with tok_declined ->", P.confirm(b["id"], "tok_declined")["status"])
c = P.create("order-3", 900, "EUR"); print("confirm with tok_3ds ->", P.confirm(c["id"], "tok_3ds")["status"], "(the customer must authenticate)")
print("refund 1000 ->", P.refund(a["id"], 1000)["refunded"], "| refund 5000 (too much) ->", P.refund(a["id"], 5000), "| refund on a declined payment ->", P.refund(b["id"], 100))
P.refund(a["id"], 3200)
mine = [e for e in events if e["intent"] == a["id"]]
print("events for the first payment:", [(e["seq"], e["type"]) for e in mine])
def finals_for(cls):
out = set()
for perm in itertools.permutations(mine):
o = cls(4200)
for e in perm: o.apply(e)
out.add(o.view)
return out
naive, keyed = finals_for(NaiveOrder), finals_for(Order)
n_orders = len(list(itertools.permutations(mine)))
print("rule 1, ignore older events : %d distinct final states over %d arrival orders: %s" % (len(naive), n_orders, sorted(naive)))
print("rule 2, keep events by seq : %d distinct final state over %d arrival orders: %s" % (len(keyed), n_orders, sorted(keyed)))
o = Order(4200)
for e in [mine[0], mine[0]]: o.apply(e)
print("a duplicate delivery changes nothing:", o.view, "with", len(o.events), "event kept")
ledger = sum(i["amount"] for i in intents.values() if i["status"] == "succeeded") - sum(r["amount"] for r in refunds)
print("provider ledger: collected minus refunds =", ledger, "cents")
print("DATA " + json.dumps({"naive": sorted(list(f) for f in naive), "finals": [list(f) for f in keyed], "n": n_orders, "ledger": ledger, "events": [(e["seq"], e["type"]) for e in mine], "statuses": [a["status"], b["status"], c["status"]], "ints": len(intents)}))
same idempotency key returns the same intent: True | intents on the provider: 1
confirm with tok_ok -> succeeded
confirm with tok_declined -> failed
confirm with tok_3ds -> requires_action (the customer must authenticate)
refund 1000 -> 1000 | refund 5000 (too much) -> None | refund on a declined payment -> None
events for the first payment: [(1, 'payment.succeeded'), (2, 'refund.created'), (3, 'refund.created')]
rule 1, ignore older events : 2 distinct final states over 6 arrival orders: [('partially_refunded', 3200, 3), ('refunded', 4200, 3)]
rule 2, keep events by seq : 1 distinct final state over 6 arrival orders: [('refunded', 4200, 3)]
a duplicate delivery changes nothing: ('paid', 0, 1) with 1 event kept
provider ledger: collected minus refunds = 0 cents
The flow ran in the order of the table. Creating the intent twice with the key “order-1” returned the same intent, and the provider holds only 1 intent for that order, so a retry cannot charge twice. Confirming with the test token for success gave “succeeded”, the decline token gave “failed”, and the token for extra authentication gave “requires_action”, an outcome that is not final: the customer must complete a challenge, and the final result will arrive later as an event. The provider also enforced the rules of refunds: a refund of 1,000 of the 4,200 collected was accepted, a refund of 5,000 was refused because it exceeds what is left, and a refund on the declined payment was refused because nothing was collected.
The sequence numbers are what make the ordering problem solvable. The first payment produced three events: (1, payment.succeeded), (2, refund.created), (3, refund.created). The experiment fed the three events to a fresh order object in every possible arrival order, 6 of them, with two designs. The tempting rule, ignore any event older than the last one applied, ended in 2 different final states: when the last refund arrived first, the earlier events were dropped as stale, and the order stayed at “partially_refunded” with only 3,200 cents refunded instead of 4,200. That is a real bug that a test with a single, tidy order of events would never find. The second design kept each event under its sequence number, ignored a duplicate, and computed the state by replaying the events in order, and it ended in exactly 1 final state in all 6 orders: refunded, with 4,200 cents refunded, last sequence number 3. A duplicate delivery of one event changed nothing. A real shop also fetches the current state of the intent from the API when it sees a gap in the numbers, as a second safety net.
Independent check: the final state was predicted without the state machine, by sorting the events by their sequence number and summing the refunds: 1,000 + 3,200 = 4,200, which is the whole amount, so the order is fully refunded, and the shop’s result for every permutation agrees. The provider’s own ledger, collected money minus refunds, is 0 cents, which equals what the shop believes it still holds for this order: nothing. Reconciliation, comparing your records with the provider’s, is done regularly in real systems, and any difference is investigated.
Check by hand: 4,200 collected, 1,000 refunded, then 3,200 refunded gives 4,200 refunded, the total, so the state is “refunded”. There are 3 x 2 x 1 = 6 orders of three events. The declined payment collected nothing and the one waiting for authentication collected nothing yet, so the ledger counts only the first payment.
Use the provider’s hosted fields or checkout and handle only tokens. Storing or logging card numbers creates legal and security obligations that most shops should avoid completely.
The reply to a confirmation can be lost, and some outcomes are asynchronous. Update orders from verified events, and fetch the object from the API when in doubt.
Every program in this lesson was run while the course was written, with Python 3.13 (standard library only) against small mock APIs that the lesson itself starts on a local port, and cross-checked with curl, OpenSSL, Node.js or a second calculation. The services are invented stand-ins, not real vendors: always read the current documentation of the real API you use. The provider here is a simulation and its flow is a typical pattern, not any real provider’s exact API. Real providers add many statuses, fees, disputes and regional rules, so read the current documentation and the legal requirements for your country.
Practice
Add a payment.requires_action event and the state “waiting_for_customer”. Add a timeout that cancels an order that stays unpaid for an hour. Extend the property test to include a duplicate of every event.
Check what you learned
Five quick questions. Pick an answer and you will see straight away whether it is right and why.
What does the shop receive instead of a card number?
- A hash of the number
- A token
- The last four digits only
- A password
Hosted fields keep card data out of your systems.
What does requires_action mean?
- The customer must complete extra authentication
- The payment failed
- The payment is refunded
- The key is wrong
The final result arrives later.
Why keep events by sequence number?
- To get the same state whatever the arrival order
- To sort emails
- To count customers
- To compress data
Ignore stale or duplicate ones.
Why try every arrival order in a test?
- To make the test slower
- It is required by HTTP
- To find the fastest order
- To prove the final state does not depend on order
A property test.
What is reconciliation?
- Refunding a payment
- Signing a webhook
- Creating an intent
- Comparing your records with the provider’s
Done regularly.
Summary
- Create an intent with an idempotency key, confirm with a token, and rely on events.
- Never handle raw card data.
- Keep events by sequence number and replay them: the state no longer depends on arrival order.
- Reconcile with the provider’s ledger.
Questions
Should I trust the confirmation response or the webhook?
Both give information, and the webhook, verified by its signature, is the record. Fetch the current object by id when something looks inconsistent.
What about disputes and chargebacks?
They arrive as events too, and need a process: gather evidence, respond within the deadline, and update the order. Read your provider's documentation.
How do I test payments safely?
Use the provider's test mode, with its documented test tokens and cards, and never real card numbers.
