Sub topic 15
Reconciling with PSP and bank reports
Reconciliation compares your own records with the reports that outside parties send you, then investigates every difference. This chapter assumes you know the payment lifecycle (authorization, capture, settlement), the double-entry ledger, and idempotency keys from earlier chapters. It also assumes you can read short Python snippets.
Why reconcile at all
Your system believes a payment succeeded because a PSP (payment service provider) said so. Several things can make that belief wrong:
- A timeout hid a successful capture, so your record says "failed" while the PSP captured the money.
- A webhook was lost or delivered out of order.
- The PSP changed a transaction later, for example through a chargeback or a fee adjustment.
- A bug in your code wrote a wrong amount.
Reconciliation is the backstop. It does not prevent these errors. It finds them within hours instead of letting them surface in an audit months later.
The three sources of truth
You compare three data sets, each closer to real money than the last.
| Source | What it tells you | Typical timing |
|---|---|---|
| Internal ledger and payment table | What you believe happened | Real time |
| PSP transaction report | What the PSP processed, with fees and statuses | Daily file or API export |
| Bank statement | What money actually arrived in your account | Daily, often with a delay of one to several days |
Each comparison answers a different question. Internal records against the PSP report catch lost updates and wrong amounts. The PSP settlement report against the bank statement confirms that the PSP paid out what it said it would.
Choosing a matching key
Matching needs a key that both sides share. Good keys, in order of preference:
- The PSP's own transaction reference, which you store when the PSP responds.
- Your idempotency key or payment ID, if the PSP echoes it back as merchant reference metadata.
- A composite of amount, currency, and timestamp window. Use this only as a last resort, because two real payments can share all three.
The first key has a gap. If a timeout hid the PSP's response, you never stored the PSP reference. That is why you should also send your own payment ID to the PSP on every request. It lets you match the orphaned transaction later.
A matching algorithm
The core job is a full outer join on the key, followed by a field comparison. Every row falls into one of four groups:
- Matched: both sides agree on amount, currency, and status.
- Missing in report: you have it, the PSP does not.
- Missing internally: the PSP has it, you do not.
- Mismatch: both have it, but a field differs.
from dataclasses import dataclass
@dataclass(frozen=True)
class Row:
ref: str
amount_minor: int
currency: str
status: str
def index(rows):
by_ref = {}
for row in rows:
if row.ref in by_ref:
raise ValueError(f"duplicate reference {row.ref}")
by_ref[row.ref] = row
return by_ref
def reconcile(internal, report):
ours_by_ref = index(internal)
theirs_by_ref = index(report)
result = {"matched": [], "missing_in_report": [],
"missing_internally": [], "mismatch": []}
for ref, ours in ours_by_ref.items():
theirs = theirs_by_ref.get(ref)
if theirs is None:
result["missing_in_report"].append(ref)
elif ours != theirs:
result["mismatch"].append((ref, ours, theirs))
else:
result["matched"].append(ref)
for ref in theirs_by_ref:
if ref not in ours_by_ref:
result["missing_internally"].append(ref)
return result
internal = [
Row("psp_1", 1999, "USD", "captured"),
Row("psp_2", 500, "USD", "captured"),
Row("psp_3", 1200, "USD", "captured"),
]
report = [
Row("psp_1", 1999, "USD", "captured"),
Row("psp_2", 550, "USD", "captured"),
Row("psp_4", 800, "USD", "captured"),
]
for group, items in reconcile(internal, report).items():
print(group, items)Running this reports psp_1 as matched, psp_2 as a mismatch, psp_3 as missing in the report, and psp_4 as missing internally.
The index function raises on duplicate references on purpose. A plain dictionary would silently keep the last row and hide a double-reported transaction.
Handling timing differences
Many differences are not errors. They are timing. A payment captured at 23:59 UTC may appear in tomorrow's PSP report. Settlement to the bank usually lags the PSP report by days.
Handle this in three ways:
- Compare by report cutoff, not by calendar day. Use the same time zone and the same cutoff as the PSP's report.
- Give "missing" items a grace period. Mark them pending for a set window, such as 48 hours, and escalate only if they stay unmatched.
- Keep each exception's age. A one-day-old unmatched item is normal. A seven-day-old one needs a person.
Matching payouts, fees, and refunds
The bank does not receive one deposit per payment. The PSP batches many transactions into one payout and subtracts fees, refunds, and chargebacks. To match a payout, rebuild its total from the transactions in the settlement report:
payout = sum(captured) - sum(refunded) - sum(chargebacks) - sum(fees) ± reserve adjustments
Compare that computed figure with the settlement report's stated total, then with the bank deposit. Keep all values in integer minor units and group by currency. Never add USD to EUR. If the PSP converts currency, the report should state the exchange rate and the converted amount, and you record both.
Fees deserve their own check. Recompute expected fees from your contract's rate card and compare them with the fees charged. Small systematic fee errors add up to real money.
Resolving exceptions
Each exception type has a usual cause and a usual fix.
| Exception | Common cause | Typical resolution |
|---|---|---|
| Missing in report | Timing lag, or you recorded a capture that failed | Wait out the grace period, then query the PSP for the status |
| Missing internally | Timeout hid the response, or a lost webhook | Create the payment from the PSP data and post ledger entries |
| Amount mismatch | Partial capture, fee netting, or a bug | Compare the lifecycle events, then correct |
| Status mismatch | Late webhook, or a later chargeback | Apply the transition through the state machine |
Fix every error with new ledger entries, never by editing old rows. The ledger is append-only, so a correction is a new transaction that references the one it fixes. This keeps the audit trail intact. Run status corrections through the same state machine code as normal events, so an illegal transition still fails loudly.
Operating the process
- Run it on a schedule and on demand. Daily is typical, and you also want to rerun a single day after a fix.
- Make it idempotent. Rerunning a day must not create duplicate exceptions. Key each exception by source, reference, and report date.
- Store the raw files. Keep the original PSP and bank files unchanged, with a checksum, so you can replay a run.
- Alert on rates, not just counts. A rise in the unmatched percentage often signals a new bug or a PSP change before any single case is noticed.
- Check the ledger against itself. Total debits must equal total credits per currency. Run this before comparing with outside data.
Exercise
A PSP report shows a transaction your system has no record of. Your logs show a request to the PSP that timed out. What does this likely mean, and what should reconciliation do?
Show answer
The PSP probably processed the request, but the timeout hid the response, so you never stored the PSP reference. Reconciliation should match the transaction using the payment ID you sent as merchant metadata, then create or update the payment record and post the ledger entries through the normal state transitions. If the payment ID cannot be matched, send it to the exceptions queue for review.
Exercise
Why does the matching code raise an error on duplicate references instead of keeping the last row?
Show answer
A duplicate reference means a data problem, such as a transaction reported twice or a bad key. Keeping only the last row would hide it, and the totals would be wrong without any warning.