Skip to content

Payment Processing Architecture: Idempotency, Fraud Detection, PCI ​

"The easiest way to address inconsistencies in distributed state caused by failures is to implement server endpoints so that they’re idempotent, which means that they can be called any number of times while guaranteeing that side effects only occur once." — Brandur Leach, Designing robust and predictable APIs with idempotency, Stripe blog, February 22, 2017

Summary: A payment system moves money it cannot take back by retrying, across a network that loses answers, through a PSP (Stripe, Adyen) that tells you the truth later by webhook; the whole architecture exists to make every money movement happen exactly once in effect, be recorded in an append-only double-entry ledger, agree with the PSP's settlement file, survive fraud and disputes, and keep card numbers out of your systems. Focus: Money as integer minor units with ISO 4217 exponents and explicit currency rounding; the payment intent state machine (Stripe PaymentIntent statuses); authorization, capture, void, refund and partial refund; the Idempotency-Key header and derived provider keys; timeouts and the unknown outcome; the double-entry ledger, journal entries, ledger immutability and the audit trail; webhooks with signature verification (Stripe-Signature, Adyen HMAC), replay window, out-of-order webhooks, at-least-once delivery, a webhook idempotency table and a dead-letter path; the outbox for an exactly-once effect; sagas and compensation; reconciliation against the settlement file and payouts; chargebacks and disputes; 3-D Secure, SCA and PSD2; PCI DSS v4.0.1, SAQ A, tokenization, network tokens and card vaulting; fraud score, velocity rules, device fingerprint, the risk engine and the manual review queue; retries, dunning and smart retries; Laravel Cashier, the Stripe PHP SDK and stripe-go. Learning goal: Design a payment service that never double-charges after a timeout, never loses a webhook, never lets its books drift from the PSP, keeps the card number out of its own servers, and decides fraud in the checkout's latency budget; and explain each of those choices in an interview with the exact product behaviour behind it.

This chapter is the "Domain Systems" view of payments: how the pieces fit together into one service and what each piece must guarantee. Several neighbours own the general mechanisms and are linked, not re-taught: the storage and lease details of idempotency keys are in API Idempotency; retry budgets, backoff and jitter are in Timeouts, Retries & Jitter; the outbox relay is in Outbox Pattern; orchestration vs choreography is in Saga Pattern; the consumer-side dedup table is in Idempotent Consumer & Inbox; transaction guarantees and isolation anomalies are in ACID Transactions and Isolation Levels; web attacks against a checkout page are in OWASP Top 10; HMAC, TLS and secret storage are in Cryptography in Practice; the payment as a consistency boundary is in Aggregates & Factories; and a whole-company example is in Case Study: Amazon.

Page map ​

If you are looking forGo to
The whole page in three tablesEverything in one minute
Why payments are harder than "call the API"Why it exists
Card networks, PSPs, PCI DSS, PSD2, idempotency keys: the datesWhere it comes from
Floats, minor units, ISO 4217, rounding, the money typeMoney
Issuer, acquirer, card network, PSP, Stripe vs AdyenThe payment chain
PaymentIntent statuses and the state machinePayment intent and state machine
Authorize, capture, void, refund, partial refundMoney movements
Idempotency-Key header, provider keysIdempotency keys
Timeouts, 5xx, the unknown outcome, failover rulesTimeouts and the unknown outcome
Debit, credit, journal entry, append-only, audit trailDouble-entry ledger
Stripe-Signature, HMAC, replay window, order, duplicatesWebhooks
Outbox, at-least-once delivery, exactly-once effectOutbox
Multi-step checkout, void as compensationSaga and compensation
Settlement file, payout report, feesReconciliation
Chargebacks, inquiries, evidence, feesDisputes
3-D Secure, SCA, PSD2, liability shift, exemptions3-D Secure and SCA
PCI DSS v4.0.1, SAQ A, tokens, vaulting, network tokensPCI DSS and tokenization
Fraud score, velocity rules, device fingerprint, review queueFraud and risk engine
Soft vs hard declines, dunning, smart retriesDeclines, retries and dunning
Two PSPs, routing, failoverMulti-PSP routing
Laravel Cashier, Stripe PHP SDK, stripe-go, Adyen librariesLibraries
Request flow, error codes, knobs, SQLMechanics
CodeGo, Laravel
Eleven classic failures and their fixesSolving the classic problems
Which capture mode, which integration, which retry policyChoosing
From a monolith to many regionsIn architecture
Runnable programs and expected experimentsLab
Wrong beliefs, summary, interview questions, termsMisconceptions, Cheat sheet, Self-check, Glossary

Everything in one minute ​

The money movements.

OperationIn plain wordsStripeAdyenLedger effect
AuthorizationAsk the issuer to reserve the amount on the cardConfirm a PaymentIntent with capture_method=manual → requires_capture/payments with manual captureNone yet: a hold is not revenue
CaptureTake the reserved moneyPOST /v1/payment_intents/:id/capture, optional smaller amount_to_capture/payments/{paymentPspReference}/capturesD PSP receivable, C sales
VoidRelease a hold that was never capturedCancel the PaymentIntent (canceled)/payments/{paymentPspReference}/cancelsNone
RefundSend captured money backPOST /v1/refunds (full or partial refund)/payments/{paymentPspReference}/refundsD refunds, C PSP receivable
ChargebackThe cardholder's bank takes money backcharge.dispute.created; amount and fee debitedDispute notificationsD chargeback losses + fees, C receivable
PayoutPSP pays your balance to your bankPayout, matched with automatic_payout_idSettlement batchD bank cash, C PSP receivable

The five guarantees and what provides each.

GuaranteeFailure it preventsMechanism on this page
Exactly-once effect per paymentDouble charge after a timeoutIdempotency-Key header from the client, derived provider key to the PSP, unique constraints
No illegal state"Refunded" before "captured"; a late webhook overwriting succeededOne state machine with an explicit transition table
Books that balanceMoney created or lost by a bugDouble-entry ledger: every journal entry has debits = credits; append-only
Every event processedLost webhook, lost receipt e-mailWebhook inbox + queue + dead-letter; outbox for your own events
Your books = the PSP's booksSilent drift, unknown outcomes never resolvedDaily reconciliation against the settlement file and payouts

The threats and what stops them.

ThreatWhat it looks likeWhat stops it
Card data theftPAN and CVV in your logs or databaseTokenization in the PSP iframe; you stay in SAQ A scope
Forged webhookPOST /webhooks/stripe with payment_intent.succeeded from anyoneSignature verification over the raw body, constant-time compare
Replayed webhookA captured valid request sent again laterReplay window (Stripe libraries: 5 minutes) + event-id dedup
Card testingHundreds of small charges with stolen cards from one deviceVelocity rules, device fingerprint, CAPTCHA, block
Stolen-card purchaseA large first order shipped to a reshipperFraud score, 3-D Secure step-up (liability shift), manual review queue
Friendly fraud"I did not buy this" after deliveryEvidence (3DS result, delivery proof), dispute response
Insider or bug edits a balanceUPDATE accounts SET balance = ...Ledger immutability: triggers forbid UPDATE/DELETE; corrections are reversals
BrowserPSP iframe: token only(SAQ A scope)Checkout APIIdempotency-KeyheaderPayment servicestate machinefraud / risk enginePSP: Stripe / Adyenprovider idempotency keyauthorize, capture, refundOne DB transactionpayments + attemptsledger entries (D = C)outbox rowWebhook endpointverify signature, inbox,200 fast, queue workerOutbox relayat-least-oncepublishBrokerorders, e-mail,analytics (dedupe)Reconciliationdaily diff, ticketsSettlement file, payoutreport (fees, refunds,chargebacks)

The picture is the whole chapter in one frame. Read it left to right for the synchronous path (browser → checkout API → payment service → PSP) and bottom to top for the asynchronous truth: the PSP's webhook and its settlement file both end in the same database transaction box, which writes the payment row, the ledger entries and the outbox row together. The card number never crosses the first arrow: the browser sends only a token.

Why it exists ​

Charging a card looks like one HTTP call. In production it is a distributed transaction between your database and a PSP that you do not control, over a network that can lose the answer after the money moved. A retry can charge twice; not retrying can lose a sale or leave the customer charged with no order. The PSP's final word often arrives later: 3-D Secure needs the customer, bank debits (SEPA, ACH) take days, and disputes arrive up to months later. Your finance team needs books that a PSP report can check line by line. And the card number itself is regulated data: touching it puts your whole application into PCI DSS scope.

Simpler / cheaperStronger / more control
Charge immediately (automatic capture)Authorize now, capture on shipment (manual capture): no refund for out-of-stock items, but holds expire: the PSP tells you when (Stripe: payment_method_details.card.capture_before on the charge; Visa merchant-initiated holds last 5 days, most others 7)
Trust the synchronous API answerTreat webhooks as the source of truth for async outcomes; reconcile daily
A balance column you updateA double-entry ledger of immutable entries; balances are derived
Retry until it worksRetry only with the same key; park unknown outcomes; never fail over after an ambiguous error
One PSPTwo PSPs with routing: better uptime and authorization rates, double the reconciliation
Card form on your pagePSP-hosted fields or redirect: SAQ A instead of hundreds of PCI controls
Block on rules onlyRules + ML fraud score + 3DS step-up + human review

The analogy we reuse on this page: a restaurant with a card terminal and a cash book. The waiter (your checkout) asks the bank terminal (the PSP) to authorize the bill; nothing has been paid yet, the card is only reserved. At the end of the evening the manager captures the day's authorizations. If the terminal's printer jams after "approved" (a lost response), pressing "pay" again on the same bill number must not charge twice: the bill number is the idempotency key. The cash book (the ledger) is written in pen: a mistake is fixed by a new correcting line, never by scratching out the old one. Every morning the manager ticks the bank statement against the cash book (reconciliation). The terminal's receipt tape (webhooks) can come out of order or twice, so the manager files receipts by their serial number. And the waiter never writes the card number on the bill (tokenization).

Three common misunderstandings, up front ​

  1. "The PSP is idempotent, so retries are safe." Only if you send the same idempotency key with the same parameters on every retry, and only for as long as the PSP keeps the key (Stripe API v1: keys can be pruned after 24 hours; Adyen: "valid for a period of 7 to 14 days"). A retry with a new key, or after the key expired, is a second payment.
  2. "succeeded in the API response is the end of the story." It is the end of the authorization and capture. Refunds, partial refunds, disputes, fees and the payout to your bank all happen afterwards, and you only learn about most of them through webhooks and the settlement file. A payment system that does not reconcile does not know its own state.
  3. "Using Stripe makes us PCI compliant." Using Stripe's hosted fields (Payment Element, Checkout) can reduce your scope to SAQ A, the shortest self-assessment questionnaire; it does not remove PCI DSS. Since PCI DSS v4.0.1 requirements became effective on 31 March 2025, SAQ A merchants must also confirm their site "is not susceptible to attacks from scripts that could affect the merchant’s e-commerce system(s)" (PCI SSC).

Where it comes from ​

Double-entry bookkeeping, 1494. Martin Fowler's Patterns for Accounting recalls that double-entry bookkeeping was "developed in medieval times and first documented by Luca Pacioli, an Italian friar, in 1494". Every payment ledger on this page is that idea with a database underneath.

Card networks and the chargeback. Card schemes gave cardholders the right to dispute a payment through their issuer; the merchant answers with evidence. The dispute window for cards is commonly 120 days (Stripe: "Card networks typically allow cardholders to initiate disputes within 120 days of the original payment").

PCI DSS. The Payment Card Industry Security Standards Council (PCI SSC) publishes the Data Security Standard. PCI DSS v4.0 was published in March 2022; v4.0.1 is "a limited revision" with "no additional or deleted requirements"; v4.0 was retired on 31 December 2024, and the future-dated requirements became effective on 31 March 2025. In January 2025 PCI SSC changed SAQ A: requirements 6.4.3 and 11.6.1 (payment page scripts) were removed from it and replaced by an eligibility criterion about scripts.

3-D Secure and PSD2. EMVCo maintains EMV 3-D Secure (3DS2), which it describes as "an e-commerce fraud prevention protocol that enables consumer authentication for CNP purchases". In the European Economic Area, PSD2 and its regulatory technical standards (Commission Delegated Regulation (EU) 2018/389, published by the EBA as the RTS on SCA and CSC) require strong customer authentication; Stripe documents SCA "in effect as of September 14, 2019".

Idempotency keys, 2017 and the IETF draft. Stripe's 2017 post made the Idempotency-Key header the industry pattern; the IETF HTTPAPI working group has standardised it as draft-ietf-httpapi-idempotency-key-header (revision 09 read for this chapter), which recommends 422 for a reused key with a different payload and 400 when a required key is missing. RFC 9110 section 9.2.2 keeps the classic definition: a method is idempotent "if the intended effect on the server of multiple identical requests with that method is the same as the effect for a single such request", and POST is not one of them.

Ledgers at PSP scale. Stripe describes its internal Ledger as "an immutable and auditable log" based on double-entry bookkeeping that "sees five billion events" a day.

text
     Year   Event                                             What changed in practice
1    1494   Pacioli documents double-entry bookkeeping          Debits = credits; ledgers in pen
2    2017   Stripe "Designing robust ... APIs with idempotency" Idempotency-Key header becomes the norm
3    2018   EU RTS 2018/389 on SCA                              Strong customer authentication defined
4    2019   SCA in effect (Sept 14, per Stripe)                 3-D Secure 2 for European card payments
5    2019   Stripe API 2019-02-11                               requires_payment_method / requires_action names
6    2022   PCI DSS v4.0 (March)                                New e-commerce script requirements, future-dated
7    2024   PCI DSS v4.0.1; v4.0 retired 31 Dec 2024            Clarifications only, no new requirements
8    2025   31 Mar 2025: future-dated requirements effective    New SAQ A with a script eligibility criterion
9    2026   draft-ietf-httpapi-idempotency-key-header-09        400 missing key, 422 key reuse, 409 in flight

Line 5 is from Stripe's lifecycle page ("Versions of the API before 2019-02-11 show requires_source instead of requires_payment_method"). The year on line 7 is inferred from the PCI SSC post (comment period December 2023 to January 2024, v4.0 retired 31 December 2024); line 9 is the draft revision current when this chapter was researched (November 2026).

The concept catalogue ​

Each block follows the same order: plain words, the usual wrong belief, a definition, a timeline, real scenarios, what products do, and the fix. The code each fix refers to is in Go and Laravel.

Money: minor units, ISO 4217, decimal and currency rounding Must-know ​

In plain words: store money as a whole number of the currency's smallest unit (cents for USD, yen for JPY, fils for BHD) together with the three-letter currency code, and never as a floating-point number.

Common misunderstanding: "A float64 or DOUBLE is fine if I round when I display it." Binary floating point cannot represent 0.1 exactly. This chapter's before/main.go adds 0.1 and 0.2 and prints 0.30000000000000004; summed over a million rows, or compared with == in a reconciliation job, those float pitfalls become missing cents and mismatches nobody can explain. A second wrong belief is "every currency has two decimals": ISO 4217 gives JPY 0 minor-unit digits, BHD and KWD 3, and CLF 4.

Definition: a money type is a value object of (amount in minor units as an integer, ISO 4217 alphabetic code). The minor-unit exponent comes from the ISO 4217 list (published by SIX on behalf of ISO; the list read for this chapter is dated 2026-09-17). Arithmetic is allowed only between equal currencies; conversion needs an explicit rate and an explicit rounding rule; splitting an amount (allocation) must hand out the remainder so that the parts sum to the whole. Where you need fractions of a minor unit (FX rates, tax rates, interest), use a decimal type (math/big.Rat in Go, NUMERIC in PostgreSQL, brick/money or bcmath in PHP), then round once, at a documented point, into minor units. Currency rounding is a business rule: half-up for invoices in many countries, half-even (banker's rounding) for statistical neutrality.

PSPs follow the same convention with their own exceptions. Stripe: "1000 to charge 10 USD (or any other two-decimal currency)" and "to charge 500 JPY, provide an amount value of 500"; ISK and UGX "transitioned to a zero-decimal currency, but backward compatibility requires you to represent it as a two-decimal value"; HUF and TWD payouts must be "evenly divisible by 100". Keep your exponent table per PSP, not only per ISO.

text
     Step                                  float64                     int64 minor units (money package)
1    price 0.10 USD                        0.1 (0.1000000000000000055) 10
2    + 0.20 USD                            0.30000000000000004         30
3    == 0.30 ?                             false                       true
4    split 1.00 USD three ways             0.333... x 3 = 0.999...     34, 33, 33  (sum 100)
5    10.00 USD at 0.9235 EUR/USD           9.235 -> 9.23 or 9.24 ?     923.5 -> half-even -> 924 = 9.24 EUR
6    charge 500 JPY                        amount 500? 50000?          exponent 0 -> amount 500

Real scenario: a marketplace that splits a 100.00 order into 3 sellers' shares loses one cent per order until finance notices a seven-figure drift; a Kuwaiti customer is charged 10 times too much because the code assumed two decimals for KWD; a reconciliation job flags thousands of "mismatches" because one side summed DOUBLE columns; a tax engine rounds per line while the invoice rounds per total.

What provides it:

LayerType for minor unitsType for fractions / ratesNote
PostgreSQLBIGINT + CHAR(3)NUMERIC(p,s)REAL/DOUBLE PRECISION are binary floats; avoid them for money
MySQLBIGINT + CHAR(3)DECIMAL(p,s)FLOAT/DOUBLE are approximate
Goint64 in a Money structmath/big.Rat, github.com/shopspring/decimal (a stripe-go v87 dependency)Never float64
PHP / Laravelint (64-bit)bcmath, brick/moneyEloquent offers a decimal:<precision> cast; keep money columns integer and do arithmetic in integers
Stripe APIInteger amount in the smallest unitn/aLower-case currency codes in requests
Adyen APIamount.value integer, "The amount in minor units (without a decimal point)" (capture docs), plus amount.currencyn/aSame convention as Stripe

Fix / how to use it: the money package (Parse without floats, Add/Sub with currency checks and overflow detection, Allocate with the largest-remainder rule, Convert with an exact decimal rate and half-even rounding); BIGINT + CHAR(3) columns in the SQL schema; total_minor integers in the Laravel controllers.

The payment chain: cardholder, issuer, network, acquirer, PSP Must-know ​

In plain words: your PSP (payment service provider) sits between you and the card world. It forwards your request to an acquirer (the merchant's bank), which sends it over a card network (Visa, Mastercard) to the issuer (the cardholder's bank), which says yes or no.

Common misunderstanding: "A decline means the PSP refused." Almost always the issuer declined (insufficient funds, suspected fraud, wrong CVC), and the PSP passes on a decline code. A PSP's own fraud engine can block too (Stripe Radar), and that is a different code (highest_risk_level appears in Stripe's hard-decline list).

Definition: a PSP aggregates acquiring, payment methods, tokenization, fraud tools and reporting behind one API. Stripe and Adyen are both PSPs. An authorization is the issuer's promise to pay a given amount; clearing and settlement move the money later in batches; the PSP then pays out your balance minus fees to your bank account.

text
     Customer       Your server        PSP (Stripe / Adyen)     Acquirer / network      Issuer
1    enters card in PSP iframe ------> token pm_123
2                   confirm(pi_42, pm_123) ->
3                                      authorization request -> route by BIN ------> check funds, fraud, 3DS
4                                      <---------------------------------------------- approved (auth code)
5                   <- requires_capture or succeeded
6    (later)                           capture / clearing batch ------------------> money moves (T+1..T+n)
7    (later)        <- payout to bank account, settlement file with fees

Real scenario: a checkout in the Netherlands where the issuer requires 3-D Secure; a US subscription renewal where the issuer declines with insufficient_funds and a retry three days later succeeds; a cross-border card with a lower approval rate that a second acquirer approves; a payout that arrives one banking day after the PSP sent it.

What each PSP calls things:

ConceptStripeAdyen
Payment objectPaymentIntent (pi_...), Charge (ch_...)Payment with pspReference
WebhookEvent (evt_...) to a webhook endpoint, Stripe-Signature headerNotification / webhook event with hmacSignature in additionalData
IdempotencyIdempotency-Key header, up to 255 charactersidempotency-key header, valid 7 to 14 days, per company account
Manual capturecapture_method=manualManual capture setting / delayed automatic capture
VoidCancel PaymentIntent/cancels
FraudRadar: risk score 0–99, 65+ elevated, 75+ highRisk management: risk profiles, rules, ML rules
ReconciliationPayout reconciliation report, balance reportSettlement detail report, settlement reconciliation

Fix / how to use it: model the PSP behind an interface (PSP in payment/service.go) with your own state names mapped from the provider's, store the provider's reference next to your attempt, and keep the provider's decline code verbatim for retries and analytics.

Payment intent and state machine Must-know ​

In plain words: a payment intent is one attempt to collect one amount for one order, and its status may move only along the arrows of a fixed diagram. Anything else (a stale webhook, a double click, a bug) is rejected instead of silently overwriting the status.

Common misunderstanding: "The status is just a column; set it to whatever the latest event says." Events arrive out of order: Stripe "doesn’t guarantee the delivery of events in the order that they’re generated". If payment_intent.processing arrives after payment_intent.succeeded and you blindly write it, a paid order looks unpaid and is cancelled by a cron job. A state machine makes the late event a no-op.

Definition: Stripe's PaymentIntent statuses are requires_payment_method, requires_confirmation, requires_action (for example 3-D Secure), processing (asynchronous methods "can take up to a few days"), requires_capture (manual capture), succeeded and canceled. A failed attempt "returns to requires_payment_method so that the payment can be retried"; a PaymentIntent can be cancelled "before it reaches a processing or succeeded state", and cancellation "releases any held funds". A PaymentIntent "might also automatically transition to canceled if they’re confirmed too many times". Refunds and disputes do not change the PaymentIntent status; they are separate objects.

requires_payment_methodrequires_confirmationrequires_actionprocessingrequires_capturesucceededcanceledattach3DS / SCAauto capturemanualcapturecapturevoid / expirydecline: back to requires_payment_method, customer may retryterminal; refunds anddisputes move money later

The picture is the transition table in intent/intent.go and PaymentStatus.php. The dashed arrow is the retry loop after a decline. Nothing leaves the two terminal boxes; a refund is a new money movement recorded next to the intent, not a new status.

text
     Event (arrival order)               Intent status before    Transition table says     Result
1    confirm (client)                    requires_confirmation   -> requires_action         3DS challenge shown
2    payment_intent.succeeded (evt_2)    requires_action         -> succeeded               ledger + outbox written
3    payment_intent.requires_action      succeeded               no edge                    acked, ignored
     (evt_1, created earlier, late)
4    payment_intent.succeeded (evt_2)    succeeded               inbox says: seen           acked, ignored
     (redelivery)

Real scenario: a webhook from a 3-D Secure flow arrives after the success webhook; two browser tabs confirm the same intent; an admin clicks "cancel" on an order that has just been captured; a SEPA payment stays processing for days and the order screen must show "pending", not "failed".

What provides it:

ProductStatesTransition enforcement
Stripe PaymentIntent7 statuses aboveEnforced by Stripe; your copy must enforce its own
AdyenResult codes (Authorised, Refused, Pending, ...) + webhooks per event codeYou build the state machine from event codes
This chapter, Gointent.Intent + transition map; requires_capture also accepts a verified PSPSucceeded carrying the captured amount (Succeed(amount), partial allowed)Apply returns ErrInvalidTransition
This chapter, LaravelPaymentStatus enum + canBecome() (edge or forward progress by rank)ProcessStripeEvent acks stale events, throws on conflicting terminal states
SQLCHECK (status IN (...)), version columnOptimistic lock: UPDATE ... WHERE version = ?

Fix / how to use it: one transition table, one function that applies events, a version column for optimistic locking (see Optimistic & Pessimistic Locking), and the intent treated as the aggregate root that owns its attempts, refunds and amounts (Aggregates & Factories).

Money movements: authorization, capture, void, refund, partial refund Must-know ​

In plain words: authorization reserves money, capture takes it, void releases a reservation, refund gives captured money back. A partial capture takes less than was reserved; a partial refund gives part of it back.

Common misunderstanding: "An authorization is a payment." It is a hold that expires. Stripe: "an authorization for an online card payment is valid for 7 days" (extended authorizations exist for some cases), but the windows differ by brand and type: Visa merchant-initiated card-not-present authorizations get "5 days" ("The exact authorization window is 4 days and 18 hours"), card-present Mastercard, American Express and Discover 2 days, and "the payment_method_details.card.capture_before attribute on the charge indicates when the authorization expires". Also "you can only perform one capture on an authorized payment for most payments. If you partially capture a payment, you can’t perform another capture for the difference." Shipping goods on an authorization you never capture is giving them away. The opposite mistake: refunding an uncaptured payment instead of voiding it, which costs fees and confuses the customer.

Definition:

OperationPreconditionEffect on the cardReversible?
AuthorizationValid card, issuer approvalHold on the available creditVoid, or expiry
Capture (full / partial)requires_capture, amount ≤ holdHold turns into a charge; the rest of the hold is releasedOnly by refund
Void (cancel)Not yet capturedHold releasedNo
Refund (full / partial refund)Captured; refunded total ≤ capturedCredit to the card in "approximately 5-10 business days" (Stripe)Some card refunds can be cancelled briefly; a refund can fail (refund.failed)
text
     Hotel booking (manual capture), amounts in cents
1    t0   authorize 10000           intent requires_capture, amount_capturable 10000, ledger: nothing
2    t3d  guest checks out: 8250     capture(8250) -> succeeded, amount_received 8250, hold for 1750 released
3                                    ledger: D psp_receivable 8250 / C sales 8250
4    t5d  minibar dispute: refund 1000 with key rf-hotel-7-1
5                                    ledger: D refunds 1000 / C psp_receivable 1000, amount_refunded 1000
6    t5d  client retries refund rf-hotel-7-1 -> no-op (same key)
7    t6d  refund 8000 requested     8000 + 1000 > 8250 -> rejected locally, never sent to the PSP

Real scenario: e-commerce that captures on shipment and voids out-of-stock lines; car rental and hotels with a large hold and a smaller capture; a food delivery app that captures the final amount after substitutions; customer service issuing several partial refunds on one order.

What provides it:

ProductPartial captureMultiple capturesVoidPartial refunds
Stripeamount_to_captureMulticapture only for some card paymentsCancel PaymentIntentYes, multiple partial refunds
AdyenYes; recommends flagging as pre-authorization"Multiple partial capture is disabled by default" (contact support)/cancels; use /reversals when "you do not know if the payment has been captured"Yes
Laravel CashierVia the Stripe clientn/aVia the Stripe client$user->refund($paymentIntentId) for a full refund (documented); partial amounts through Cashier::stripe()

Fix / how to use it: Intent.Capture(amount) rejects more than the hold and releases the rest; Service.Capture records the amount with its key capture:<intent> before calling the PSP (another amount later is ErrMismatch), books the ledger only after the PSP succeeds, and accepts a capture webhook that arrived first only if its amount matches; a webhook carries amount_received and the PSP's payment reference (HandleWebhook(..., amount, pspRef)), so a partial capture is booked as captured, not as the hold, and an event is attributed to the attempt that owns that reference (a late decline for attempt 1 cannot touch attempt 2); a capture or refund that the PSP confirmed but the ledger rejected is booked on retry from the stored result, without calling the PSP; Service.Refund binds each refund key to (payment, amount) forever, counts its amount as taken from the moment the key is recorded, and frees it only when the refund is booked or when a fresh key's first send is provably refused; any other failure leaves the refund unknown until the same key succeeds or ResolveRefund (after a lookup) settles it; each refund has its own idempotency key (rf-<order>-<n>), never the payment's.

Idempotency keys and the Idempotency-Key header Must-know ​

In plain words: every request that moves money carries a unique key; if the same key arrives again, the server returns the first result instead of doing the work again. There are two keys: the one your client sends you, and the one you send your PSP.

Common misunderstanding: "Generate a fresh UUID for each HTTP call to the PSP." Then each retry is a new payment. The provider key must be derived from something stable (the intent id plus the attempt number), so a crash-and-restart of your worker sends the same key again. The second wrong belief is that the key replaces a unique constraint on your side: the key protects one API; UNIQUE (merchant_id, order_id) protects your data from two different keys for one order.

Definition: the Idempotency-Key header (IETF draft-ietf-httpapi-idempotency-key-header) carries a client-generated key. Stripe: keys "are up to 255 characters long", "we suggest using V4 UUIDs"; for API v1 "Stripe saves the status code and body of the first request made with a given idempotency key after endpoint execution begins. Retries with the same key return the saved response, including 500 errors", "you can remove keys from the system automatically after they’re at least 24 hours old", and the layer "compares incoming parameters to those of the original request and errors if they’re not the same". Adyen: "Idempotency keys are valid for a period of 7 to 14 days after first submission", stored per company account. The full storage design (records, leases, 409/422) is in API Idempotency.

text
     Client (mobile)        Payment API (yours)                         Stripe
1    POST /payments  Idempotency-Key: c-7f3a  {order 1001, 2500 USD}
2                           idempotency_keys (m_1, c-7f3a) -> in_progress
3                           payments: pi_0001 created
4                           attempt 1: key pi_0001:attempt:1  -------->  charge processed
5                                                    <-- x  connection reset (answer lost)
6                           retry with the SAME key pi_0001:attempt:1 -> saved response: succeeded
7    <-- 201 {pi_0001, succeeded}  (key c-7f3a -> completed, response stored)
8    POST /payments  Idempotency-Key: c-7f3a  (user tapped again)
9    <-- 201 same body, replayed; nothing sent to Stripe

Real scenario: a double tap on "Pay"; a mobile app that retries on reconnect; a queue worker that crashes after the PSP call and is re-run; a load balancer 504 while the backend completes.

What provides it:

ProviderHeaderDocumented retention and duplicate behaviour
Stripe API v1Idempotency-KeyKeys can be pruned after 24 h; the saved first response (including 500s) is replayed; parameters are compared and a mismatch is an error; 409 while the first request runs: "wait and retry with that key and the same parameters"
Adyenidempotency-key"valid for a period of 7 to 14 days", per company account, not checked across regional endpoints; a duplicate before the first completes gets 422 or 409 with error code 704 "request already processed or in progress"; a race can return transient-error: true (retry with the same key); 503 with code 703 if the idempotency store is unavailable
SquareAn idempotency key ("a unique string") on the requestSame key, same request: "returns the response as the first successful" call; same key, changed request: "you get an error indicating that you used the idempotency key previously" ("might vary depending on the API")
IETF draftIdempotency-KeyRetention server-defined; 422 SHOULD for a reused key with another payload, 409 SHOULD while the original is processing, 400 when a required key is missing
Your APIIdempotency-KeyAt least the PSP's window; 422 (fingerprint), 409; plus one payment per merchant and order (ErrDuplicateOrder) whatever the key

Fix / how to use it: idem.Store (fingerprint, Started/Replay/InFlight, ErrMismatch); payment_attempts.psp_idem_key UNIQUE with the derived pi_...:attempt:N; in Laravel, the PaymentIntent is created through Cashier::stripe()->paymentIntents->create($params, ['idempotency_key' => 'pay_<order>:intent']) (Cashier's pay() and charge() do not expose a key), and the refund route requires the client's own Idempotency-Key header, stored on the refunds row and replayed on retry.

Timeouts, retries and the unknown outcome Must-know ​

In plain words: when a call to the PSP times out you do not know whether the customer was charged. You must find out (ask, or resend with the same key) before doing anything else, and you must never try a different PSP for that payment while the first one might have charged.

Common misunderstanding: "A timeout is a failure; show 'payment failed' and let the customer try again." The charge may have gone through; the customer pays again. Stripe's own guidance: "Treat the outcome of a request that returns 500 as indeterminate: the operation might have produced side effects even though you received an error. Don’t retry with a new idempotency key until you’ve resolved the original outcome."

Definition: an unknown outcome is any result after which the side effect may or may not have happened: client timeout, connection reset after the request was sent, 5xx. A provably-not-processed result is one where the request never reached processing: connection refused, DNS failure before sending, a documented error that says no side effect happened. Only the second class allows failover to another PSP. Stripe: "Limit retries of an unresolved operation to the first 24 hours after the original request, using the same key and parameters", and if the outcome is still unknown "don’t retry with either the old key or a new one", reconcile instead. Stripe also sends a Stripe-Should-Retry header with retry guidance. Shopify's payments team puts it first in its resilience list: "1. Lower Your Timeouts" (the Ruby Net::HTTP default is 60 seconds per phase).

Call PSPkey = pi_42:attempt:1Clear answersuccess / decline / 3DSRefused before processingconnect refused, no effectTimeout or 5xxunknown outcomeFail over to PSP 2new key, new attemptQuery or resendSAME key, SAME PSPPark: unknownno failoverApply resultstate + ledger + outboxanswer foundnonereconciliation sweep or the next retry with the same key

The picture is Service.charge and Service.Confirm in payment/service.go: the middle row is the only path that switches PSP, the bottom row keeps the same key at the same PSP, and the red box is where an attempt waits for the reconciliation sweep.

text
     Payment service                    Stripe (primary)                 Adyen (secondary)
1    Authorize key=pi_2:attempt:1 ---->  charge processed
2    ... 200 ms timeout                  (answer lost)
3    Lookup / resend key=pi_2:attempt:1 -> timeout again (Stripe degraded)
4    attempt 1 state = unknown            -- do NOT call Adyen: Stripe may have charged
5    order screen: "payment pending"
6    (5 min later) sweep: resend same key -> saved response: succeeded
7    apply: succeeded, ledger, outbox     -> customer charged once

Real scenario: a PSP incident where requests are processed but responses time out; a deploy that kills workers mid-call; a mobile client on a train; a "smart router" that fails over on every error and double-charges during a PSP brown-out.

What each error class allows:

ErrorExampleOutcomeRetry with same keyFail over to another PSP
Clear declinecard_declined / insufficient_fundsKnown: no chargeNo (it is final for this attempt)Not for the same reason; maybe for issuer-specific errors
4xx validationInvalid parameterKnown: no chargeNo, fix the requestNo
409 key in flightConcurrent duplicateUnknown, still runningYes, after a waitNo
Timeout after sendingcontext.DeadlineExceededUnknownYes, same parametersNever
5xx500Unknown (Stripe caches it with the key)Resolve firstNever
Refusal on a retry of an unknown key503 after an earlier timeoutStill unknown: this refusal says nothing about the earlier sendYes, laterNever
Anything unclassifiedConnection reset, response decode errorUnknown (fail closed)YesNever
Connect refused / DNS on a fresh keyNothing sent, never sent beforeKnown: no chargeYesYes, with a new key and a new attempt

Fix / how to use it: one operation per payment at a time (Confirm, Capture and Refund take a per-payment token; a second caller gets ErrInFlight, the 409 of this service); an attempt that was ever sent stays pinned to its key and PSP until a clear answer or reconciliation proves its outcome; per-call timeout well below the checkout budget (NewService(200*time.Millisecond, ...) in the lab), query-then-retry with the same key (charge), park unknown attempts (payment_attempts_open partial index), resend them with the same key only inside ResendWindow (23 h by default, below Stripe's 24 h key retention) and after that return ErrNeedsReconciliation and reconcile instead of resending; client-side retry budgets and jitter from Timeouts, Retries & Jitter; a circuit breaker in front of each PSP so a brown-out fails fast.

Double-entry ledger: debit, credit, journal entry, append-only Must-know ​

In plain words: every money movement is written as one journal entry with at least two lines, and the money taken from some accounts (credits) always equals the money put into others (debits). Nothing is ever edited; mistakes are fixed by a new entry that reverses the old one. Balances are sums of lines.

Common misunderstanding: "Debit means minus and credit means plus." Whether a debit increases or decreases a balance depends on the account kind. Modern Treasury: "Debit normal accounts increase with a debit entry and decrease with a credit entry"; "Credit normal accounts increase with a credit entry and decrease with a debit entry". Assets (cash, money the PSP owes you) and expenses are debit normal; liabilities (customer wallet balances, money you owe sellers), revenue and equity are credit normal. The second wrong belief: "a balance column plus an audit log is the same thing". A mutable balance can drift from its log; a derived balance cannot.

Definition: an account is "a discrete pool of value that represents a balance you want to track" (Modern Treasury). A journal entry (journal transaction) is an atomic set of entries (lines), each with an account, a direction (debit or credit) and a positive amount in minor units; per currency, the sum of debits equals the sum of credits. Fowler: "The value, or balance, of the Account is derived as the sum of all the Accounting Entrys." Ledger immutability means entries are append-only: no UPDATE, no DELETE; a correction is a reversing journal entry, so the audit trail shows both the mistake and the fix. Stripe's internal Ledger follows the same rule: "Transactions previously published into Ledger cannot be deleted or modified, and we can always reconstruct past state by processing all events up to that point." A clearing account (here psp_receivable) holds money in transit and should return to zero when the flow completes; Stripe compares that to "intermediate (clearing) pipes" that are "empty" at steady state.

Journal transactionDebit (D)Credit (C)capture:pi_0003partial capture of a 10000 holdpsp_receivable:stripe:USD 8250sales:USD 8250refund:rf-hotel-7-1partial refundrefunds:USD 1000psp_receivable:stripe:USD 1000fee:po_77from the settlement filepsp_fees:USD 270psp_receivable:stripe:USD 270payout:po_77bank statement linecash:bank:USD 6980psp_receivable:stripe:USD 6980D = CD = CD = Creceivable = 0

The picture follows the hotel booking from the money movements block through to the bank. Every row balances on its own, and the PSP receivable clearing account is debited once and credited three times until it is back to zero after the payout: a non-zero clearing balance at month end is a reconciliation ticket.

text
     Two concurrent postings on the same wallet (liability, balance 100), PostgreSQL READ COMMITTED
     T1 (withdraw 80)                                 T2 (withdraw 50)
1    BEGIN;                                           BEGIN;
2    SELECT ... FROM ledger_accounts WHERE id IN
       ('wallet:u1:USD','cash:USD') ORDER BY id FOR UPDATE;   -- locks in id order
3                                                     SELECT ... same rows ORDER BY id FOR UPDATE;  -- waits
4    check: 100 - 80 >= 0 -> insert entries, update cached balance
5    COMMIT;  -- deferred trigger checks D = C
6                                                     -- wakes, sees balance 20: 20 - 50 < 0 -> ROLLBACK
     Without FOR UPDATE both read 100 and the wallet ends at -30 (a lost update, see Isolation Levels).

Real scenario: a marketplace that owes sellers their share (liability) and takes a commission (revenue); a wallet that must never go negative; a refund issued twice by two support agents; an auditor asking "what was this account's balance on 30 June, and why"; finance closing the month and needing PSP fees as an expense line.

What provides it:

SystemDouble-entryImmutabilityBalance check
This chapter's SQLledger_entries lines, journal_transactions headersBEFORE UPDATE OR DELETE triggers raiseDeferred constraint trigger: D = C per currency at COMMIT; CHECK (allow_negative OR balance >= 0)
Go ledger packagePost rejects unbalanced or single-line transactionsNo update API; Post and Journal return deep copies, so no caller can edit a stored entry; Reverse posts a mirrorTrialBalance() always zero; Recompute() equals the cache
Laravel LedgerServicepost() in DB::transaction(..., attempts: 3)Insert onlyAccounts locked in sorted order with lockForUpdate()
Stripe Ledger (internal)"based on double-entry bookkeeping""immutable log of events"Data quality metrics on fund flows

Fix / how to use it: derive the posting id from the business event (capture:pi_..., refund:<key>) so posting is idempotent; lock accounts in a fixed order to avoid deadlocks; keep a cached balance only as an optimisation that Recompute can verify; isolation details in Isolation Levels and transaction mechanics in ACID Transactions.

Webhooks: signature verification, replay window, ordering, duplicates Must-know ​

In plain words: the PSP calls your HTTPS endpoint to tell you what happened. You must check that the call really came from the PSP, store it, answer 200 quickly, and process it later exactly once, without assuming it arrives once or in order.

Common misunderstanding: "Parse the JSON, check type, update the order." Without signature verification anyone can POST payment_intent.succeeded and get goods for free. Verifying against the parsed and re-encoded JSON fails, because "Stripe requires the raw body of the request to perform signature verification". And doing the business work before answering makes the PSP retry: "Your endpoint must quickly return a successful status code (2xx) before any complex logic that could cause a timeout."

Definition: Stripe signs each delivery in the Stripe-Signature header: t=<timestamp>,v1=<hex HMAC-SHA256>, computed over t + "." + raw body with the endpoint's signing secret. "Our libraries have a default tolerance of 5 minutes between the timestamp and the current time" (stripe-go: DefaultTolerance time.Duration = 300 * time.Second); "Don’t use a tolerance value of 0. Using a tolerance value of 0 disables the recency check entirely." That tolerance is the replay window: a captured request is useless after it. During a secret roll, "multiple secrets are active for the endpoint. Stripe generates one signature per secret" for up to 7 days; the v0 entry "is only present for test events", and your parser "must accept unknown entries and must not depend on a fixed entry count or order". Delivery is at-least-once delivery: "Webhook endpoints might occasionally receive the same event more than once"; Stripe retries "for up to three days with an exponential back off in live mode", and duplicates can even be two different Event objects ("use the ID of the object in data.object along with the event.type"). Ordering is not guaranteed (out-of-order webhooks), and "Don’t use created to determine event order". Events can be fetched with the API "for 30 days". Adyen signs with HMAC too: SHA256 over the payload with the HMAC key, Base64-encoded, delivered as hmacSignature in additionalData.

text
     Stripe                          Webhook endpoint (yours)                    Queue worker
1    POST /webhooks/stripe  Stripe-Signature: t=1798765432,v1=5257a8...
2                                    raw body bytes -> HMAC(secret_v2) == v1?  -- also try secret_v1 during a roll
3                                    |now - t| <= 300 s ?                       -- replay window
4                                    INSERT webhooks_inbox (stripe, evt_1) ON CONFLICT DO NOTHING
5                                    processed_at IS NULL -> dispatch job
6    <- 200 {"received": true}       (in milliseconds)
7    (retry: our 200 was lost)  POST same evt_1, new t and new signature
8                                    INSERT ... -> 0 rows (duplicate); processed_at still NULL
                                     -> dispatch again (the job is idempotent) -> 200
                                     (had the job already finished: processed_at set -> 200, no job)
9                                                                                lock inbox row + payment row
10                                                                               state machine allows edge?
11                                                                               payment, ledger, outbox, processed_at
12                                                                               -- one DB transaction

Real scenario: a forged succeeded webhook during a sale; a deploy that changes the JSON middleware order and breaks every signature check ("make sure app.use(express.json()) appears after your webhook route" is Stripe's Node advice, and the same trap exists in every framework); a 30-second handler that makes Stripe resend the same event five times; charge.refunded arriving before payment_intent.succeeded; a secret roll that breaks verification on half the servers.

What provides it:

ConcernStripeAdyenLaravel / CashierThis chapter
SignatureStripe-Signature, HMAC-SHA256, hexHMAC-SHA256, Base64, additionalData.hmacSignatureCashier's webhook route verifies with STRIPE_WEBHOOK_SECRETwebhook.Verifier, StripeWebhookController::verify
Replay windowTimestamp in the header; 5-minute library defaultNo timestamp tolerance in the HMAC scheme on Adyen's page; dedupe insteadcashier.webhook.tolerance = STRIPE_WEBHOOK_TOLERANCE, default 300, passed to WebhookSignature::verifyHeaderTolerance > 0 enforced (ErrBadTolerance)
Secret rollUp to 7 days, one v1 per secret"Changing your HMAC key" procedureOne secret in envSecrets [][]byte, any one may match
RetriesUp to three days, exponential backoff (live)No 2xx within 10 seconds → retry queue, retried "for up to 30 days" (30 s, 30 s, 1 min, 2 min … 8 h intervals); alert after 5 retriesn/aReturn 200 once stored; dispatch again if still unprocessed
OrderNot guaranteed"always check the timestamp"; some webhooks carry sequenceNumbern/aState machine ignores stale events, accepts forward progress
DedupEvent id; object id + typeDuplicates "have the same values in the eventCode and pspReference fields"; "use the details from the latest webhook event"n/awebhooks_inbox primary key (psp, event_id)

Fix / how to use it: verify (raw body, constant-time compare, tolerance, multiple secrets), insert into a webhook idempotency table (webhooks_inbox, the inbox of Idempotent Consumer & Inbox), return 200, process in a queued job inside one transaction, and after the last retry leave the row unprocessed with last_error as the dead-letter record for a human (compare Dead Letter Queue). If a webhook arrives for a payment your database does not have yet, retry later; do not mark it processed. In production prefer the SDK verifier (webhook.ConstructEvent in stripe-go, \Stripe\Webhook::constructEvent in the Stripe PHP SDK); the hand-written verifier on this page exists to show what those functions check.

Outbox: at-least-once delivery, exactly-once effect Must-know ​

In plain words: when a payment succeeds, other parts of the system (orders, e-mail, analytics) must hear about it. Write the "payment succeeded" event into an outbox table in the same database transaction as the payment and the ledger; a relay publishes it later. Consumers drop duplicates by event id.

Common misunderstanding: "Commit, then publish to Kafka; if the publish fails we log it." A crash between the two loses the event: the customer paid and the order never ships. The opposite order (publish, then commit) announces payments that roll back. There is no exactly-once delivery; there is an exactly-once effect, built from at-least-once delivery plus idempotent consumers.

Definition: the outbox pattern stores events as rows written atomically with the state change; a relay (polling or CDC) publishes rows and marks them published; a crash between publish and mark re-publishes, so delivery is at least once; consumers apply each event id once (inbox), so the effect is exactly once. Ordering per payment is kept by using the payment id as the partition key. Mechanics and relay designs are in Outbox Pattern.

text
     Payment service tx                         Relay                         Order service
1    BEGIN
2    UPDATE payments SET status='succeeded'...
3    INSERT ledger entries ...
4    INSERT outbox (evt_pi_0001_v3, payments.payment_succeeded)
5    COMMIT
6                                               SELECT ... WHERE published_at IS NULL
7                                               publish evt_pi_0001_v3 -> broker
8                                               (crash before marking published)
9                                               restart: publish evt_pi_0001_v3 again
10                                                                            inbox: evt_pi_0001_v3 new -> ship
11                                                                            inbox: seen -> skip

Real scenario: a receipt e-mail sent twice or never; a fulfilment service that ships an unpaid order because it consumed an event from a transaction that rolled back; an analytics pipeline double-counting revenue.

What provides it:

PieceHereAlternatives
Outbox tableoutbox with event_id UNIQUE, partial index on unpublished rowsDebezium CDC on the table
Relayoutbox.RelayOnce, stops at the first error to keep per-key orderLaravel queued job, Kafka Connect
Consumer dedupoutbox.Inbox / webhooks_inboxProcessed-events table per consumer
Laravel dispatchProcessStripeEvent::dispatch(...)->afterCommit()after_commit queue connection option

Fix / how to use it: never call the broker inside the payment transaction; emit outbox rows from the same function that applies the state change (Service.apply); give every event a deterministic id (evt_<intent>_v<version>).

Saga and compensation: multi-step checkout Must-know ​

In plain words: a checkout touches several services (stock, payment, shipping). There is no transaction across them, so you run the steps in order and, if a later step fails, you undo the earlier ones with compensations: release the stock, void the card hold.

Common misunderstanding: "A refund is the compensation for a payment." Only after capture. Before capture the compensation is a void, which costs nothing and leaves no line on the customer's statement; that is why many checkouts authorize first and capture only after the last step that can fail. The second wrong belief: "compensations cannot fail". A void can time out like any other PSP call; it needs retries and a dead-letter path.

Definition: a saga is a sequence of local transactions, each with a compensating action, coordinated by an orchestrator or by events (choreography); each step and each compensation must be idempotent, because the coordinator may re-run them after a crash. Orchestration vs choreography is in Saga Pattern.

text
     Orchestrator (order-77)     Inventory        Payment (PSP)          Shipping
1    reserve_stock  ---------->  reserved
2    authorize      ---------------------------->  hold 4999
3    book_shipment  ---------------------------------------------------->  "no slot" (fail)
4    undo authorize ---------------------------->  void hold (key order-77:authorize)
5    undo reserve   ---------->  released
6    order -> canceled; customer sees "could not ship", card statement shows nothing
     If step 4 keeps failing: parked on the dead-letter list; the hold expires by itself at its capture_before

Real scenario: an out-of-stock discovered after authorization; a ticketing system that holds seats and payment together; travel bookings (flight + hotel) where one leg fails; a marketplace where the seller rejects the order.

What provides it:

StepActionCompensationIdempotency key
Reserve stockDecrement availableReleaseorder-77:reserve_stock
AuthorizeManual-capture PaymentIntentVoid (cancel)order-77:authorize
Book shipmentCarrier APICancel labelorder-77:book_shipment
CaptureCapture the holdRefund (rarely: capture is last)order-77:capture

Fix / how to use it: checkout.Orchestrator runs steps, undoes completed steps in reverse order, retries each undo UndoTries times and parks failures in DeadLetter; capture is the last step and has no undo.

Reconciliation: settlement file, payout, fees Must-know ​

In plain words: every day, compare what you think happened with what the PSP says happened, line by line: charges, refunds, chargebacks, fees and the payout that reached your bank. Every difference is either a bug or an unknown outcome that just became known.

Common misunderstanding: "Our webhooks are reliable, so the database is right." Webhooks can be lost for longer than the retry window, mis-processed, or never sent for events that did not exist when you subscribed; fees and FX are only in the reports. And payouts do not map to calendar days: Stripe says to "Match report rows to payouts using automatic_payout_id instead of assuming that report dates coincide with the dates payouts arrive in your bank account".

Definition: a settlement file (Adyen settlement detail report, Stripe payout reconciliation report or balance report) lists each settled line with the PSP reference, type, gross, fee and net, grouped into a payout (settlement batch). Reconciliation is a three-way match: your payments/ledger ↔ the PSP file ↔ the bank statement. The output is lists: matched, missing at the PSP (after a cutoff), missing locally (the PSP settled money you never booked), amount mismatches, and unbooked fees.

text
     06:00  job loads stripe payout po_77 lines into settlement_lines (insertOrIgnore: rerun-safe)
     06:01  join on psp_reference
1    stripe_ch_1   charge  2500  fee 103   ours 2500   -> matched
2    stripe_ch_2   charge  4000  fee 146   ours 4000   -> matched
3    stripe_ch_9   charge  1200  fee  65   ours: none  -> missing_locally (an "unknown" attempt that succeeded)
4    fees total 314 -> post D psp_fees / C psp_receivable
5    bank statement: payout po_77 net amount -> post D cash:bank / C psp_receivable; receivable for po_77 = 0

Real scenario: the "unknown" attempt from a PSP incident that turns out to have succeeded (refund it or fulfil it); a refund created in the PSP dashboard by support, never booked; FX fees on a cross-currency charge; a payout that failed and was retried by the PSP.

What provides it:

SourceWhat it containsHow to match
Stripe payout reconciliation reportTransactions grouped by automatic payoutautomatic_payout_id
Stripe balance reportBalance movements by categoryPeriod totals
Adyen settlement detail reportPer-transaction settled lines per batchpspReference, batch number
Bank statementPayout creditPayout id in the reference text
This chapterrecon.Reconcile, ReconcileSettlementFile jobpsp_reference, cutoff time

Fix / how to use it: load files idempotently (primary key on (psp, batch_id, psp_reference, line_type)), compare in integers, book fees and payouts as ledger entries, open a ticket for every unmatched line, and treat "missing locally" as the resolution path for unknown outcomes.

Disputes and chargebacks Important ​

In plain words: a cardholder can ask their bank to take a payment back. The bank does it immediately, you pay a fee, and you can send evidence to win the money back weeks later.

Common misunderstanding: "A dispute is like a refund the customer requested." The money and a fee leave your balance at once ("Debits the disputed amount, plus a dispute fee, from your Stripe account"), the fee is usually not returned even when you win ("Unless otherwise stated in your Stripe contract, we never return the dispute received fee"), and refunding after a dispute was opened can pay the customer twice. Another wrong belief: "3-D Secure prevents disputes." It shifts fraud liability to the issuer ("If a cardholder disputes a 3DS payment as fraudulent, the liability typically shifts from you to the card issuer"); it does not stop "item not received" disputes.

Definition: an inquiry (retrieval request) may come first; a chargeback (formal dispute) debits the merchant; the merchant responds with evidence ("usually 7-21 days, depending on the card network"); the issuer decides ("usually 60-75 days"); the outcome is won or lost, with rare late wins and, for some networks, pre-arbitration. Cards "typically allow cardholders to initiate disputes within 120 days of the original payment"; SEPA Direct Debit customers can dispute "without providing a reason for up to 8 weeks after the debit".

text
     Day    Event                          Ledger (minor units)                        Dispute status
1    0      payment captured 5000          D receivable 5000 / C sales 5000
2    40     charge.dispute.created         D chargeback_losses 5000, D dispute_fees 1500
                                           / C receivable 6500                        needs_response
3    45     evidence submitted (3DS, tracking)                                        under_review
4    100    issuer decides: won            D receivable 5000 / C chargeback_losses 5000  won
5           fee 1500 stays an expense

Real scenario: "friendly fraud" after a digital download; a subscription the customer forgot about; a stolen card used without 3DS; a SEPA mandate disputed within eight weeks; early fraud warnings, where Stripe's analysis suggests refunding is "most worthwhile on charges at or below your dispute fee".

What provides it:

ProductSignalEvidenceFee behaviour
Stripecharge.dispute.created, charge.dispute.closedDashboard or API evidence submissionReceived fee not returned (except Mexico); countered fee returned if you win
This chapterdispute.Open, SubmitEvidence, Closen/aFee line booked at open, never reversed

Fix / how to use it: book the chargeback immediately (posting id dispute_opened:<id>, idempotent), keep 3DS results, IP, device and delivery proof with the payment (you need them for evidence and for the fraud model), block refunds on disputed payments, and feed lost disputes back into the fraud rules.

3-D Secure, SCA and PSD2 Important ​

In plain words: for many online card payments, especially in Europe, the customer's bank wants proof that the cardholder is really there: an app confirmation, a fingerprint, a one-time code. 3-D Secure is the protocol that asks; SCA is the European rule that requires it; PSD2 is the law behind the rule.

Common misunderstanding: "3-D Secure always means a pop-up." EMV 3DS (version 2) can complete in a frictionless flow: "the acquirer, issuer, and card scheme exchange all necessary information in the background through passive authentication using the shopper's device fingerprint" (Adyen). Only a challenge flow asks the shopper. The opposite misunderstanding: "low-risk payments are exempt, so we can skip 3DS support". Stripe: "banks can still request that the customer complete authentication", and "Exemptions aren’t guaranteed".

Definition: Strong Customer Authentication requires two independent factors for electronic payments in the EEA, under PSD2 and Commission Delegated Regulation (EU) 2018/389 (the EBA's RTS on SCA and CSC). Stripe: "Strong Customer Authentication (SCA), a rule in effect as of September 14, 2019, as part of PSD2 regulation in Europe" and "Card payments require you to use 3D Secure to meet SCA requirements". EMVCo: "While EMV 3DS 2.1 supports SCA, EMVCo recommends that v2.2 (or higher) should be considered"; its version list read for this chapter includes v2.4.0.0. Saved-card payments without the customer present are merchant-initiated transactions (MIT) that need "an agreement (also known as a mandate)". A successful 3DS authentication gives a liability shift for fraud disputes.

text
     Customer        Your server         PSP / 3DS server        Issuer ACS
1    Pay 120 EUR --> confirm(pi_9)  ---> 3DS2 AReq with device data, history -> risk check
2                                                                 frictionless? -> ARes "Y" (no UI)
3                    <- succeeded                                 (liability shift)
     or
2'                                                                challenge -> ARes "C"
3'                   <- requires_action (next_action)
4'   bank app approve ----------------------------------------->  CRes OK
5'                   webhook payment_intent.succeeded

Real scenario: a European checkout where the issuer challenges every first purchase; a subscription renewal (off-session MIT) that the issuer still soft-declines with authentication_required, so the customer must come back on-session; a fraud rule that steps up instead of blocking; a US merchant that adds 3DS only for high-risk orders to shift liability.

What provides it:

ProductHow 3DS appearsDeveloper action
StripePaymentIntent requires_action; Radar can "request 3DS authentication"Handle next_action with Stripe.js; webhooks for the result
AdyenNative or redirect 3D Secure 2; frictionless or challengeaction object handled by Drop-in / Components
Laravel CashierIncompletePayment exceptionRedirect to the cashier.payment route with redirect
This chapterintent.RequiresAction, fraud.Request3DFraud engine chooses step-up for medium risk when the card is 3DS-capable

Fix / how to use it: always handle requires_action; save cards with a SetupIntent (Stripe: "an object that represents your intent to set up a customer’s payment method for future payments") so later off-session payments carry the mandate; use 3DS as the "medium risk" action of the fraud engine; store the 3DS result as dispute evidence.

PCI DSS, SAQ A, tokenization, network tokens, card vaulting Must-know ​

In plain words: if card numbers pass through your servers, a large security standard applies to all of them. Let the PSP collect the card in its own iframe or page, receive a token instead, and most of the standard stops applying to you.

Common misunderstanding: "We don't store cards, so PCI does not apply." Transmitting or processing a PAN (even only in memory, or in a log line) puts the system in scope. The Before.php controller posts card_number to the server and logs it with the CVV: that is SAQ D territory (the full assessment), and logging the CVV is never allowed. Stripe: merchants handling untokenized PANs "might be required to meet more than 300 security controls in PCI DSS".

Definition: PCI DSS (current version v4.0.1) applies to systems that store, process or transmit cardholder data. A Self-Assessment Questionnaire (SAQ) is the validation tool for merchants; SAQ A "includes only those PCI DSS requirements applicable to merchants with account data functions completely outsourced to PCI DSS validated and compliant third parties"; such merchants "do not store, process, or transmit any account data in electronic form on their systems or premises". Since the January 2025 SAQ A, merchants must "confirm their site is not susceptible to attacks from scripts that could affect the merchant’s e-commerce system(s)" (requirements 6.4.3 and 11.6.1 were removed from SAQ A, not from PCI DSS). Who must validate how is set by "brands, acquirers, payment facilitators" (the compliance enforcing entities), not by PCI SSC. Tokenization replaces the PAN with a reference (pm_... on Stripe) that is useless outside the PSP. Card vaulting is storing cards for later use; with a PSP, the PSP's vault holds the PAN and you hold the token and a stable card fingerprint. Network tokens are issued by the card network itself: Visa Token Service works "By substituting Visa card numbers with tokens", and network tokens can stay valid when the physical card is reissued (Visa describes refreshing outdated expiry dates during provisioning). Stripe "is certified annually by an independent PCI Qualified Security Assessor (QSA) as a PCI Level 1 Service Provider".

text
     Browser (your page)            PSP iframe (stripe.com origin)       Your server            PSP
1    loads checkout from your origin + Stripe.js (CSP allowlists only Stripe's origins)
2                                   customer types PAN, expiry, CVC
3                                   PAN -> PSP over TLS --------------------------------------> vault
4                                   <- pm_123 (token)
5    POST /orders/42/charge {payment_method: pm_123} --------> server sees only pm_123
6                                                              confirm(pm_123) ------------> charge
     Your servers never see the PAN: SAQ A (if all other eligibility criteria hold)

Real scenario: a startup that built its own card form and discovers the PCI cost at its first enterprise deal; a support tool that echoes the full request body into logs; a migration between PSPs that needs a PAN export from one vault to the other (arranged between the PSPs, never through you); a script-injection (Magecart-style) attack on the checkout page, which is why the script criterion was added (see OWASP Top 10).

What provides it:

IntegrationCard data on your serversTypical SAQNotes
PSP-hosted payment page (Stripe Checkout, Adyen Hosted Checkout)NoSAQ ARedirect; least work
PSP fields in an iframe (Stripe Payment Element, Adyen Drop-in)NoSAQ A (with the script eligibility criterion)Your page hosts the iframe: protect your scripts
JavaScript that posts directly to the PSP from your own form fieldsNot stored, but your page controls the fieldsNot SAQ A: the account data functions are not "completely outsourced"; ask your acquirer which SAQ appliesYour page can be tampered with
Card form posting to your serverYesSAQ DAvoid
Network tokens via the PSPNoSame as the integrationBetter authorization rates and card updates (vendor claims; not measured here)

Fix / how to use it: collect cards only in PSP iframes or pages; send only tokens to the server; keep a Content Security Policy for the checkout page; never log request bodies on payment routes; store the PSP customer id and payment method id, never the PAN; secrets (API keys, webhook secrets) in a secret manager (Cryptography in Practice).

Fraud and the risk engine: fraud score, velocity rules, device fingerprint Important ​

In plain words: before charging, a risk engine looks at the payment (amount, card, device, IP, history), computes a fraud score and applies rules, then decides: allow, ask for 3-D Secure, send to a human, or block. It must decide within the checkout's latency budget.

Common misunderstanding: "Block everything risky." Every block of a real customer is lost revenue and a support ticket; every review costs a human's time. The goal is the cheapest action that is safe enough, which is often 3DS step-up. The second wrong belief: "the ML model decides". Rules still run first for hard facts (a card seen on 20 devices in 10 minutes), and the engine must still decide when the model times out.

Definition: a risk engine combines features (card fingerprint, BIN country vs IP country, account age, device fingerprint from the checkout SDK, email, history), velocity rules (counters per card, device, IP, email in sliding windows: the defence against card testing), an ML fraud score, allowlists and blocklists, and four actions. Stripe Radar's rules "take four actions": request 3DS, allow, block, review; its risk score "ranges from 0–99" and "By default, a score of 65 or above indicates elevated risk, while a score of 75 or above indicates high risk"; elevated-risk payments can go to the manual review queue ("placed it in your manual review queue"). Adyen risk management uses risk profiles with custom rules, ML rules and post-authorization rules, with backtesting.

text
     Checkout latency budget ~300 ms; model budget 50 ms
1    t=0    features: card fp_a, device dev_bot, IP 203.0.113.7, amount 1.00 USD
2    t=1    velocity: dev_bot has seen 7 distinct cards in 10 min        -> rule card_testing: block
3    t=2    model call starts (50 ms budget)
4    t=52   model late -> score = -1, reason model_timeout:rules_only
5    t=52   decision: block, reasons [card_testing..., model_timeout:rules_only]
6           store decision + reasons with the payment (disputes, tuning, audits)

Real scenario: card testing bots running hundreds of 1-dollar charges; account takeover followed by a large order to a new address; a reshipper address shared by many cards; legitimate travellers whose card country differs from their IP country (step up, do not block); a review queue that grows faster than the team can work it during a sale.

What provides it:

ProductScoreRulesActionsReview
Stripe Radar0–99; 65+ elevated, 75+ high by defaultCustom rules (plan dependent), allow/block listsAllow, block, review, request 3DSManual review queue (plan dependent)
Adyen risk managementRisk evaluation per payment, configured by risk profilesCustom, ML and post-authorization rules; backtest"an action to block, allow, or review the transaction"; dynamic 3D SecureCase management "to manually review certain transactions"
This chapter's fraud enginePluggable Scorer with a hard budgetOrdered rules, velocity countersallow, request_3ds, review, blockDecision with reasons

Fix / how to use it: fraud.Engine: velocity per device/card/IP, rule ranking (block > review > 3DS > allow), Radar-like thresholds, step-up when the card supports 3DS, a 50 ms model budget with rules-only fallback, reasons stored for every decision. Rate limiting on the checkout endpoint (Rate Limiting) is the first velocity rule.

Declines, retries, dunning and smart retries Good to know ​

In plain words: when a subscription renewal is declined, some declines may succeed later (no money today) and some never will (stolen card). Dunning is the process of retrying the soft ones on a schedule and asking the customer to update the card for the hard ones.

Common misunderstanding: "Retry every failed renewal every hour." Retrying a hard decline is pointless and can harm your standing with issuers and networks; retrying a soft decline too often looks like card testing. Stripe states that for its hard decline codes it "can’t automatically retry a payment".

Definition: a soft decline (insufficient_funds, try_again_later, processing_error) may succeed later; a hard decline needs a new payment method. Stripe's subscription retries treat these codes as hard: incorrect_number, lost_card, pickup_card, stolen_card, revocation_of_authorization, revocation_of_all_authorizations, authentication_required, highest_risk_level, transaction_not_allowed. Smart retries choose retry times with a model; Stripe "enables Smart Retries by default and configures it for up to 8 retries within 2 weeks" for new accounts, and a custom schedule allows "up to three retries". Dunning also includes e-mails, an "update your card" page and a final action (cancel the subscription or mark it unpaid).

text
     Day   Attempt   Decline code          Dunning decision (dunning.Default)
1    0     1         insufficient_funds    soft -> retry in 1 day, e-mail "please check your card"
2    1     2         insufficient_funds    soft -> retry in 2 days
3    3     3         insufficient_funds    soft -> retry in 4 days
4    7     4         insufficient_funds    soft -> retry in 6 days
5    13    5         insufficient_funds    attempt cap reached (5 attempts, inside 14 days) -> exhausted, cancel
     Day 0 alternative: stolen_card -> hard -> no retry, ask for a new payment method

Real scenario: monthly SaaS renewals failing on payday-dependent cards; expired cards (the network's card updater or network tokens can refresh them); an off-session renewal that hits authentication_required and needs the customer to come back.

What provides it:

ProductRetry engineHard declinesCustomer contact
Stripe BillingSmart Retries (AI-chosen times) or custom scheduleRetries continue to be scheduled but execute only with a new payment methodRevenue recovery e-mails, invoice.payment_failed
Laravel CashierUses Stripe BillingSame as StripeIncompletePayment, hasIncompletePayment()
This chapter's dunning packageFixed schedule with attempt and duration capsClassify = Stripe's hard listNotify flag

Fix / how to use it: classify by decline code, cap attempts and duration, send one e-mail on the first failure and one on exhaustion, and never put a hard decline back in the retry queue.

Multi-PSP routing and failover Good to know ​

In plain words: some companies use two PSPs to survive an outage or to send each payment to the one most likely to approve it. The rule that keeps this safe: switch PSP only when the first one provably did nothing.

Common misunderstanding: "Failover on any error." After a timeout the first PSP may have charged the card. Failing over charges it a second time at the second PSP, and no idempotency key can help, because the two PSPs do not share keys.

Definition: a router chooses a PSP per payment (by currency, card BIN, cost, health); each try is a separate attempt with its own provider key; an attempt can be sent, done or unknown; only a done-without-effect attempt allows a new attempt elsewhere. Tokens are PSP-specific unless you use network tokens or a third-party vault, which is the main cost of multi-PSP.

text
     Router                     Stripe                       Adyen
1    attempt 1 key pi_3:attempt:1 -> connection refused (nothing processed)
2    attempt 1 = done (no effect)
3    attempt 2 key pi_3:attempt:2 ----------------------->  approved
4    ledger: D psp_receivable:adyen:GBP / C sales:GBP  (booked against the PSP that charged)

Real scenario: a PSP regional outage during a sale; an acquirer with low approval rates for one country; negotiating fees by moving volume.

What provides it:

ConcernSingle PSPTwo PSPs
OutageWait or degradeFail over on provably-not-processed errors
Card storagePSP vaultNetwork tokens, a third-party vault or one vault per PSP
ReconciliationOne fileTwo files, two payout schedules, per-PSP receivable accounts
CodeOne adapterPSP interface, routing order, attempt table

Fix / how to use it: Service.Confirm and routeFrom in payment/service.go: unknown attempts stay pinned to their PSP; receivables are per PSP (psp_receivable:adyen:GBP).

Libraries: Laravel Cashier, Stripe PHP SDK, stripe-go Good to know ​

In plain words: use the PSP's official SDK for API calls and webhook verification; in Laravel, Laravel Cashier wraps the Stripe PHP SDK for customers, payment methods, one-off charges and subscriptions.

Common misunderstanding: "Cashier handles everything, including our ledger and idempotency." Cashier syncs Stripe objects into its tables via webhooks and gives you charge(), pay(), refund(), but it does not post double-entry journal entries, reconcile settlement files or expose an idempotency key on charge(). Drop to the Stripe client for that.

Definition and facts (from the docs read):

LibraryFactsUse on this page
Laravel Cashier (Stripe)composer.json requires stripe/stripe-php ^17.4 to ^21.0 and illuminate/* ^12.0|^13.0; "Cashier uses the Stripe API version pinned by your installed version of the stripe/stripe-php SDK" (21.x → API version 2026-08-26.dahlia); amounts "in the lowest denominator"; webhook controller at /stripe/webhook, php artisan cashier:webhook creates the endpoint; IncompletePayment + cashier.payment route for SCACheckoutController
Stripe PHP SDK (stripe/stripe-php)\Stripe\Webhook::constructEvent($payload, $sigHeader, $secret, $tolerance = self::DEFAULT_TOLERANCE) with DEFAULT_TOLERANCE = 300; request option idempotency_key becomes the Idempotency-Key header (Util/RequestOptions.php); README: "even if you locally timeout, the request on Stripe's side can still complete"Cashier::stripe()->paymentIntents->create($params, ['idempotency_key' => ...])
stripe-go (github.com/stripe/stripe-go/v87)go.mod says go 1.24; README: supports "Go 1.24+"; stripe.NewClient(apiKey), sc.V1PaymentIntents...; automatic retries "up to two" with idempotency keys "always added"; MaxNetworkRetries configurable; webhook.ConstructEvent with DefaultTolerance 300 sNamed in the Go angle; this chapter's module is stdlib only so its tests run offline
AdyenHMAC verification as documented; Adyen server libraries include "a validator to verify the HMAC signature"Mapping tables

Fix / how to use it: in production, use webhook.ConstructEvent (Go) or \Stripe\Webhook::constructEvent (PHP) instead of the hand-written verifiers, keep the SDK's automatic retries and your own derived idempotency keys, and pin the SDK major version because it pins the Stripe API version.

Mechanics ​

The request flow, exactly ​

text
     Step  Where              What                                                     Failure handling
1     1    checkout API       require Idempotency-Key header (400 if missing)           client retries with the same key
2     2    payment service    idempotency_keys INSERT (merchant, key, fingerprint)      replay 2xx / 409 in flight / 422 mismatch
3     3    payment service    payments INSERT, UNIQUE (merchant_id, order_id)           second key for same order -> conflict
4     4    risk engine        decide within 50 ms (rules-only fallback)                 block -> 402 to client, no PSP call
5     5    payment service    payment_attempts INSERT (psp, psp_idem_key, state=sent)   crash here: attempt resumed later
6     6    PSP call           timeout << checkout budget, provider key                  unknown -> lookup / same key
7     7    one transaction    payments status + version, ledger entries, outbox row     deferred D = C check at COMMIT
8     8    response           201 with intent status; key -> completed with body        replayed for 24 h+
9     9    webhook            verify, inbox, 200, queued job                            dead-letter after the last try
10   10    reconciliation     daily file vs ledger vs bank                              tickets, fixes as new entries

Status codes and errors you will see ​

SourceCode / messageMeaningWhat to do
Your API (IETF draft)400 missing Idempotency-KeyRequired key absentClient adds a key
Your API (IETF draft)409 ConflictSame key still processingWait, retry with the same key
Your API (IETF draft)422 Unprocessable ContentKey reused with a different payloadClient bug; new key only for a new intent
Stripe500 (cached with the key in API v1)"indeterminate"Resolve the outcome before any new key
StripeStripe-Should-Retry headerExplicit retry guidanceFollow it
Stripe declinecard_declined with decline_code such as insufficient_funds, do_not_honor, generic_declineIssuer declinedAsk for another card or retry later (soft)
Stripe hard declinestolen_card, lost_card, pickup_card, incorrect_number, ...Will not succeedNew payment method; never auto-retry
Stripeauthentication_requiredIssuer wants SCABring the customer on-session for 3DS
Adyen503 from the idempotency layer"Idempotent processing relies on this data store being available"Adyen: fall back to non-idempotent processing only deliberately
stripe-gowebhook.ErrNoValidSignature, webhook.ErrTooOldBad signature / outside tolerance400, alert if frequent
This chapterwebhook: timestamp outside tolerance, webhook: no v1 signature matchesSame in the hand-written verifier400
This chapterledger: debits != credits, ledger is append-only (ledger_entries)Unbalanced posting / UPDATE attemptBug: fix the code, post a reversal
LaravelDomainException: invalid transition succeeded -> processingStale event in PaymentStatus::to()Ack and ignore
This chapterpayment: another operation on this payment is in progress (ErrInFlight)A second Confirm/Capture/Refund while one is running409; retry later with the same key
This chapterpayment: PSP result not booked, retry or reconcile (ErrUnbooked)The PSP moved money, the posting failed; the intent did not changeFix the cause; the next Confirm, Capture or Refund with the same key books the stored result without calling the PSP again
This chapterpayment: outcome unknown past the resend window, reconcile (ErrNeedsReconciliation)An attempt, capture or refund is still unknown after ResendWindowNever resend: look it up at the PSP or in the settlement file, then resolve
This chapterpayment: amount mismatch, needs reconciliation (ErrMismatch)Webhook and capture (or two captures) disagreeStop; a human or reconciliation decides
This chapterpayment: this order already has a payment (ErrDuplicateOrder)Second client key for one order409; reuse the existing payment

Knobs ​

KnobValue used hereWhereWhy
PSP call timeout200 ms in tests; a few seconds in productionNewService(callTimeout)Must fit the checkout budget and leave time for lookup
Idempotency key retention24 hidem.New(24*time.Hour), expires_at defaultAt least Stripe's window; Adyen keeps 7 to 14 days
Webhook tolerance300 sVerifier.Tolerance, TOLERANCE_SECONDSStripe libraries' default; > 0 always
Webhook secretsCurrent + previousSecrets, services.stripe.webhook_secretsSecret roll up to 7 days
Queue retries#[Tries(8)], #[Backoff([10, 30, 60, 300])]ProcessStripeEventLast value repeats for later attempts
Fraud model budget50 msEngine.ModelBudgetDecide on rules if the model is late
Fraud thresholdsreview 65, block 75Engine.ReviewAt, BlockAtRadar's documented defaults
Velocity window10 minNewVelocity(10 * time.Minute)Card testing happens in bursts
Dunningretry after 1, 2, 4, 6 days (days 1, 3, 7, 13); 5 attempts; 14 daysdunning.Default()Bounded by attempts and duration
Saga undo tries3Orchestrator.UndoTriesThen dead-letter
Authorization validityPer payment: payments.capture_before from the PSP (Stripe: Visa MIT 4 days 18 hours, most online CIT 7 days)ProcessStripeEvent stores it on requires_captureSchedule capture or void against this timestamp, never a fixed window
DB::transaction attempts3LedgerService::postRetries the closure on deadlock

The SQL that matters ​

The full schema is imported in Laravel. These are the statements each step runs (PostgreSQL 16+):

sql
-- 2. claim the client's key (one row wins; the loser reads it and replays or returns 409/422)
INSERT INTO idempotency_keys (merchant_id, key, fingerprint, status)
VALUES ($1, $2, $3, 'in_progress')
ON CONFLICT (merchant_id, key) DO NOTHING
RETURNING key;

-- 5. one attempt row per PSP call; the provider key is unique and reused on every retry
INSERT INTO payment_attempts (payment_id, psp, psp_idem_key, state)
VALUES ($1, 'stripe', $1 || ':attempt:' || $2, 'sent');

-- 7. state change with optimistic locking, ledger and outbox in ONE transaction
BEGIN;
UPDATE payments
   SET status = 'succeeded', amount_received = $2, version = version + 1, updated_at = now()
 WHERE id = $1 AND version = $3 AND status NOT IN ('succeeded', 'canceled');   -- forward progress only
-- 0 rows: someone else moved it first -> ROLLBACK, reload and re-evaluate
INSERT INTO journal_transactions (id, description) VALUES ('capture:' || $1, 'capture ' || $1)
ON CONFLICT (id) DO NOTHING
RETURNING id;                         -- 0 rows: already posted -> ROLLBACK, nothing below runs
SELECT id FROM ledger_accounts
 WHERE id IN ('psp_receivable:stripe:USD', 'sales:USD') ORDER BY id FOR UPDATE;  -- fixed lock order
INSERT INTO ledger_entries (transaction_id, account_id, direction, amount, currency) VALUES
  ('capture:' || $1, 'psp_receivable:stripe:USD', 'D', $2, 'USD'),
  ('capture:' || $1, 'sales:USD',                 'C', $2, 'USD');
-- the cached normal-side balances move with the entries (asset debit +, revenue credit +);
-- the "cached = derived" query below returns no rows only because of this statement
UPDATE ledger_accounts SET balance = balance + $2, version = version + 1
 WHERE id IN ('psp_receivable:stripe:USD', 'sales:USD');
INSERT INTO outbox (event_id, topic, aggregate_id, payload)
VALUES ('evt_' || $1 || '_v' || ($3 + 1), 'payments.payment_succeeded', $1, jsonb_build_object('id', $1));
COMMIT;                               -- deferred trigger: debits = credits per currency

-- capture/void scheduler: due holds, by the PSP's own expiry (partial index payments_capture_due)
SELECT id, capture_before FROM payments
 WHERE status = 'requires_capture' AND capture_before < now() + interval '24 hours'
 ORDER BY capture_before;

-- 9. webhook idempotency table: store first, process later
INSERT INTO webhooks_inbox (psp, event_id, event_type, object_id, payload)
VALUES ('stripe', $1, $2, $3, $4)
ON CONFLICT (psp, event_id) DO NOTHING;

-- open attempts for the sweep (partial index payment_attempts_open):
--   unbooked -> book psp_result, never resend; sent/unknown inside the window -> resend the same key;
--   sent/unknown past the window (23 h, below Stripe's 24 h key retention) -> reconcile, never resend
SELECT payment_id, psp, psp_idem_key, state, psp_result,
       first_sent_at < now() - interval '23 hours' AS past_resend_window
  FROM payment_attempts
 WHERE state IN ('sent', 'unknown', 'unbooked') AND first_sent_at < now() - interval '5 minutes';

-- a balance is a sum, and must equal the cached one
SELECT a.id, a.balance AS cached,
       sum(CASE e.direction WHEN 'D' THEN e.amount ELSE -e.amount END)
         * CASE WHEN a.kind IN ('asset', 'expense') THEN 1 ELSE -1 END AS derived
  FROM ledger_accounts a JOIN ledger_entries e ON e.account_id = a.id
 GROUP BY a.id, a.balance, a.kind
HAVING a.balance <> sum(CASE e.direction WHEN 'D' THEN e.amount ELSE -e.amount END)
         * CASE WHEN a.kind IN ('asset', 'expense') THEN 1 ELSE -1 END;   -- must return no rows

-- trial balance: zero per currency, always
SELECT currency, sum(CASE direction WHEN 'D' THEN amount ELSE -amount END) FROM ledger_entries GROUP BY currency;

-- reconciliation: charges settled by the PSP that we never booked, or booked differently
-- (provider identity = psp + intent id; amount, currency and status compared)
SELECT s.psp_reference, s.gross, s.currency, p.id, p.amount_received, p.currency AS our_currency, p.status
  FROM settlement_lines s
  LEFT JOIN payments p ON p.stripe_payment_intent_id = s.psp_reference AND p.psp = s.psp
 WHERE s.psp = $1 AND s.batch_id = $2 AND s.line_type = 'charge'
   AND (p.id IS NULL OR p.amount_received <> s.gross OR p.currency <> s.currency OR p.status <> 'succeeded');

-- refunds the PSP settled that we did not book, matched through the refund's payment
SELECT s.psp_reference, s.gross FROM settlement_lines s
  LEFT JOIN refunds r ON r.stripe_refund_id = s.psp_reference
  LEFT JOIN payments p ON p.id = r.payment_id AND p.psp = s.psp
 WHERE s.psp = $1 AND s.batch_id = $2 AND s.line_type = 'refund'
   AND (p.id IS NULL OR r.state <> 'succeeded' OR r.amount <> abs(s.gross) OR r.currency <> s.currency);

These statements were written against the schema file and checked by reading. sql/schema.sql and the Laravel migration are kept in sync on purpose (same tables, columns and recovery states: psp_result, first_sent_at, refused/unbooked, needs_reconciliation; the migration also seeds the ledger accounts the postings use), so every query here runs against either; PostgreSQL is not installed on the machine this chapter was built on, so they were not executed.

Go ​

The Go module (academy/payment-processing-architecture, go 1.24) is standard library only, one package per idea, so every test runs offline and with -race. stripe-go v87 also declares go 1.24 and could replace the PSP fake with a real adapter; it was left out so the tests need no network and no API key.

Before ​

Float money, a blind retry loop that charges again after a timeout, a mutable balance and an e-mail that a crash loses:

go
// Package main shows the payment handler most teams write first.
// It compiles and "works" in a demo; every comment marks a production bug.
package main

import (
	"errors"
	"fmt"
	"sync"
)

type gateway struct{ charges int }

// Charge pretends to call the PSP. The second call fails after the money moved,
// which is exactly what a timeout looks like from the caller's side.
func (g *gateway) Charge(amount float64) error {
	g.charges++
	if g.charges == 1 {
		return errors.New("i/o timeout") // the charge happened, the answer was lost
	}
	return nil
}

type shop struct {
	mu      sync.Mutex
	balance float64 // float money: 0.1 + 0.2 != 0.3
	gw      *gateway
}

// Pay has no idempotency key, no state machine, no ledger, no outbox.
func (s *shop) Pay(amount float64) error {
	for attempt := 0; attempt < 3; attempt++ { // blind retry: a second real charge
		if err := s.gw.Charge(amount); err != nil {
			continue
		}
		s.mu.Lock()
		s.balance += amount // a mutable balance: no history, no audit, no reconciliation
		s.mu.Unlock()
		// "send the receipt e-mail" here: lost if the process dies right now
		return nil
	}
	return errors.New("payment failed")
}

func main() {
	s := &shop{gw: &gateway{}}
	_ = s.Pay(0.1)
	_ = s.Pay(0.2)
	fmt.Printf("charges sent to PSP: %d (customer paid twice for the first order)\n", s.gw.charges)
	fmt.Printf("balance: %.17f (expected 0.3)\n", s.balance)
}

Running it prints charges sent to PSP: 3 (customer paid twice for the first order) and balance: 0.30000000000000004 (expected 0.3).

After ​

Money as integer minor units with ISO 4217 exponents, strict parsing, allocation and half-even conversion:

go
// Package money stores amounts as integers in the currency's minor unit.
// 10.99 USD is Money{Amount: 1099, Currency: "USD"}; 500 JPY is {500, "JPY"}.
package money

import (
	"errors"
	"fmt"
	"math"
	"math/big"
	"strings"
)

// exponents is the number of minor-unit digits (ISO 4217). Extend from your PSP's table.
var exponents = map[string]int{
	"USD": 2, "EUR": 2, "GBP": 2, "CAD": 2, "AUD": 2,
	"JPY": 0, "KRW": 0, "VND": 0,
	"BHD": 3, "KWD": 3, "OMR": 3, "JOD": 3,
}

var (
	ErrUnknownCurrency  = errors.New("money: unknown currency")
	ErrCurrencyMismatch = errors.New("money: currency mismatch")
	ErrOverflow         = errors.New("money: int64 overflow")
	ErrPrecision        = errors.New("money: more decimals than the currency allows")
	ErrInvalid          = errors.New("money: invalid amount")
)

// Money is an immutable value: never a float.
type Money struct {
	Amount   int64
	Currency string
}

// Exponent returns the minor-unit digits of a currency.
func Exponent(currency string) (int, error) {
	e, ok := exponents[currency]
	if !ok {
		return 0, fmt.Errorf("%w: %q", ErrUnknownCurrency, currency)
	}
	return e, nil
}

// New validates the currency.
func New(minor int64, currency string) (Money, error) {
	if _, err := Exponent(currency); err != nil {
		return Money{}, err
	}
	return Money{Amount: minor, Currency: currency}, nil
}

// Parse turns a decimal string ("10.99") into minor units without floats.
func Parse(s, currency string) (Money, error) {
	exp, err := Exponent(currency)
	if err != nil {
		return Money{}, err
	}
	neg := strings.HasPrefix(s, "-")
	s = strings.TrimPrefix(s, "-")
	whole, frac, _ := strings.Cut(s, ".")
	if whole == "" || len(frac) > exp {
		if len(frac) > exp {
			return Money{}, ErrPrecision
		}
		return Money{}, ErrInvalid
	}
	if !digits(whole) || !digits(frac) {
		return Money{}, ErrInvalid
	}
	frac += strings.Repeat("0", exp-len(frac))
	n, ok := new(big.Int).SetString(whole+frac, 10)
	if !ok || !n.IsInt64() {
		return Money{}, ErrInvalid
	}
	v := n.Int64()
	if neg {
		v = -v
	}
	return Money{Amount: v, Currency: currency}, nil
}

func digits(s string) bool {
	for _, c := range s {
		if c < '0' || c > '9' {
			return false
		}
	}
	return true
}

// String renders "10.99 USD".
func (m Money) String() string {
	exp, _ := Exponent(m.Currency)
	sign, a := "", m.Amount
	if a < 0 {
		sign, a = "-", -a
	}
	if exp == 0 {
		return fmt.Sprintf("%s%d %s", sign, a, m.Currency)
	}
	p := int64(math.Pow10(exp))
	return fmt.Sprintf("%s%d.%0*d %s", sign, a/p, exp, a%p, m.Currency)
}

// Add returns m+o; both must share a currency.
func (m Money) Add(o Money) (Money, error) {
	if m.Currency != o.Currency {
		return Money{}, ErrCurrencyMismatch
	}
	s := m.Amount + o.Amount
	if (o.Amount > 0 && s < m.Amount) || (o.Amount < 0 && s > m.Amount) {
		return Money{}, ErrOverflow
	}
	return Money{Amount: s, Currency: m.Currency}, nil
}

// Sub returns m-o with checked subtraction (not negate-then-add, which fails for
// o = MinInt64 even when the result fits: -1 - MinInt64 = MaxInt64).
func (m Money) Sub(o Money) (Money, error) {
	if m.Currency != o.Currency {
		return Money{}, ErrCurrencyMismatch
	}
	d := m.Amount - o.Amount
	if (o.Amount > 0 && d > m.Amount) || (o.Amount < 0 && d < m.Amount) {
		return Money{}, ErrOverflow
	}
	return Money{Amount: d, Currency: m.Currency}, nil
}

// Allocate splits m by ratios so the parts always sum to m (largest remainder:
// leftover minor units go to the first parts). Splitting 100 three ways gives 34, 33, 33.
func (m Money) Allocate(ratios ...int64) ([]Money, error) {
	var total int64
	for _, r := range ratios {
		if r < 0 {
			return nil, ErrInvalid
		}
		total += r
	}
	if total == 0 {
		return nil, ErrInvalid
	}
	parts := make([]Money, len(ratios))
	var used int64
	for i, r := range ratios {
		share := new(big.Int).Mul(big.NewInt(m.Amount), big.NewInt(r))
		share.Quo(share, big.NewInt(total))
		parts[i] = Money{Amount: share.Int64(), Currency: m.Currency}
		used += parts[i].Amount
	}
	step := int64(1)
	if m.Amount < 0 {
		step = -1
	}
	for i := 0; used != m.Amount; i = (i + 1) % len(parts) {
		parts[i].Amount += step
		used += step
	}
	return parts, nil
}

// Convert applies an FX rate given as an exact decimal string ("0.9235" EUR per USD)
// and rounds half-to-even (banker's rounding) into the target minor unit.
func Convert(m Money, to, rate string) (Money, error) {
	fromExp, err := Exponent(m.Currency)
	if err != nil {
		return Money{}, err
	}
	toExp, err := Exponent(to)
	if err != nil {
		return Money{}, err
	}
	r, ok := new(big.Rat).SetString(rate)
	if !ok || r.Sign() <= 0 {
		return Money{}, ErrInvalid
	}
	v := new(big.Rat).SetInt64(m.Amount)
	v.Mul(v, r)
	scale := new(big.Rat).SetFrac(
		new(big.Int).Exp(big.NewInt(10), big.NewInt(int64(toExp)), nil),
		new(big.Int).Exp(big.NewInt(10), big.NewInt(int64(fromExp)), nil))
	v.Mul(v, scale)
	out := roundHalfEven(v)
	if !out.IsInt64() {
		return Money{}, ErrOverflow
	}
	return Money{Amount: out.Int64(), Currency: to}, nil
}

func roundHalfEven(v *big.Rat) *big.Int {
	num, den := new(big.Int).Set(v.Num()), v.Denom()
	neg := num.Sign() < 0
	num.Abs(num)
	q, r := new(big.Int).QuoRem(num, den, new(big.Int))
	twice := new(big.Int).Mul(r, big.NewInt(2))
	switch twice.Cmp(den) {
	case 1:
		q.Add(q, big.NewInt(1))
	case 0:
		if q.Bit(0) == 1 {
			q.Add(q, big.NewInt(1))
		}
	}
	if neg {
		q.Neg(q)
	}
	return q
}
go
package money

import (
	"errors"
	"math"
	"testing"
)

func TestParseAndString(t *testing.T) {
	cases := []struct {
		in, cur, out string
		minor        int64
	}{
		{"10.99", "USD", "10.99 USD", 1099},
		{"10.9", "USD", "10.90 USD", 1090},
		{"500", "JPY", "500 JPY", 500},
		{"1.234", "BHD", "1.234 BHD", 1234},
		{"-0.05", "EUR", "-0.05 EUR", -5},
	}
	for _, c := range cases {
		m, err := Parse(c.in, c.cur)
		if err != nil || m.Amount != c.minor || m.String() != c.out {
			t.Fatalf("Parse(%q,%s) = %v %v", c.in, c.cur, m, err)
		}
	}
	if _, err := Parse("10.999", "USD"); !errors.Is(err, ErrPrecision) {
		t.Fatalf("want ErrPrecision, got %v", err)
	}
	for _, bad := range []string{"--5", "1e3", "+5", "1,00", " 5"} {
		if _, err := Parse(bad, "USD"); !errors.Is(err, ErrInvalid) {
			t.Fatalf("Parse(%q) = %v, want ErrInvalid", bad, err)
		}
	}
	if _, err := Parse("1.5", "JPY"); !errors.Is(err, ErrPrecision) {
		t.Fatalf("JPY has no minor unit, got %v", err)
	}
}

func TestFloatTrapIsGone(t *testing.T) {
	a, _ := Parse("0.10", "USD")
	b, _ := Parse("0.20", "USD")
	s, _ := a.Add(b)
	if s.Amount != 30 {
		t.Fatalf("0.10 + 0.20 = %v", s)
	}
}

func TestCurrencyMismatch(t *testing.T) {
	if _, err := (Money{100, "USD"}).Add(Money{100, "EUR"}); !errors.Is(err, ErrCurrencyMismatch) {
		t.Fatalf("got %v", err)
	}
}

func TestAllocateNeverLosesACent(t *testing.T) {
	m := Money{100, "USD"}
	parts, err := m.Allocate(1, 1, 1)
	if err != nil || parts[0].Amount != 34 || parts[1].Amount != 33 || parts[2].Amount != 33 {
		t.Fatalf("got %v %v", parts, err)
	}
	for _, total := range []int64{1, 7, 999, 1_000_001, -101} {
		parts, _ := Money{total, "USD"}.Allocate(70, 20, 10)
		var sum int64
		for _, p := range parts {
			sum += p.Amount
		}
		if sum != total {
			t.Fatalf("allocate %d: parts sum %d", total, sum)
		}
	}
}

func TestConvertHalfEven(t *testing.T) {
	cases := []struct {
		amount   int64
		from, to string
		rate     string
		want     int64
	}{
		{1000, "USD", "EUR", "0.9235", 924},     // 923.5 -> 924 (4 is even)
		{1001, "USD", "EUR", "0.5", 500},        // 500.5 -> 500 (0 is even)
		{1003, "USD", "EUR", "0.5", 502},        // 501.5 -> 502
		{1000, "USD", "JPY", "151.37", 1514},    // 10.00 USD -> 1513.7 JPY -> 1514
		{150000, "JPY", "USD", "0.0066", 99000}, // 990.00 USD
		{1000, "USD", "BHD", "0.376", 3760},
	}
	for _, c := range cases {
		got, err := Convert(Money{c.amount, c.from}, c.to, c.rate)
		if err != nil || got.Amount != c.want {
			t.Fatalf("Convert(%d %s->%s @%s) = %v %v, want %d", c.amount, c.from, c.to, c.rate, got, err, c.want)
		}
	}
}

// Finding 12: negating MinInt64 overflows; Sub must report it.
func TestSubMinInt64Overflows(t *testing.T) {
	if _, err := (Money{0, "USD"}).Sub(Money{math.MinInt64, "USD"}); !errors.Is(err, ErrOverflow) {
		t.Fatalf("got %v, want ErrOverflow", err)
	}
}

// N14: subtraction is checked as subtraction, not as negate-then-add.
func TestSubMinInt64RepresentableResults(t *testing.T) {
	if got, err := (Money{-1, "USD"}).Sub(Money{math.MinInt64, "USD"}); err != nil || got.Amount != math.MaxInt64 {
		t.Fatalf("-1 - MinInt64 = %v %v, want MaxInt64", got.Amount, err)
	}
	if got, err := (Money{math.MinInt64, "USD"}).Sub(Money{math.MinInt64, "USD"}); err != nil || got.Amount != 0 {
		t.Fatalf("MinInt64 - MinInt64 = %v %v, want 0", got.Amount, err)
	}
	if _, err := (Money{math.MaxInt64, "USD"}).Sub(Money{-1, "USD"}); !errors.Is(err, ErrOverflow) {
		t.Fatalf("MaxInt64 - (-1): %v, want ErrOverflow", err)
	}
}

The payment intent state machine with Stripe's status names, capture and refund limits:

go
// Package intent is a payment-intent state machine with Stripe's status names
// (docs.stripe.com/payments/paymentintents/lifecycle). Every change goes through
// one transition table, so an illegal or stale event is an error, not a silent overwrite.
package intent

import (
	"errors"
	"fmt"

	"academy/payment-processing-architecture/money"
)

// Status values copied from the Stripe PaymentIntent lifecycle.
type Status string

const (
	RequiresPaymentMethod Status = "requires_payment_method"
	RequiresConfirmation  Status = "requires_confirmation"
	RequiresAction        Status = "requires_action"
	Processing            Status = "processing"
	RequiresCapture       Status = "requires_capture"
	Succeeded             Status = "succeeded"
	Canceled              Status = "canceled"
)

// Event is what happened: a client call or a PSP answer (sync or webhook).
type Event string

const (
	AttachMethod   Event = "attach_method"
	PSPActionReq   Event = "psp_requires_action" // 3-D Secure challenge
	PSPProcessing  Event = "psp_processing"      // async rails: SEPA, ACH
	PSPAuthorized  Event = "psp_authorized"      // manual capture: hold placed
	PSPSucceeded   Event = "psp_succeeded"
	PSPDeclined    Event = "psp_declined" // back to requires_payment_method, can retry
	Cancel         Event = "cancel"
	AuthExpired    Event = "auth_expired" // hold not captured in time
	CaptureRequest Event = "capture"
)

var transitions = map[Status]map[Event]Status{
	RequiresPaymentMethod: {AttachMethod: RequiresConfirmation, Cancel: Canceled},
	RequiresConfirmation: {
		PSPActionReq: RequiresAction, PSPProcessing: Processing, PSPAuthorized: RequiresCapture,
		PSPSucceeded: Succeeded, PSPDeclined: RequiresPaymentMethod, Cancel: Canceled,
		AttachMethod: RequiresConfirmation,
	},
	RequiresAction: {
		PSPProcessing: Processing, PSPAuthorized: RequiresCapture, PSPSucceeded: Succeeded,
		PSPDeclined: RequiresPaymentMethod, Cancel: Canceled,
	},
	Processing: {PSPSucceeded: Succeeded, PSPDeclined: RequiresPaymentMethod},
	// PSPSucceeded: the capture happened at the PSP (dashboard, another worker) and a
	// verified webhook reports it; the local Capture() path uses CaptureRequest.
	RequiresCapture: {CaptureRequest: Succeeded, PSPSucceeded: Succeeded, Cancel: Canceled, AuthExpired: Canceled},
	Succeeded:       {},
	Canceled:        {},
}

var (
	ErrInvalidTransition = errors.New("intent: invalid transition")
	ErrAmount            = errors.New("intent: invalid amount")
)

// Intent is one attempt to collect one amount for one order.
type Intent struct {
	ID               string
	Amount           int64 // minor units
	Currency         string
	Status           Status
	AmountCapturable int64
	AmountReceived   int64
	AmountRefunded   int64
	Version          int // optimistic-lock counter, bumped on every change
	History          []Status
}

// New starts in requires_payment_method.
func New(id string, amount int64, currency string) (*Intent, error) {
	if amount <= 0 {
		return nil, ErrAmount
	}
	return &Intent{ID: id, Amount: amount, Currency: currency, Status: RequiresPaymentMethod,
		History: []Status{RequiresPaymentMethod}}, nil
}

// Can reports whether ev is legal now.
func (p *Intent) Can(ev Event) bool {
	_, ok := transitions[p.Status][ev]
	return ok
}

// Apply moves the intent or returns ErrInvalidTransition. Capture uses Capture().
func (p *Intent) Apply(ev Event) error {
	if ev == CaptureRequest {
		return fmt.Errorf("%w: use Capture(amount)", ErrInvalidTransition)
	}
	next, ok := transitions[p.Status][ev]
	if !ok {
		return fmt.Errorf("%w: %s --%s-->", ErrInvalidTransition, p.Status, ev)
	}
	switch {
	case next == RequiresCapture:
		p.AmountCapturable = p.Amount
	case next == Succeeded && p.Status == RequiresCapture:
		// the PSP may have captured less than the hold: only Succeed(amount) knows how much
		return fmt.Errorf("%w: use Succeed(amount) from %s", ErrInvalidTransition, p.Status)
	case next == Succeeded:
		p.AmountReceived = p.Amount
	case next == Canceled:
		p.AmountCapturable = 0 // the hold is released
	}
	p.set(next)
	return nil
}

// Succeed records a PSP-reported success with the amount the PSP says it received.
// From requires_capture this is the captured amount (partial capture allowed, <= hold);
// from any other state it must be the full amount. Anything else is refused.
func (p *Intent) Succeed(received int64) error {
	next, ok := transitions[p.Status][PSPSucceeded]
	if !ok {
		return fmt.Errorf("%w: %s --%s-->", ErrInvalidTransition, p.Status, PSPSucceeded)
	}
	if p.Status == RequiresCapture {
		if received <= 0 || received > p.AmountCapturable {
			return ErrAmount
		}
	} else if received != p.Amount {
		return ErrAmount
	}
	p.AmountReceived, p.AmountCapturable = received, 0
	p.set(next)
	return nil
}

// Clone returns an independent copy (the History slice is copied too), so a caller can
// apply a change to the copy and keep it only if the ledger posting succeeds.
func (p *Intent) Clone() *Intent {
	c := *p
	c.History = append([]Status(nil), p.History...)
	return &c
}

// Capture takes amount <= the authorized hold. A partial capture releases the rest:
// for most card payments only one capture is allowed (Stripe "place a hold" docs).
func (p *Intent) Capture(amount int64) error {
	if p.Status != RequiresCapture {
		return fmt.Errorf("%w: capture in %s", ErrInvalidTransition, p.Status)
	}
	if amount <= 0 || amount > p.AmountCapturable {
		return ErrAmount
	}
	p.AmountReceived, p.AmountCapturable = amount, 0
	p.set(Succeeded)
	return nil
}

// Refund is a new money movement on a succeeded intent; the status stays succeeded.
// Refunds are tracked separately and may never exceed what was received.
func (p *Intent) Refund(amount int64) error {
	if p.Status != Succeeded {
		return fmt.Errorf("%w: refund in %s", ErrInvalidTransition, p.Status)
	}
	total, err := money.Money{Amount: p.AmountRefunded, Currency: p.Currency}.Add(money.Money{Amount: amount, Currency: p.Currency})
	if amount <= 0 || err != nil || total.Amount > p.AmountReceived { // checked: no wrap-around
		return ErrAmount
	}
	p.AmountRefunded = total.Amount
	p.Version++
	return nil
}

func (p *Intent) set(s Status) {
	p.Status = s
	p.Version++
	p.History = append(p.History, s)
}

// Terminal reports succeeded or canceled.
func (p *Intent) Terminal() bool { return p.Status == Succeeded || p.Status == Canceled }
go
package intent

import (
	"errors"
	"math"
	"testing"
)

func mustNew(t *testing.T) *Intent {
	t.Helper()
	p, err := New("pi_1", 1099, "USD")
	if err != nil {
		t.Fatal(err)
	}
	return p
}

func TestHappyPathWith3DS(t *testing.T) {
	p := mustNew(t)
	for _, ev := range []Event{AttachMethod, PSPActionReq, PSPSucceeded} {
		if err := p.Apply(ev); err != nil {
			t.Fatal(err)
		}
	}
	if p.Status != Succeeded || p.AmountReceived != 1099 || p.Version != 3 {
		t.Fatalf("got %+v", p)
	}
}

func TestDeclineReturnsToRequiresPaymentMethod(t *testing.T) {
	p := mustNew(t)
	_ = p.Apply(AttachMethod)
	if err := p.Apply(PSPDeclined); err != nil || p.Status != RequiresPaymentMethod {
		t.Fatalf("got %s %v", p.Status, err)
	}
	// the customer can retry with another card on the same intent
	if err := p.Apply(AttachMethod); err != nil {
		t.Fatal(err)
	}
}

func TestManualCaptureAndPartialCapture(t *testing.T) {
	p := mustNew(t)
	_ = p.Apply(AttachMethod)
	_ = p.Apply(PSPAuthorized)
	if p.Status != RequiresCapture || p.AmountCapturable != 1099 {
		t.Fatalf("got %+v", p)
	}
	if err := p.Capture(2000); !errors.Is(err, ErrAmount) {
		t.Fatalf("over-capture must fail, got %v", err)
	}
	if err := p.Capture(750); err != nil {
		t.Fatal(err)
	}
	if p.Status != Succeeded || p.AmountReceived != 750 || p.AmountCapturable != 0 {
		t.Fatalf("got %+v", p)
	}
	if err := p.Capture(349); !errors.Is(err, ErrInvalidTransition) {
		t.Fatalf("second capture must fail, got %v", err)
	}
}

func TestVoidAndExpiry(t *testing.T) {
	for _, ev := range []Event{Cancel, AuthExpired} {
		p := mustNew(t)
		_ = p.Apply(AttachMethod)
		_ = p.Apply(PSPAuthorized)
		if err := p.Apply(ev); err != nil || p.Status != Canceled || p.AmountCapturable != 0 {
			t.Fatalf("%s: got %+v %v", ev, p, err)
		}
	}
}

func TestStaleWebhookIsRejectedNotApplied(t *testing.T) {
	p := mustNew(t)
	_ = p.Apply(AttachMethod)
	_ = p.Apply(PSPSucceeded)
	// a late "requires_action" webhook arrives after "succeeded": must not move backwards
	if err := p.Apply(PSPActionReq); !errors.Is(err, ErrInvalidTransition) {
		t.Fatalf("got %v", err)
	}
	if p.Status != Succeeded {
		t.Fatalf("status changed to %s", p.Status)
	}
}

func TestRefundsNeverExceedReceived(t *testing.T) {
	p := mustNew(t)
	_ = p.Apply(AttachMethod)
	_ = p.Apply(PSPSucceeded)
	if err := p.Refund(1000); err != nil {
		t.Fatal(err)
	}
	if err := p.Refund(100); !errors.Is(err, ErrAmount) {
		t.Fatalf("1000+100 > 1099 must fail, got %v", err)
	}
	if err := p.Refund(99); err != nil || p.AmountRefunded != 1099 {
		t.Fatalf("got %+v %v", p, err)
	}
}

func TestEveryStatusHasARow(t *testing.T) {
	for _, s := range []Status{RequiresPaymentMethod, RequiresConfirmation, RequiresAction, Processing, RequiresCapture, Succeeded, Canceled} {
		if _, ok := transitions[s]; !ok {
			t.Fatalf("missing row for %s", s)
		}
	}
	if len(transitions[Succeeded]) != 0 || len(transitions[Canceled]) != 0 {
		t.Fatal("terminal states must have no exits")
	}
}

// Finding 9: a capture done at the PSP (webhook) completes requires_capture.
func TestPSPSucceededCompletesRequiresCapture(t *testing.T) {
	p := mustNew(t)
	for _, ev := range []Event{AttachMethod, PSPAuthorized} {
		if err := p.Apply(ev); err != nil {
			t.Fatal(err)
		}
	}
	if err := p.Apply(PSPSucceeded); err == nil {
		t.Fatal("from requires_capture the captured amount is required")
	}
	if err := p.Clone().Succeed(2000); !errors.Is(err, ErrAmount) {
		t.Fatalf("more than the hold: %v", err)
	}
	if err := p.Succeed(800); err != nil || p.Status != Succeeded || p.AmountReceived != 800 || p.AmountCapturable != 0 {
		t.Fatalf("partial capture by webhook: err=%v %+v", err, p)
	}
}

// N30: the refund cap uses checked arithmetic.
func TestRefundCapCannotOverflow(t *testing.T) {
	p, _ := New("pi_max", math.MaxInt64, "USD")
	_ = p.Apply(AttachMethod)
	if err := p.Succeed(math.MaxInt64); err != nil {
		t.Fatal(err)
	}
	if err := p.Refund(math.MaxInt64); err != nil {
		t.Fatal(err)
	}
	if err := p.Refund(1); !errors.Is(err, ErrAmount) {
		t.Fatalf("refund beyond the captured amount: %v (refunded %d)", err, p.AmountRefunded)
	}
}

Idempotency store for the client's Idempotency-Key (full design in API Idempotency):

go
// Package idem is a minimal idempotency store for the payment API. The full design
// (leases, PostgreSQL and Redis stores, 409/422 semantics) is in the API Idempotency chapter.
package idem

import (
	"crypto/sha256"
	"encoding/hex"
	"errors"
	"sync"
	"time"
)

// Outcome of Begin.
type Outcome int

const (
	Started  Outcome = iota // first time: run the operation
	Replay                  // finished before: return the stored result
	InFlight                // another copy is running: 409
)

var ErrMismatch = errors.New("idem: key reused with a different request") // 422

type record struct {
	fingerprint string
	done        bool
	result      string
	expires     time.Time
}

// Store keys records by scope+key (scope = merchant or API client).
type Store struct {
	mu  sync.Mutex
	m   map[string]*record
	ttl time.Duration
	now func() time.Time
}

// New returns a store; Stripe API v1 keeps keys for at least 24 hours, Adyen 7 to 14 days.
func New(ttl time.Duration, now func() time.Time) *Store {
	if now == nil {
		now = time.Now
	}
	return &Store{m: map[string]*record{}, ttl: ttl, now: now}
}

// Fingerprint hashes the canonical request body.
func Fingerprint(parts ...string) string {
	h := sha256.New()
	for _, p := range parts {
		h.Write([]byte(p))
		h.Write([]byte{0})
	}
	return hex.EncodeToString(h.Sum(nil))
}

// Begin claims scope/key atomically.
func (s *Store) Begin(scope, key, fp string) (Outcome, string, error) {
	s.mu.Lock()
	defer s.mu.Unlock()
	k := scope + "\x00" + key
	r, ok := s.m[k]
	if ok && s.now().After(r.expires) {
		ok = false
	}
	if !ok {
		s.m[k] = &record{fingerprint: fp, expires: s.now().Add(s.ttl)}
		return Started, "", nil
	}
	if r.fingerprint != fp {
		return 0, "", ErrMismatch
	}
	if !r.done {
		return InFlight, "", nil
	}
	return Replay, r.result, nil
}

// Complete stores the result to replay.
func (s *Store) Complete(scope, key, result string) {
	s.mu.Lock()
	defer s.mu.Unlock()
	if r, ok := s.m[scope+"\x00"+key]; ok {
		r.done, r.result = true, result
	}
}

// Abandon frees the key so a retry can run again (used when nothing happened).
func (s *Store) Abandon(scope, key string) {
	s.mu.Lock()
	defer s.mu.Unlock()
	delete(s.m, scope+"\x00"+key)
}

Double-entry ledger: balanced, append-only, idempotent postings, reversals, recomputable balances:

go
// Package ledger is an append-only double-entry journal. Balances are derived from
// entries (cached for speed, recomputable at any time); nothing is ever updated or deleted.
// A correction is a new, reversing transaction.
package ledger

import (
	"errors"
	"fmt"
	"math"
	"sort"
	"sync"
	"time"
)

// Kind decides the normal side of an account.
type Kind int

const (
	Asset     Kind = iota // normal debit: cash at bank, PSP receivable
	Expense               // normal debit: PSP fees, chargeback losses
	Liability             // normal credit: customer wallet balances, payable to merchants
	Revenue               // normal credit: sales
	Equity                // normal credit
)

func (k Kind) debitNormal() bool { return k == Asset || k == Expense }

// Direction of one entry.
type Direction int

const (
	Debit Direction = iota
	Credit
)

// Account is a named bucket in one currency.
type Account struct {
	ID            string
	Currency      string
	Kind          Kind
	AllowNegative bool // false: the normal-side balance may never go below zero
}

// Entry is one line of a transaction.
type Entry struct {
	Account   string
	Direction Direction
	Amount    int64 // minor units, always > 0
}

// Transaction is an atomic, balanced set of entries.
type Transaction struct {
	ID          string // also the idempotency key of the posting
	Description string
	Entries     []Entry
	PostedAt    time.Time
}

var (
	ErrUnbalanced   = errors.New("ledger: debits != credits")
	ErrTooFewLines  = errors.New("ledger: a transaction needs at least two entries")
	ErrBadAmount    = errors.New("ledger: entry amount must be > 0")
	ErrNoAccount    = errors.New("ledger: unknown account")
	ErrInsufficient = errors.New("ledger: balance would go negative")
	ErrConflict     = errors.New("ledger: transaction id reused with different entries")
	ErrExists       = errors.New("ledger: account exists")
	ErrOverflow     = errors.New("ledger: int64 overflow")
)

// Ledger keeps the journal in memory; the SQL schema in this chapter is the durable version.
type Ledger struct {
	mu       sync.Mutex
	accounts map[string]Account
	journal  []Transaction
	byID     map[string]int
	balance  map[string]int64 // signed: debits minus credits
	now      func() time.Time
}

// New returns an empty ledger.
func New(now func() time.Time) *Ledger {
	if now == nil {
		now = time.Now
	}
	return &Ledger{accounts: map[string]Account{}, byID: map[string]int{}, balance: map[string]int64{}, now: now}
}

// Open registers an account.
func (l *Ledger) Open(a Account) error {
	l.mu.Lock()
	defer l.mu.Unlock()
	if _, ok := l.accounts[a.ID]; ok {
		return ErrExists
	}
	l.accounts[a.ID] = a
	return nil
}

// Post validates and appends. Re-posting the same ID with the same entries is a no-op
// (idempotent); the same ID with different entries is ErrConflict.
func (l *Ledger) Post(tx Transaction) (Transaction, bool, error) {
	l.mu.Lock()
	defer l.mu.Unlock()
	if i, ok := l.byID[tx.ID]; ok {
		if sameEntries(l.journal[i].Entries, tx.Entries) {
			return copyTx(l.journal[i]), false, nil
		}
		return Transaction{}, false, ErrConflict
	}
	if len(tx.Entries) < 2 {
		return Transaction{}, false, ErrTooFewLines
	}
	perCurrency := map[string]int64{}
	delta := map[string]int64{}
	for _, e := range tx.Entries {
		a, ok := l.accounts[e.Account]
		if !ok {
			return Transaction{}, false, fmt.Errorf("%w: %s", ErrNoAccount, e.Account)
		}
		if e.Amount <= 0 {
			return Transaction{}, false, ErrBadAmount
		}
		s := e.Amount
		if e.Direction == Credit {
			s = -s
		}
		var ok1, ok2 bool
		if perCurrency[a.Currency], ok1 = add(perCurrency[a.Currency], s); !ok1 {
			return Transaction{}, false, fmt.Errorf("%w: %s total", ErrOverflow, a.Currency)
		}
		if delta[a.ID], ok2 = add(delta[a.ID], s); !ok2 {
			return Transaction{}, false, fmt.Errorf("%w: %s delta", ErrOverflow, a.ID)
		}
	}
	for cur, sum := range perCurrency {
		if sum != 0 {
			return Transaction{}, false, fmt.Errorf("%w: %s off by %d", ErrUnbalanced, cur, sum)
		}
	}
	next := map[string]int64{}
	for id, d := range delta {
		a := l.accounts[id]
		b, ok := add(l.balance[id], d)
		if !ok || b == math.MinInt64 { // MinInt64 has no normal-side (negated) value
			return Transaction{}, false, fmt.Errorf("%w: %s balance", ErrOverflow, id)
		}
		if !a.AllowNegative && normal(a, b) < 0 {
			return Transaction{}, false, fmt.Errorf("%w: %s", ErrInsufficient, id)
		}
		next[id] = b
	}
	for id, b := range next {
		l.balance[id] = b
	}
	tx.Entries = append([]Entry(nil), tx.Entries...)
	tx.PostedAt = l.now()
	l.byID[tx.ID] = len(l.journal)
	l.journal = append(l.journal, tx)
	return copyTx(tx), true, nil
}

// Reverse posts the mirror image of an existing transaction.
func (l *Ledger) Reverse(id, newID, why string) (Transaction, error) {
	l.mu.Lock()
	i, ok := l.byID[id]
	var orig Transaction
	if ok {
		orig = l.journal[i]
	}
	l.mu.Unlock()
	if !ok {
		return Transaction{}, fmt.Errorf("ledger: no transaction %s", id)
	}
	rev := Transaction{ID: newID, Description: "reversal of " + id + ": " + why}
	for _, e := range orig.Entries {
		e.Direction = 1 - e.Direction
		rev.Entries = append(rev.Entries, e)
	}
	tx, _, err := l.Post(rev)
	return tx, err
}

// Balance returns the normal-side balance (positive is "has money" for every kind).
func (l *Ledger) Balance(id string) int64 {
	l.mu.Lock()
	defer l.mu.Unlock()
	return normal(l.accounts[id], l.balance[id])
}

// Recompute derives every balance from the journal; it must equal the cache.
func (l *Ledger) Recompute() map[string]int64 {
	l.mu.Lock()
	defer l.mu.Unlock()
	out := map[string]int64{}
	for _, tx := range l.journal {
		for _, e := range tx.Entries {
			s := e.Amount
			if e.Direction == Credit {
				s = -s
			}
			out[e.Account] += s
		}
	}
	for id := range out {
		out[id] = normal(l.accounts[id], out[id])
	}
	return out
}

// TrialBalance returns debits minus credits per currency; always zero in a sound ledger.
func (l *Ledger) TrialBalance() map[string]int64 {
	l.mu.Lock()
	defer l.mu.Unlock()
	out := map[string]int64{}
	for id, b := range l.balance {
		out[l.accounts[id].Currency] += b
	}
	return out
}

// Journal returns a deep copy of all transactions in posting order: callers cannot
// reach the stored entries, so the journal stays append-only.
func (l *Ledger) Journal() []Transaction {
	l.mu.Lock()
	defer l.mu.Unlock()
	out := make([]Transaction, len(l.journal))
	for i, tx := range l.journal {
		out[i] = copyTx(tx)
	}
	return out
}

func copyTx(tx Transaction) Transaction {
	tx.Entries = append([]Entry(nil), tx.Entries...)
	return tx
}

// add is checked int64 addition: ok is false when the true sum does not fit.
func add(a, b int64) (int64, bool) {
	s := a + b
	if (b > 0 && s < a) || (b < 0 && s > a) {
		return 0, false
	}
	return s, true
}

func normal(a Account, signed int64) int64 {
	if a.Kind.debitNormal() {
		return signed
	}
	return -signed
}

func sameEntries(a, b []Entry) bool {
	if len(a) != len(b) {
		return false
	}
	key := func(es []Entry) []string {
		out := make([]string, len(es))
		for i, e := range es {
			out[i] = fmt.Sprintf("%s|%d|%d", e.Account, e.Direction, e.Amount)
		}
		sort.Strings(out)
		return out
	}
	ka, kb := key(a), key(b)
	for i := range ka {
		if ka[i] != kb[i] {
			return false
		}
	}
	return true
}
go
package ledger

import (
	"errors"
	"fmt"
	"math"
	"math/rand/v2"
	"sync"
	"testing"
)

func setup(t *testing.T) *Ledger {
	t.Helper()
	l := New(nil)
	for _, a := range []Account{
		{ID: "psp_receivable", Currency: "USD", Kind: Asset},
		{ID: "bank", Currency: "USD", Kind: Asset},
		{ID: "psp_fees", Currency: "USD", Kind: Expense},
		{ID: "sales", Currency: "USD", Kind: Revenue},
		{ID: "wallet:alice", Currency: "USD", Kind: Liability},
		{ID: "wallet:bob", Currency: "USD", Kind: Liability},
		{ID: "funding", Currency: "USD", Kind: Equity, AllowNegative: true},
	} {
		if err := l.Open(a); err != nil {
			t.Fatal(err)
		}
	}
	return l
}

func TestUnbalancedIsRejected(t *testing.T) {
	l := setup(t)
	_, _, err := l.Post(Transaction{ID: "t1", Entries: []Entry{
		{"psp_receivable", Debit, 1099}, {"sales", Credit, 1000},
	}})
	if !errors.Is(err, ErrUnbalanced) {
		t.Fatalf("got %v", err)
	}
	if len(l.Journal()) != 0 {
		t.Fatal("nothing may be written on failure")
	}
}

func TestCaptureThenSettlementWithFee(t *testing.T) {
	l := setup(t)
	mustPost(t, l, "capture:pi_1", []Entry{{"psp_receivable", Debit, 1099}, {"sales", Credit, 1099}})
	// the settlement file says: gross 1099, fee 62, net 1037 paid out to the bank
	mustPost(t, l, "settle:po_1:pi_1", []Entry{{"bank", Debit, 1037}, {"psp_fees", Debit, 62}, {"psp_receivable", Credit, 1099}})
	if l.Balance("psp_receivable") != 0 || l.Balance("bank") != 1037 || l.Balance("sales") != 1099 {
		t.Fatalf("receivable=%d bank=%d sales=%d", l.Balance("psp_receivable"), l.Balance("bank"), l.Balance("sales"))
	}
}

func TestWalletCannotGoNegative(t *testing.T) {
	l := setup(t)
	mustPost(t, l, "fund", []Entry{{"funding", Debit, 500}, {"wallet:alice", Credit, 500}})
	_, _, err := l.Post(Transaction{ID: "p2p", Entries: []Entry{{"wallet:alice", Debit, 501}, {"wallet:bob", Credit, 501}}})
	if !errors.Is(err, ErrInsufficient) {
		t.Fatalf("got %v", err)
	}
	mustPost(t, l, "p2p-ok", []Entry{{"wallet:alice", Debit, 500}, {"wallet:bob", Credit, 500}})
	if l.Balance("wallet:alice") != 0 || l.Balance("wallet:bob") != 500 {
		t.Fatal("wrong balances")
	}
}

func TestPostIsIdempotentByID(t *testing.T) {
	l := setup(t)
	e := []Entry{{"psp_receivable", Debit, 100}, {"sales", Credit, 100}}
	mustPost(t, l, "capture:pi_9", e)
	_, created, err := l.Post(Transaction{ID: "capture:pi_9", Entries: e})
	if err != nil || created {
		t.Fatalf("replay must be a no-op, created=%v err=%v", created, err)
	}
	_, _, err = l.Post(Transaction{ID: "capture:pi_9", Entries: []Entry{{"psp_receivable", Debit, 999}, {"sales", Credit, 999}}})
	if !errors.Is(err, ErrConflict) {
		t.Fatalf("got %v", err)
	}
	if l.Balance("sales") != 100 {
		t.Fatal("double posting")
	}
}

func TestReversalNetsToZeroAndKeepsHistory(t *testing.T) {
	l := setup(t)
	mustPost(t, l, "capture:pi_2", []Entry{{"psp_receivable", Debit, 2500}, {"sales", Credit, 2500}})
	if _, err := l.Reverse("capture:pi_2", "rev:pi_2", "posted twice by an old bug"); err != nil {
		t.Fatal(err)
	}
	if l.Balance("sales") != 0 || len(l.Journal()) != 2 {
		t.Fatal("reversal must add a row, not delete one")
	}
}

// The two invariants under concurrency: the trial balance is zero, and wallets never
// go negative, whatever order 200 random transfers arrive in.
func TestInvariantsUnderConcurrentTransfers(t *testing.T) {
	l := setup(t)
	mustPost(t, l, "fund-a", []Entry{{"funding", Debit, 10_000}, {"wallet:alice", Credit, 10_000}})
	mustPost(t, l, "fund-b", []Entry{{"funding", Debit, 10_000}, {"wallet:bob", Credit, 10_000}})
	var wg sync.WaitGroup
	for i := 0; i < 200; i++ {
		wg.Add(1)
		go func(i int) {
			defer wg.Done()
			from, to := "wallet:alice", "wallet:bob"
			if i%2 == 1 {
				from, to = to, from
			}
			amt := int64(rand.IntN(400) + 1)
			_, _, _ = l.Post(Transaction{ID: fmt.Sprintf("p2p-%d", i), Entries: []Entry{{from, Debit, amt}, {to, Credit, amt}}})
		}(i)
	}
	wg.Wait()
	for cur, v := range l.TrialBalance() {
		if v != 0 {
			t.Fatalf("trial balance %s = %d", cur, v)
		}
	}
	if l.Balance("wallet:alice") < 0 || l.Balance("wallet:bob") < 0 {
		t.Fatal("negative wallet")
	}
	if l.Balance("wallet:alice")+l.Balance("wallet:bob") != 20_000 {
		t.Fatal("money created or destroyed")
	}
	derived := l.Recompute()
	for id, v := range derived {
		if l.Balance(id) != v {
			t.Fatalf("cache %s=%d, derived=%d", id, l.Balance(id), v)
		}
	}
}

func mustPost(t *testing.T, l *Ledger, id string, e []Entry) {
	t.Helper()
	if _, _, err := l.Post(Transaction{ID: id, Entries: e}); err != nil {
		t.Fatalf("%s: %v", id, err)
	}
}

// Finding 5: values returned by Post and Journal must not alias the stored entries.
func TestReturnedTransactionsCannotMutateTheJournal(t *testing.T) {
	l := setup(t)
	tx, _, err := l.Post(Transaction{ID: "c1", Entries: []Entry{{"psp_receivable", Debit, 100}, {"sales", Credit, 100}}})
	if err != nil {
		t.Fatal(err)
	}
	tx.Entries[0].Amount = 999
	l.Journal()[0].Entries[1].Amount = 999
	if got := l.Journal()[0].Entries; got[0].Amount != 100 || got[1].Amount != 100 {
		t.Fatalf("journal mutated through a returned value: %+v", got)
	}
	if l.Recompute()["sales"] != l.Balance("sales") {
		t.Fatal("recomputed balance no longer equals the cache")
	}
}

// N9: totals and deltas use checked arithmetic; a wrapped "balanced" journal is rejected.
func TestOverflowingJournalIsRejected(t *testing.T) {
	l := setup(t)
	_, _, err := l.Post(Transaction{ID: "wrap", Entries: []Entry{
		{"bank", Debit, math.MaxInt64}, {"bank", Debit, math.MaxInt64}, {"bank", Debit, 2},
	}})
	if !errors.Is(err, ErrOverflow) {
		t.Fatalf("got %v, want ErrOverflow", err)
	}
	if len(l.Journal()) != 0 {
		t.Fatal("nothing may be written")
	}
}

The payment service, built to fail closed: one payment per merchant and order; one operation per payment at a time (ErrInFlight for the second caller, standing in for a row lock held across the PSP call); an attempt that was ever sent is resent with the same key until its outcome is proven, and only a fresh key the PSP provably refused allows failover; unclassified errors count as unknown; state changes are made on a copy and kept only after the ledger posting succeeds (ErrUnbooked otherwise, and the next call books the stored PSP result instead of charging again); capture amounts are recorded before the call; refund keys are bound to payment and amount; webhooks carry the amount they report. Also: a success retained for booking (unbooked) is found by one retained() lookup that Confirm, Capture and the webhook all repair from, and nothing else may overwrite it (applyLocked, setAttempt); webhook attribution, validation and application run in one critical section; webhooks are matched by PSP reference, a webhook-first success keeps its reference, every return clones the intent while s.mu is held, UnknownAttempts returns deep copies, unknown operations are resent only inside ResendWindow (FirstSentAt), and the fake PSP rejects an unknown payment reference so tests notice a lost one. Deliberate limits, stated in the code and in Known limitations: the token is in memory (a real service needs the row lock or a processing status in the database), and unknown attempts and refunds wait for reconciliation (UnknownAttempts, PendingRefunds, ResolveRefund) instead of resolving themselves:

go
// Package payment is a payment-intent service: idempotent create, confirm against one
// of several PSPs with a derived provider idempotency key, query-then-retry on ambiguous
// outcomes, and ledger postings plus outbox events committed together.
package payment

import (
	"context"
	"errors"
	"fmt"
	"sync"
	"time"

	"academy/payment-processing-architecture/idem"
	"academy/payment-processing-architecture/intent"
	"academy/payment-processing-architecture/ledger"
	"academy/payment-processing-architecture/outbox"
)

// ChargeRequest is what we send to a PSP.
type ChargeRequest struct {
	IdempotencyKey string // derived: <intent>:attempt:<n>, identical on every retry
	IntentID       string
	PaymentMethod  string // a PSP token (pm_..., a network token), never a PAN
	Amount         int64
	Currency       string
	ManualCapture  bool
}

// Result is the PSP's answer mapped onto our events.
type Result struct {
	PSPRef      string
	Outcome     intent.Event // PSPSucceeded, PSPAuthorized, PSPActionReq, PSPProcessing, PSPDeclined
	Amount      int64        // what the PSP says it received (PSPSucceeded); 0 otherwise
	DeclineCode string       // e.g. insufficient_funds, do_not_honor
}

// PSP is one provider adapter (Stripe, Adyen, Braintree...).
type PSP interface {
	Name() string
	Authorize(ctx context.Context, r ChargeRequest) (Result, error)
	Lookup(ctx context.Context, idempotencyKey string) (Result, bool, error)
	Capture(ctx context.Context, idempotencyKey, pspRef string, amount int64) error
	Refund(ctx context.Context, idempotencyKey, pspRef string, amount int64) error
}

var (
	// ErrTimeout: the request may or may not have been processed (ambiguous).
	ErrTimeout = errors.New("psp: timeout")
	// ErrUnavailable: the PSP refused THIS request before processing it. It proves nothing
	// about an earlier request with the same key.
	ErrUnavailable = errors.New("psp: unavailable")
	// ErrKeyReuse: the PSP saw this idempotency key with different parameters.
	ErrKeyReuse = errors.New("psp: idempotency key reused with different parameters")
	// ErrAmbiguous: we still do not know; the attempt stays "unknown" for reconciliation.
	ErrAmbiguous = errors.New("payment: outcome unknown, parked for reconciliation")
	// ErrUnbooked: the PSP moved money but the ledger posting failed; the intent is unchanged
	// and the result is kept so the next call (or reconciliation) books it.
	ErrUnbooked = errors.New("payment: PSP result not booked, retry or reconcile")
	// ErrMismatch: two sources disagree about an amount; a human or reconciliation decides.
	ErrMismatch = errors.New("payment: amount mismatch, needs reconciliation")
	// ErrNeedsReconciliation: an operation whose outcome is unknown is older than the
	// resend window (the PSP may have dropped its idempotency key): it is never resent.
	ErrNeedsReconciliation = errors.New("payment: outcome unknown past the resend window, reconcile")
	ErrInFlight            = errors.New("payment: another operation on this payment is in progress") // 409
	ErrDuplicateOrder      = errors.New("payment: this order already has a payment")                 // 409
	ErrNotFound            = errors.New("payment: no such intent")
	ErrRefund              = errors.New("payment: refund not allowed")
)

// Attempt is one try at one PSP with one key.
//
//	sent     created, request (maybe) on the wire
//	unknown  sent at least once, outcome not proven: only the SAME key may be resent
//	refused  the PSP provably did not process it: a new attempt may follow
//	done     the PSP's answer is applied and booked
//	unbooked the PSP answered (Result kept) but the posting failed: repaired on the next call
type Attempt struct {
	IntentID, PSP, Key, PSPRef string
	State                      string
	Result                     *Result
	FirstSentAt                time.Time // the resend window counts from here
}

type captureRec struct {
	key         string
	amount      int64
	state       string // sent, unknown, unbooked, done
	firstSentAt time.Time
}

// RefundRec is one refund key. State: sent, unknown, unbooked, booked.
type RefundRec struct {
	IntentID, Key string
	Amount        int64
	State         string
	FirstSentAt   time.Time
}

// DefaultResendWindow stays below Stripe's documented 24 hours of key retention: after it,
// an unresolved operation goes to reconciliation instead of being sent again.
const DefaultResendWindow = 23 * time.Hour

// Service holds state in memory; s.mu stands in for one database transaction, and
// busy[intent] for a row lock held across the PSP call (SELECT ... FOR UPDATE, or a
// status column "processing" set in its own transaction).
type Service struct {
	mu       sync.Mutex
	intents  map[string]*intent.Intent
	attempts map[string][]*Attempt
	byOrder  map[string]string // merchant + order -> intent: one payment per order
	busy     map[string]bool   // single flight per payment: a second caller gets ErrInFlight
	captures map[string]*captureRec
	refunds  map[string]*RefundRec // by refund key
	idem     *idem.Store
	Ledger   *ledger.Ledger
	Outbox   *outbox.Outbox
	inbox    outbox.Inbox
	psps     []PSP // routing order: primary first
	// ResendWindow: how long an operation with an unknown outcome may be resent with its key.
	ResendWindow time.Duration
	timeout      time.Duration
	now          func() time.Time
	seq          int
	testHook     func(point string) // nil in production; tests use it to force interleavings
}

func (s *Service) hook(point string) {
	if s.testHook != nil {
		s.testHook(point)
	}
}

// NewService wires the parts. callTimeout is the per-PSP-call budget.
func NewService(callTimeout time.Duration, psps ...PSP) *Service {
	return &Service{
		intents: map[string]*intent.Intent{}, attempts: map[string][]*Attempt{},
		byOrder: map[string]string{}, busy: map[string]bool{},
		captures: map[string]*captureRec{}, refunds: map[string]*RefundRec{},
		idem: idem.New(24*time.Hour, nil), Ledger: ledger.New(nil), Outbox: &outbox.Outbox{},
		psps: psps, timeout: callTimeout, now: time.Now, ResendWindow: DefaultResendWindow,
	}
}

// expired reports whether an operation first sent at t may no longer be resent; s.mu held.
func (s *Service) expired(t time.Time) bool {
	return !t.IsZero() && s.now().Sub(t) > s.ResendWindow
}

// Create makes an intent once per (merchant, Idempotency-Key) and at most once per
// (merchant, order): a second client key for the same order is ErrDuplicateOrder.
func (s *Service) Create(merchant, key string, amount int64, currency, orderID string) (*intent.Intent, bool, error) {
	fp := idem.Fingerprint(fmt.Sprint(amount), currency, orderID)
	out, stored, err := s.idem.Begin(merchant, key, fp)
	if err != nil {
		return nil, false, err
	}
	s.mu.Lock()
	defer s.mu.Unlock()
	switch out {
	case idem.Replay:
		return s.intents[stored].Clone(), true, nil // copies only: callers never alias state
	case idem.InFlight:
		return nil, false, ErrInFlight
	}
	order := merchant + "\x00" + orderID
	if _, exists := s.byOrder[order]; exists {
		s.idem.Abandon(merchant, key)
		return nil, false, fmt.Errorf("%w: %s", ErrDuplicateOrder, orderID)
	}
	s.seq++
	p, err := intent.New(fmt.Sprintf("pi_%04d", s.seq), amount, currency)
	if err != nil {
		s.idem.Abandon(merchant, key)
		return nil, false, err
	}
	s.intents[p.ID], s.byOrder[order] = p, p.ID
	s.idem.Complete(merchant, key, p.ID)
	return p.Clone(), false, nil
}

// Get returns a copy of the intent.
func (s *Service) Get(id string) (intent.Intent, error) {
	s.mu.Lock()
	defer s.mu.Unlock()
	p, ok := s.intents[id]
	if !ok {
		return intent.Intent{}, ErrNotFound
	}
	return *p.Clone(), nil
}

// begin takes the payment's single-flight token; s.mu must be held.
func (s *Service) begin(id string) error {
	if s.busy[id] {
		return fmt.Errorf("%w: %s", ErrInFlight, id)
	}
	s.busy[id] = true
	return nil
}

func (s *Service) end(id string) {
	s.mu.Lock()
	defer s.mu.Unlock()
	delete(s.busy, id)
}

// Confirm charges the intent. One caller at a time per payment (others get ErrInFlight).
// An attempt that was ever sent without a proven outcome is resent with the SAME key at
// the SAME PSP until a clear answer arrives; only a fresh attempt that the PSP provably
// refused allows failover. A result whose posting failed is booked again, not re-charged.
func (s *Service) Confirm(ctx context.Context, id, paymentMethod string, manualCapture bool) (intent.Intent, error) {
	s.mu.Lock()
	p, ok := s.intents[id]
	if !ok {
		s.mu.Unlock()
		return intent.Intent{}, ErrNotFound
	}
	if err := s.begin(id); err != nil {
		cp := *p.Clone()
		s.mu.Unlock()
		return cp, err
	}
	defer s.end(id)
	last := s.lastAttempt(id)
	if r := s.retained(id); r != nil {
		defer s.mu.Unlock()
		return s.applyLocked(r, *r.Result) // repair: book what the PSP already did
	}
	if p.Terminal() || p.Status == intent.RequiresCapture || p.Status == intent.RequiresAction || p.Status == intent.Processing {
		// finished, or waiting for the customer (3DS) or an async rail: the webhook moves it on
		cp := *p.Clone()
		s.mu.Unlock()
		return cp, nil
	}
	if p.Status == intent.RequiresPaymentMethod {
		_ = p.Apply(intent.AttachMethod)
	}
	route, fresh := s.psps, true
	var att *Attempt
	if last != nil && (last.State == "unknown" || last.State == "sent") {
		if s.expired(last.FirstSentAt) {
			cp := *p.Clone()
			s.mu.Unlock()
			return cp, fmt.Errorf("%w: attempt %s", ErrNeedsReconciliation, last.Key)
		}
		att, fresh = last, false // never superseded until its outcome is proven
		route = []PSP{s.pspByName(last.PSP)}
	} else if len(route) > 0 {
		att = s.newAttemptLocked(id, route[0].Name())
	}
	amount, currency := p.Amount, p.Currency
	s.mu.Unlock()
	s.hook("confirm:after-lookup")

	for i, psp := range route {
		if psp == nil {
			break
		}
		if i > 0 {
			s.hook("confirm:before-fallback")
			s.mu.Lock()
			att, fresh = s.newAttemptLocked(id, psp.Name()), true // we still hold the token
			s.mu.Unlock()
		}
		req := ChargeRequest{IdempotencyKey: att.Key, IntentID: id, PaymentMethod: paymentMethod,
			Amount: amount, Currency: currency, ManualCapture: manualCapture}
		res, err := s.charge(ctx, psp, req, fresh)
		switch {
		case err == nil:
			return s.apply(att, res)
		case errors.Is(err, ErrUnavailable):
			s.setAttempt(att, "refused") // fresh key, provably not processed
			if i+1 < len(route) {
				continue
			}
			cur, _ := s.Get(id)
			return cur, err
		default:
			s.setAttempt(att, "unknown") // never fail over: this PSP may have charged
			cur, _ := s.Get(id)
			return cur, fmt.Errorf("%w: %v", ErrAmbiguous, err)
		}
	}
	return s.Get(id)
}

// charge = call; on anything but a clear answer ask "did it happen?"; resend the SAME key.
// ErrUnavailable is returned only when no send of this key can have been processed:
// a fresh key whose every send was refused. Every other failure is ambiguous.
func (s *Service) charge(ctx context.Context, psp PSP, req ChargeRequest, fresh bool) (Result, error) {
	maybeProcessed := !fresh
	for try := 0; try < 2; try++ {
		cctx, cancel := context.WithTimeout(ctx, s.timeout)
		res, err := psp.Authorize(cctx, req)
		cancel()
		if err == nil {
			return res, nil
		}
		if errors.Is(err, ErrUnavailable) {
			if !maybeProcessed {
				return Result{}, ErrUnavailable
			}
		} else {
			maybeProcessed = true // timeout, reset, decode error, unknown 5xx: fail closed
		}
		lctx, cancel := context.WithTimeout(ctx, s.timeout)
		found, ok, lerr := psp.Lookup(lctx, req.IdempotencyKey)
		cancel()
		if lerr == nil && ok {
			return found, nil
		}
	}
	return Result{}, ErrAmbiguous
}

// apply books first and changes state second: the change is made on a clone, posted, and
// only then copied into the intent. A failed posting leaves the intent as it was and keeps
// the PSP result on the attempt ("unbooked") so a retry books it without charging again.
func (s *Service) apply(att *Attempt, res Result) (intent.Intent, error) {
	s.mu.Lock()
	defer s.mu.Unlock()
	return s.applyLocked(att, res)
}

// retained returns the latest attempt of id if it holds a PSP success the ledger has not
// booked yet ("unbooked"); s.mu held. Confirm, Capture and the webhook path all repair from
// this one place, and nothing may overwrite it except its own booking.
func (s *Service) retained(id string) *Attempt {
	if a := s.lastAttempt(id); a != nil && a.State == "unbooked" && a.Result != nil {
		return a
	}
	return nil
}

// applyLocked is apply with s.mu held. If the attempt holds a retained success, an incoming
// answer never replaces it: the same success books it, an older answer (authorized, action,
// processing) is stale and the retained success is booked instead, and a decline contradicts
// it (ErrMismatch, retained success untouched).
func (s *Service) applyLocked(att *Attempt, res Result) (intent.Intent, error) {
	p := s.intents[att.IntentID]
	if att.State == "unbooked" && att.Result != nil {
		kept := *att.Result
		same := res.Outcome == intent.PSPSucceeded && res.Amount == kept.Amount && (res.PSPRef == "" || res.PSPRef == kept.PSPRef)
		if !same && (res.Outcome == intent.PSPDeclined || res.Outcome == intent.PSPSucceeded) {
			return *p.Clone(), fmt.Errorf("%w: %s contradicts the retained success of %s", ErrMismatch, res.Outcome, att.Key)
		}
		res = kept
	}
	if att.PSPRef != "" && res.PSPRef != "" && att.PSPRef != res.PSPRef {
		return *p.Clone(), fmt.Errorf("%w: attempt %s has reference %s, PSP reports %s", ErrMismatch, att.Key, att.PSPRef, res.PSPRef)
	}
	if att.PSPRef == "" {
		att.PSPRef = res.PSPRef // kept in every branch, including the terminal one below
	}
	if p.Terminal() && !p.Can(res.Outcome) {
		if res.Outcome == intent.PSPSucceeded && p.Status == intent.Succeeded && res.Amount != p.AmountReceived {
			return *p.Clone(), fmt.Errorf("%w: booked %d, PSP reports %d", ErrMismatch, p.AmountReceived, res.Amount)
		}
		if att.State != "unbooked" {
			att.State, att.Result = "done", nil
		}
		return *p.Clone(), nil // already applied by another path (webhook or an earlier call)
	}
	next := p.Clone()
	var err error
	if res.Outcome == intent.PSPSucceeded {
		err = next.Succeed(res.Amount)
	} else {
		err = next.Apply(res.Outcome)
	}
	if err != nil {
		return *p.Clone(), err
	}
	if next.Status == intent.Succeeded {
		if err := s.postCapture(next, att.PSP, next.AmountReceived); err != nil {
			stored := res
			att.State, att.Result = "unbooked", &stored
			return *p.Clone(), fmt.Errorf("%w: %v", ErrUnbooked, err)
		}
	}
	*p = *next
	att.State, att.Result = "done", nil
	switch p.Status {
	case intent.Succeeded:
		s.emit(p, "payments.payment_succeeded", fmt.Sprintf(`{"id":%q,"amount":%d,"psp":%q}`, p.ID, p.AmountReceived, att.PSP))
	case intent.RequiresCapture:
		s.emit(p, "payments.payment_authorized", fmt.Sprintf(`{"id":%q,"capturable":%d}`, p.ID, p.AmountCapturable))
	case intent.RequiresPaymentMethod:
		s.emit(p, "payments.payment_failed", fmt.Sprintf(`{"id":%q,"decline_code":%q}`, p.ID, res.DeclineCode))
	}
	return *p.Clone(), nil
}

// Capture takes a held authorization (full or partial). The amount is recorded with its
// derived key (capture:<intent>) BEFORE the PSP call; a later call with another amount is
// ErrMismatch, never a second capture. Only the PSP's success is booked; if the capture
// webhook booked first, the amounts must agree. A capture the PSP confirmed but the ledger
// rejected ("unbooked") is booked on retry WITHOUT calling the PSP again; an unknown one is
// resent only inside the resend window. Every return clones the intent under s.mu.
func (s *Service) Capture(ctx context.Context, id string, amount int64) (intent.Intent, error) {
	s.mu.Lock()
	p, ok := s.intents[id]
	if !ok {
		s.mu.Unlock()
		return intent.Intent{}, ErrNotFound
	}
	if err := s.begin(id); err != nil {
		cp := *p.Clone()
		s.mu.Unlock()
		return cp, err
	}
	defer s.end(id)
	rec := s.captures[id]
	if rec != nil && rec.amount != amount {
		cp := *p.Clone()
		s.mu.Unlock()
		return cp, fmt.Errorf("%w: capture key %s already used for %d", ErrMismatch, rec.key, rec.amount)
	}
	if r := s.retained(id); r != nil && r.Result.Outcome == intent.PSPSucceeded { // the webhook saw the capture
		defer s.mu.Unlock()
		if r.Result.Amount != amount {
			return *p.Clone(), fmt.Errorf("%w: PSP captured %d, capture asks %d", ErrMismatch, r.Result.Amount, amount)
		}
		got, err := s.applyLocked(r, *r.Result)
		if err == nil && rec != nil {
			rec.state = "done"
		}
		return got, err
	}
	if rec != nil && rec.state == "unbooked" {
		defer s.mu.Unlock()
		return s.bookCaptureLocked(p, rec, s.lastPSP(id), amount)
	}
	if p.Status == intent.Succeeded && rec != nil && p.AmountReceived == amount {
		cp := *p.Clone()
		s.mu.Unlock()
		return cp, nil // replay of a booked capture
	}
	if p.Status != intent.RequiresCapture || amount <= 0 || amount > p.AmountCapturable {
		cp := *p.Clone()
		s.mu.Unlock()
		return cp, fmt.Errorf("%w: capture %d in %s", intent.ErrInvalidTransition, amount, cp.Status)
	}
	if rec != nil && s.expired(rec.firstSentAt) {
		cp := *p.Clone()
		s.mu.Unlock()
		return cp, fmt.Errorf("%w: capture %s", ErrNeedsReconciliation, rec.key)
	}
	fresh := rec == nil
	if fresh {
		rec = &captureRec{key: "capture:" + id, amount: amount, state: "sent", firstSentAt: s.now()}
		s.captures[id] = rec
	}
	pspName := s.lastPSP(id)
	psp, ref := s.pspByName(pspName), s.lastRef(id)
	key := rec.key
	s.mu.Unlock()
	if psp == nil {
		return s.Get(id)
	}
	cctx, cancel := context.WithTimeout(ctx, s.timeout)
	err := psp.Capture(cctx, key, ref, amount)
	cancel()
	s.hook("capture:after-psp")
	s.mu.Lock()
	defer s.mu.Unlock()
	if err != nil {
		if fresh && errors.Is(err, ErrUnavailable) {
			delete(s.captures, id) // provably not captured: the amount may change later
		} else {
			rec.state = "unknown"
		}
		return *p.Clone(), err
	}
	return s.bookCaptureLocked(p, rec, pspName, amount)
}

// bookCaptureLocked books a capture the PSP confirmed; s.mu held.
func (s *Service) bookCaptureLocked(p *intent.Intent, rec *captureRec, pspName string, amount int64) (intent.Intent, error) {
	if p.Status == intent.Succeeded { // the capture webhook was faster
		if p.AmountReceived != amount {
			return *p.Clone(), fmt.Errorf("%w: webhook booked %d, capture %d", ErrMismatch, p.AmountReceived, amount)
		}
		rec.state = "done"
		return *p.Clone(), nil
	}
	next := p.Clone()
	if err := next.Capture(amount); err != nil {
		return *p.Clone(), err
	}
	if err := s.postCapture(next, pspName, amount); err != nil {
		rec.state = "unbooked" // captured at the PSP: the retry books it, it never re-captures
		return *p.Clone(), fmt.Errorf("%w: %v", ErrUnbooked, err)
	}
	*p = *next
	rec.state = "done"
	s.emit(p, "payments.payment_captured", fmt.Sprintf(`{"id":%q,"amount":%d}`, p.ID, amount))
	return *p.Clone(), nil
}

func (s *Service) pspByName(name string) PSP {
	for _, c := range s.psps {
		if c.Name() == name {
			return c
		}
	}
	return nil
}

// openRefunds sums refunds of id that are not booked yet (sent, unknown, unbooked):
// that money may already have left, so it is not refundable again.
func (s *Service) openRefunds(id string) int64 {
	var n int64
	for _, r := range s.refunds {
		if r.IntentID == id && r.State != "booked" {
			n += r.Amount
		}
	}
	return n
}

// Refund sends a refund with its own key and books it. One operation per payment at a
// time. A key is bound to (payment, amount) forever: any other use is ErrRefund. The amount
// counts as taken from the moment the key is recorded until the refund is booked, or until
// a FRESH key is provably refused (ErrUnavailable on its first send). Every other failure
// leaves the refund "unknown" and its amount taken; the same key resumes it, and
// ResolveRefund (after a lookup at the PSP) is the only other way out.
func (s *Service) Refund(ctx context.Context, id, refundKey string, amount int64) error {
	s.mu.Lock()
	p, ok := s.intents[id]
	if !ok {
		s.mu.Unlock()
		return ErrNotFound
	}
	if err := s.begin(id); err != nil {
		s.mu.Unlock()
		return err
	}
	defer s.end(id)
	rec, seen := s.refunds[refundKey]
	switch {
	case seen && (rec.IntentID != id || rec.Amount != amount):
		s.mu.Unlock()
		return fmt.Errorf("%w: key %s belongs to %s / %d", ErrRefund, refundKey, rec.IntentID, rec.Amount)
	case seen && rec.State == "booked":
		s.mu.Unlock()
		return nil // exact replay
	case seen && rec.State == "unbooked":
		defer s.mu.Unlock()
		return s.bookRefund(p, rec, s.lastPSP(id)) // known success: book it, never resend
	case seen && s.expired(rec.FirstSentAt):
		s.mu.Unlock()
		return fmt.Errorf("%w: refund %s", ErrNeedsReconciliation, refundKey)
	case !seen:
		if p.Status != intent.Succeeded || amount <= 0 || amount > p.AmountReceived-p.AmountRefunded-s.openRefunds(id) {
			s.mu.Unlock()
			return ErrRefund
		}
		rec = &RefundRec{IntentID: id, Key: refundKey, Amount: amount, State: "sent", FirstSentAt: s.now()}
		s.refunds[refundKey] = rec
	}
	fresh := !seen
	pspName, ref := s.lastPSP(id), s.lastRef(id)
	psp := s.pspByName(pspName)
	s.mu.Unlock()

	var err error
	if psp == nil {
		err = fmt.Errorf("%w: no PSP attempt recorded for %s", ErrUnavailable, id)
	} else {
		cctx, cancel := context.WithTimeout(ctx, s.timeout)
		err = psp.Refund(cctx, refundKey, ref, amount)
		cancel()
	}
	s.hook("refund:before-booking")
	s.mu.Lock()
	defer s.mu.Unlock()
	if err != nil {
		if fresh && errors.Is(err, ErrUnavailable) {
			delete(s.refunds, refundKey) // first send refused before processing: nothing left
			return err
		}
		rec.State = "unknown"
		return fmt.Errorf("%w: refund %s, amount stays reserved: %v", ErrAmbiguous, refundKey, err)
	}
	return s.bookRefund(p, rec, pspName)
}

// bookRefund posts the journal entry first and changes the intent second; s.mu held.
func (s *Service) bookRefund(p *intent.Intent, rec *RefundRec, pspName string) error {
	next := p.Clone()
	if err := next.Refund(rec.Amount); err != nil {
		rec.State = "unbooked"
		return fmt.Errorf("%w: %v", ErrUnbooked, err)
	}
	cur := p.Currency
	if _, _, err := s.Ledger.Post(ledger.Transaction{ID: "refund:" + rec.Key, Description: "refund " + p.ID, Entries: []ledger.Entry{
		{Account: s.acct("refunds", "", cur, ledger.Expense), Direction: ledger.Debit, Amount: rec.Amount},
		{Account: s.acct("psp_receivable", pspName, cur, ledger.Asset), Direction: ledger.Credit, Amount: rec.Amount},
	}}); err != nil {
		rec.State = "unbooked" // refunded at the PSP: the next call with this key books it
		return fmt.Errorf("%w: %v", ErrUnbooked, err)
	}
	*p = *next
	rec.State = "booked"
	s.emit(p, "payments.payment_refunded", fmt.Sprintf(`{"id":%q,"amount":%d}`, p.ID, rec.Amount))
	return nil
}

// ResolveRefund is the reconciliation exit for an unknown refund, after a lookup at the
// PSP (or the settlement file) proved what happened: refunded -> booked, not -> released.
func (s *Service) ResolveRefund(refundKey string, refundedAtPSP bool) error {
	s.mu.Lock()
	defer s.mu.Unlock()
	rec, ok := s.refunds[refundKey]
	if !ok || rec.State == "booked" {
		return nil
	}
	if s.busy[rec.IntentID] {
		return ErrInFlight
	}
	if !refundedAtPSP {
		delete(s.refunds, refundKey)
		return nil
	}
	return s.bookRefund(s.intents[rec.IntentID], rec, s.lastPSP(rec.IntentID))
}

// PendingRefunds lists refunds that are not booked, for the reconciliation job.
func (s *Service) PendingRefunds() []RefundRec {
	s.mu.Lock()
	defer s.mu.Unlock()
	var out []RefundRec
	for _, r := range s.refunds {
		if r.State != "booked" {
			out = append(out, *r)
		}
	}
	return out
}

// HandleWebhook applies a verified PSP event once; duplicates and stale events are acked.
// The event is attributed by the PSP reference it carries (pspRef), never to "the latest
// attempt": an event for an older attempt is stale (acked) unless it reports a success,
// which means a second charge somewhere and is ErrMismatch. A reference we have not seen
// yet is attached only to the single in-flight attempt without one. amount is what the
// event says was received (PSPSucceeded). A retained (unbooked) success is never overwritten:
// a contradicting event is ErrMismatch, the same or an older event books the retained success.
// Attribution, validation and application run in ONE critical section. The event id is
// claimed first (a concurrent duplicate is skipped) and forgotten again if applying fails,
// so the PSP's next delivery retries it.
func (s *Service) HandleWebhook(eventID, intentID string, ev intent.Event, amount int64, pspRef string) (applied bool, err error) {
	if !s.inbox.FirstTime(eventID) {
		return false, nil
	}
	fail := func(e error) (bool, error) { s.inbox.Forget(eventID); return false, e }
	s.hook("webhook:window") // before the critical section: nothing can interleave inside it
	s.mu.Lock()
	defer s.mu.Unlock()
	p, ok := s.intents[intentID]
	if !ok || pspRef == "" {
		return fail(fmt.Errorf("%w: %s / %q", ErrNotFound, intentID, pspRef)) // not ours yet: retry later
	}
	atts := s.attempts[intentID]
	var att *Attempt
	for _, a := range atts {
		if a.PSPRef == pspRef {
			att = a
		}
	}
	if att == nil {
		var open []*Attempt
		for _, a := range atts {
			if a.PSPRef == "" && (a.State == "sent" || a.State == "unknown") {
				open = append(open, a)
			}
		}
		if len(open) != 1 {
			return fail(fmt.Errorf("%w: no attempt for reference %s", ErrNotFound, pspRef))
		}
		att = open[0]
	}
	latest := atts[len(atts)-1] == att
	switch {
	case !latest && ev == intent.PSPSucceeded:
		return fail(fmt.Errorf("%w: success for superseded attempt %s", ErrMismatch, att.Key))
	case !latest:
		return false, nil // stale: an older attempt's failure says nothing about the current one
	case att.State == "unbooked" && (ev == intent.PSPDeclined || (ev == intent.PSPSucceeded && att.Result.Amount != amount)):
		return fail(fmt.Errorf("%w: event %s contradicts the unbooked success of %s", ErrMismatch, ev, att.Key))
	case att.State == "unbooked": // the same success, or an older event: book the retained success
	case att.State != "unbooked" && !p.Can(ev):
		mismatch := ev == intent.PSPSucceeded && p.Status == intent.Succeeded && amount != p.AmountReceived
		if mismatch {
			return fail(fmt.Errorf("%w: booked amount differs, event says %d", ErrMismatch, amount))
		}
		return false, nil // late or out-of-order: current state already covers it
	}
	// validation above and application below share ONE critical section: the attempt
	// cannot be superseded in between
	if _, err = s.applyLocked(att, Result{Outcome: ev, Amount: amount, PSPRef: pspRef}); err != nil {
		return fail(err)
	}
	return true, nil
}

// UnknownAttempts lists attempts for the reconciliation job.
func (s *Service) UnknownAttempts() []Attempt {
	s.mu.Lock()
	defer s.mu.Unlock()
	var out []Attempt
	for _, as := range s.attempts {
		for _, a := range as {
			if a.State == "unknown" || a.State == "unbooked" {
				c := *a
				if a.Result != nil {
					r := *a.Result // deep copy: callers cannot edit recovery state
					c.Result = &r
				}
				out = append(out, c)
			}
		}
	}
	return out
}

func (s *Service) postCapture(p *intent.Intent, psp string, amount int64) error {
	_, _, err := s.Ledger.Post(ledger.Transaction{ID: fmt.Sprintf("capture:%s", p.ID), Description: "capture " + p.ID, Entries: []ledger.Entry{
		{Account: s.acct("psp_receivable", psp, p.Currency, ledger.Asset), Direction: ledger.Debit, Amount: amount},
		{Account: s.acct("sales", "", p.Currency, ledger.Revenue), Direction: ledger.Credit, Amount: amount},
	}})
	return err
}

func (s *Service) acct(name, psp, cur string, k ledger.Kind) string {
	id := name + ":" + cur
	if psp != "" {
		id = name + ":" + psp + ":" + cur
	}
	_ = s.Ledger.Open(ledger.Account{ID: id, Currency: cur, Kind: k, AllowNegative: name == "psp_receivable"})
	return id
}

func (s *Service) emit(p *intent.Intent, topic, payload string) {
	s.Outbox.Append(outbox.Event{ID: fmt.Sprintf("evt_%s_v%d", p.ID, p.Version), Topic: topic, Key: p.ID, Payload: payload, CreatedAt: s.now()})
}

func (s *Service) lastAttempt(id string) *Attempt {
	if as := s.attempts[id]; len(as) > 0 {
		return as[len(as)-1]
	}
	return nil
}

func (s *Service) newAttemptLocked(id, psp string) *Attempt {
	a := &Attempt{IntentID: id, PSP: psp, Key: fmt.Sprintf("%s:attempt:%d", id, len(s.attempts[id])+1), State: "sent", FirstSentAt: s.now()}
	s.attempts[id] = append(s.attempts[id], a)
	return a
}

// setAttempt records a failure state; it never overwrites a result that is already known
// (done) or retained for booking (unbooked), e.g. by a webhook that arrived meanwhile.
func (s *Service) setAttempt(a *Attempt, st string) {
	s.mu.Lock()
	defer s.mu.Unlock()
	if a.State == "done" || a.State == "unbooked" {
		return
	}
	a.State = st
}

func (s *Service) lastPSP(id string) string {
	as := s.attempts[id]
	if len(as) == 0 {
		return ""
	}
	return as[len(as)-1].PSP
}

func (s *Service) lastRef(id string) string {
	as := s.attempts[id]
	if len(as) == 0 {
		return ""
	}
	return as[len(as)-1].PSPRef
}
go
package payment

import (
	"context"
	"errors"
	"fmt"
	"sync"

	"academy/payment-processing-architecture/intent"
)

// ErrBadRef: the PSP does not know the payment reference (a real PSP answers 404 / 400).
var ErrBadRef = errors.New("psp: unknown payment reference")

// FakePSP behaves like a provider with server-side idempotency keys.
type FakePSP struct {
	ID string
	mu sync.Mutex
	// LoseResponses: the next N Authorize calls process the charge, then return ErrTimeout.
	LoseResponses int
	// Down: refuse every call before processing (ErrUnavailable).
	Down bool
	// Decline with this code instead of succeeding.
	DeclineCode string
	// LookupDown makes the status query fail too (a full PSP outage after the charge).
	LookupDown bool
	// Require3DS answers requires_action.
	Require3DS bool
	byKey      map[string]Result
	reqAmount  map[string]int64 // parameters stored with each key, like a PSP's key store
	refs       map[string]bool  // payment references this PSP issued
	Charges    int              // real money movements (distinct keys processed)
	// AuthorizeCalls counts every Authorize call that reached the PSP.
	AuthorizeCalls int
	// BeforeAuthorizeReturn runs (outside the fake's lock) just before a successful
	// Authorize returns: tests deliver the webhook "first" from here.
	BeforeAuthorizeReturn func(Result)
	// LoseCaptureResponses: the next N Capture calls process the capture, then return ErrTimeout.
	LoseCaptureResponses int
	// BeforeCaptureReturn runs (outside the lock) after a capture was processed.
	BeforeCaptureReturn func()
	Refunds             map[string]int64
	// LoseRefundResponses: the next N Refund calls process the refund, then return ErrTimeout.
	LoseRefundResponses int
	// TimeoutBeforeRefund: the next N Refund calls time out WITHOUT processing.
	TimeoutBeforeRefund int
	// RefundErr: after processing the refund, return this error (e.g. a connection reset).
	RefundErr error
	// RefundCalls counts every Refund call that reached the PSP.
	RefundCalls int
	// Captures records each distinct capture key and its amount.
	Captures map[string]int64
}

func (f *FakePSP) Name() string { return f.ID }

func (f *FakePSP) Authorize(ctx context.Context, r ChargeRequest) (Result, error) {
	res, err := f.authorize(r)
	if err == nil && f.BeforeAuthorizeReturn != nil {
		f.BeforeAuthorizeReturn(res)
	}
	return res, err
}

func (f *FakePSP) authorize(r ChargeRequest) (Result, error) {
	f.mu.Lock()
	defer f.mu.Unlock()
	f.AuthorizeCalls++
	if f.Down {
		return Result{}, ErrUnavailable
	}
	if f.byKey == nil {
		f.byKey, f.reqAmount, f.refs = map[string]Result{}, map[string]int64{}, map[string]bool{}
	}
	res, seen := f.byKey[r.IdempotencyKey]
	if seen && f.reqAmount[r.IdempotencyKey] != r.Amount {
		return Result{}, ErrKeyReuse
	}
	if !seen {
		f.reqAmount[r.IdempotencyKey] = r.Amount
		res = Result{PSPRef: fmt.Sprintf("%s_ch_%d", f.ID, len(f.byKey)+1), Outcome: intent.PSPSucceeded, Amount: r.Amount}
		switch {
		case f.DeclineCode != "":
			res.Outcome, res.DeclineCode = intent.PSPDeclined, f.DeclineCode
		case f.Require3DS:
			res.Outcome = intent.PSPActionReq
		case r.ManualCapture:
			res.Outcome = intent.PSPAuthorized
		}
		if res.Outcome != intent.PSPSucceeded {
			res.Amount = 0
		}
		f.byKey[r.IdempotencyKey] = res
		f.refs[res.PSPRef] = true
		if res.Outcome == intent.PSPSucceeded || res.Outcome == intent.PSPAuthorized {
			f.Charges++
		}
	}
	if f.LoseResponses > 0 {
		f.LoseResponses--
		return Result{}, ErrTimeout
	}
	return res, nil
}

func (f *FakePSP) Lookup(ctx context.Context, key string) (Result, bool, error) {
	f.mu.Lock()
	defer f.mu.Unlock()
	if f.LookupDown {
		return Result{}, false, ErrTimeout
	}
	r, ok := f.byKey[key]
	return r, ok, nil
}

func (f *FakePSP) Capture(ctx context.Context, key, ref string, amount int64) error {
	if err := f.capture(key, ref, amount); err != nil {
		return err
	}
	if f.BeforeCaptureReturn != nil {
		f.BeforeCaptureReturn()
	}
	return nil
}

func (f *FakePSP) capture(key, ref string, amount int64) error {
	f.mu.Lock()
	defer f.mu.Unlock()
	if f.Down {
		return ErrUnavailable
	}
	if !f.refs[ref] {
		return ErrBadRef
	}
	if f.Captures == nil {
		f.Captures = map[string]int64{}
	}
	if prev, dup := f.Captures[key]; dup && prev != amount {
		return ErrKeyReuse // a real PSP rejects a reused key with different parameters
	}
	f.Captures[key] = amount
	if f.LoseCaptureResponses > 0 {
		f.LoseCaptureResponses--
		return ErrTimeout
	}
	return nil
}

func (f *FakePSP) Refund(ctx context.Context, key, ref string, amount int64) error {
	f.mu.Lock()
	defer f.mu.Unlock()
	f.RefundCalls++
	if f.Refunds == nil {
		f.Refunds = map[string]int64{}
	}
	if f.Down {
		return ErrUnavailable
	}
	if !f.refs[ref] {
		return ErrBadRef // the fake no longer hides a lost reference
	}
	if f.TimeoutBeforeRefund > 0 {
		f.TimeoutBeforeRefund--
		return ErrTimeout
	}
	if prev, dup := f.Refunds[key]; dup && prev != amount {
		return ErrKeyReuse
	}
	f.Refunds[key] = amount
	if f.RefundErr != nil {
		return f.RefundErr
	}
	if f.LoseRefundResponses > 0 {
		f.LoseRefundResponses--
		return ErrTimeout
	}
	return nil
}

// RefundedTotal is the money this PSP actually sent back.
func (f *FakePSP) RefundedTotal() int64 {
	f.mu.Lock()
	defer f.mu.Unlock()
	var n int64
	for _, a := range f.Refunds {
		n += a
	}
	return n
}
go
package payment

import (
	"context"
	"errors"
	"testing"
	"time"

	"academy/payment-processing-architecture/idem"
	"academy/payment-processing-architecture/intent"
	"academy/payment-processing-architecture/outbox"
)

func newSvc(psps ...PSP) *Service { return NewService(200*time.Millisecond, psps...) }

func TestCreateIsIdempotent(t *testing.T) {
	s := newSvc(&FakePSP{ID: "stripe"})
	a, replayed, err := s.Create("m_1", "order-77", 1099, "USD", "order-77")
	if err != nil || replayed {
		t.Fatal(err)
	}
	b, replayed, err := s.Create("m_1", "order-77", 1099, "USD", "order-77")
	if err != nil || !replayed || a.ID != b.ID {
		t.Fatalf("want the same intent, got %s vs %s", a.ID, b.ID)
	}
	if _, _, err := s.Create("m_1", "order-77", 5000, "USD", "order-77"); !errors.Is(err, idem.ErrMismatch) {
		t.Fatalf("same key, other amount: want mismatch, got %v", err)
	}
}

func TestLostResponseChargesOnce(t *testing.T) {
	psp := &FakePSP{ID: "stripe", LoseResponses: 1}
	s := newSvc(psp)
	p, _, _ := s.Create("m_1", "k1", 2500, "USD", "o1")
	got, err := s.Confirm(context.Background(), p.ID, "pm_card_visa", false)
	if err != nil || got.Status != intent.Succeeded {
		t.Fatalf("got %s %v", got.Status, err)
	}
	// a client retry of the whole confirm call changes nothing
	_, _ = s.Confirm(context.Background(), p.ID, "pm_card_visa", false)
	if psp.Charges != 1 {
		t.Fatalf("PSP charged %d times", psp.Charges)
	}
	if s.Ledger.Balance("sales:USD") != 2500 || len(s.Ledger.Journal()) != 1 {
		t.Fatalf("ledger: sales=%d rows=%d", s.Ledger.Balance("sales:USD"), len(s.Ledger.Journal()))
	}
	if n := len(s.Outbox.Pending(10)); n != 1 {
		t.Fatalf("want 1 outbox event, got %d", n)
	}
}

func TestAmbiguousOutcomeIsParkedNotFailedOver(t *testing.T) {
	primary := &FakePSP{ID: "stripe", LoseResponses: 5, LookupDown: true}
	backup := &FakePSP{ID: "adyen"}
	s := newSvc(primary, backup)
	p, _, _ := s.Create("m_1", "k2", 4000, "EUR", "o2")
	got, err := s.Confirm(context.Background(), p.ID, "pm_x", false)
	if !errors.Is(err, ErrAmbiguous) || got.Status != intent.RequiresConfirmation {
		t.Fatalf("got %s %v, want requires_confirmation + ErrAmbiguous", got.Status, err)
	}
	if backup.Charges != 0 {
		t.Fatal("failing over after an ambiguous outcome risks a double charge")
	}
	if u := s.UnknownAttempts(); len(u) != 1 || u[0].Key != p.ID+":attempt:1" {
		t.Fatalf("unknown attempts: %+v", u)
	}
	// PSP recovers: retry resumes the SAME key at the SAME PSP
	primary.LoseResponses, primary.LookupDown = 0, false
	got, _ = s.Confirm(context.Background(), p.ID, "pm_x", false)
	if got.Status != intent.Succeeded || primary.Charges != 1 {
		t.Fatalf("status %s charges %d", got.Status, primary.Charges)
	}
}

func TestFailoverOnlyWhenProvablyNotProcessed(t *testing.T) {
	primary := &FakePSP{ID: "stripe", Down: true}
	backup := &FakePSP{ID: "adyen"}
	s := newSvc(primary, backup)
	p, _, _ := s.Create("m_1", "k3", 1500, "GBP", "o3")
	got, _ := s.Confirm(context.Background(), p.ID, "pm_x", false)
	if got.Status != intent.Succeeded || backup.Charges != 1 || primary.Charges != 0 {
		t.Fatalf("status %s primary %d backup %d", got.Status, primary.Charges, backup.Charges)
	}
	if s.Ledger.Balance("psp_receivable:adyen:GBP") != 1500 {
		t.Fatal("receivable must be booked against the PSP that charged")
	}
}

func TestDeclineEmitsFailureAndNoLedger(t *testing.T) {
	s := newSvc(&FakePSP{ID: "stripe", DeclineCode: "insufficient_funds"})
	p, _, _ := s.Create("m_1", "k4", 999, "USD", "o4")
	got, _ := s.Confirm(context.Background(), p.ID, "pm_x", false)
	if got.Status != intent.RequiresPaymentMethod || len(s.Ledger.Journal()) != 0 {
		t.Fatalf("got %s", got.Status)
	}
	ev := s.Outbox.Pending(10)
	if len(ev) != 1 || ev[0].Topic != "payments.payment_failed" {
		t.Fatalf("got %+v", ev)
	}
}

func TestAuthorizePartialCaptureRefund(t *testing.T) {
	psp := &FakePSP{ID: "stripe"}
	s := newSvc(psp)
	p, _, _ := s.Create("m_1", "k5", 10_000, "USD", "hotel-1")
	got, _ := s.Confirm(context.Background(), p.ID, "pm_x", true)
	if got.Status != intent.RequiresCapture || len(s.Ledger.Journal()) != 0 {
		t.Fatalf("a hold is not revenue; got %s", got.Status)
	}
	if _, err := s.Capture(context.Background(), p.ID, 8_250); err != nil {
		t.Fatal(err)
	}
	if err := s.Refund(context.Background(), p.ID, "rf-1", 1_000); err != nil {
		t.Fatal(err)
	}
	if err := s.Refund(context.Background(), p.ID, "rf-2", 8_000); err == nil {
		t.Fatal("refund above captured amount must fail")
	}
	if s.Ledger.Balance("sales:USD")-s.Ledger.Balance("refunds:USD") != 7_250 {
		t.Fatal("net revenue wrong")
	}
	for cur, v := range s.Ledger.TrialBalance() {
		if v != 0 {
			t.Fatalf("trial balance %s=%d", cur, v)
		}
	}
}

func TestWebhookDuplicatesAndStaleEvents(t *testing.T) {
	s := newSvc(&FakePSP{ID: "stripe", Require3DS: true})
	p, _, _ := s.Create("m_1", "k6", 3000, "EUR", "o6")
	got, _ := s.Confirm(context.Background(), p.ID, "pm_x", false)
	if got.Status != intent.RequiresAction {
		t.Fatalf("got %s", got.Status)
	}
	if ok, err := webhook(s, "evt_1", p.ID, intent.PSPSucceeded, 3000, refOf(s, p.ID)); !ok || err != nil {
		t.Fatalf("first delivery: %v %v", ok, err)
	}
	if ok, _ := webhook(s, "evt_1", p.ID, intent.PSPSucceeded, 3000, refOf(s, p.ID)); ok {
		t.Fatal("duplicate delivery applied twice")
	}
	if ok, _ := webhook(s, "evt_0", p.ID, intent.PSPActionReq, 0, refOf(s, p.ID)); ok {
		t.Fatal("older event applied after success")
	}
	if s.Ledger.Balance("sales:EUR") != 3000 {
		t.Fatal("ledger posted twice or not at all")
	}
}

type countingPublisher struct{ n int }

func (c *countingPublisher) Publish(context.Context, outbox.Event) error { c.n++; return nil }

func TestOutboxRelayAndConsumerDedup(t *testing.T) {
	s := newSvc(&FakePSP{ID: "stripe"})
	p, _, _ := s.Create("m_1", "k7", 100, "USD", "o7")
	_, _ = s.Confirm(context.Background(), p.ID, "pm_x", false)
	pub := &countingPublisher{}
	n, _ := outbox.RelayOnce(context.Background(), s.Outbox, pub, time.Now)
	if n != 1 || len(s.Outbox.Pending(10)) != 0 {
		t.Fatalf("relayed %d", n)
	}
	var in outbox.Inbox
	if !in.FirstTime("evt_pi_0001_v2") || in.FirstTime("evt_pi_0001_v2") {
		t.Fatal("inbox must accept an event id once")
	}
}

func TestRefundIsCheckedBeforeThePSPAndReplaySafe(t *testing.T) {
	psp := &FakePSP{ID: "stripe"}
	s := newSvc(psp)
	p, _, _ := s.Create("m_1", "k8", 5_000, "USD", "o8")
	_, _ = s.Confirm(context.Background(), p.ID, "pm_x", false)
	if err := s.Refund(context.Background(), p.ID, "rf-big", 6_000); !errors.Is(err, ErrRefund) {
		t.Fatalf("over-refund: %v", err)
	}
	if len(psp.Refunds) != 0 {
		t.Fatal("an over-refund must never reach the PSP")
	}
	for i := 0; i < 2; i++ { // client retries the same refund
		if err := s.Refund(context.Background(), p.ID, "rf-a", 2_000); err != nil {
			t.Fatal(err)
		}
	}
	got, _ := s.Get(p.ID)
	if got.AmountRefunded != 2_000 || s.Ledger.Balance("refunds:USD") != 2_000 || len(psp.Refunds) != 1 {
		t.Fatalf("refunded %d, ledger %d, psp %d", got.AmountRefunded, s.Ledger.Balance("refunds:USD"), len(psp.Refunds))
	}
	q, _, _ := s.Create("m_1", "k9", 100, "USD", "o9")
	if err := s.Refund(context.Background(), q.ID, "rf-none", 100); !errors.Is(err, ErrRefund) {
		t.Fatalf("refund of an unpaid intent: %v", err)
	}
}

func TestWebhookForUnknownIntentIsRetriedLater(t *testing.T) {
	s := newSvc(&FakePSP{ID: "stripe", Require3DS: true})
	if _, err := webhook(s, "evt_early", "pi_9999", intent.PSPSucceeded, 700, refOf(s, "pi_9999")); !errors.Is(err, ErrNotFound) {
		t.Fatalf("want not found, got %v", err)
	}
	p, _, _ := s.Create("m_1", "k10", 700, "USD", "o10") // becomes pi_0001
	_, _ = s.Confirm(context.Background(), p.ID, "pm_x", false)
	if _, err := webhook(s, "evt_x", p.ID+"-missing", intent.PSPSucceeded, 700, refOf(s, p.ID+"-missing")); err == nil {
		t.Fatal("want error")
	}
	if ok, err := webhook(s, "evt_x", p.ID, intent.PSPSucceeded, 700, refOf(s, p.ID)); !ok || err != nil {
		t.Fatalf("redelivery after a failure must be processed: %v %v", ok, err)
	}
}

func TestConcurrentRefundsCannotOverRefund(t *testing.T) {
	psp := &FakePSP{ID: "stripe"}
	s := newSvc(psp)
	p, _, _ := s.Create("m_1", "k11", 1_000, "USD", "o11")
	_, _ = s.Confirm(context.Background(), p.ID, "pm_x", false)
	errs := make(chan error, 2)
	for _, k := range []string{"rf-x", "rf-y"} {
		go func(k string) { errs <- s.Refund(context.Background(), p.ID, k, 700) }(k)
	}
	var ok, refused int
	for i := 0; i < 2; i++ {
		if err := <-errs; err == nil {
			ok++
		} else if errors.Is(err, ErrRefund) || errors.Is(err, ErrInFlight) {
			refused++
		}
	}
	got, _ := s.Get(p.ID)
	if ok != 1 || refused != 1 || len(psp.Refunds) != 1 || got.AmountRefunded != 700 {
		t.Fatalf("ok=%d refused=%d psp=%d refunded=%d", ok, refused, len(psp.Refunds), got.AmountRefunded)
	}
}

Interleaving and failure tests (each failed against an earlier version of this service; the testHook forces the interleaving):

go
package payment

import (
	"context"
	"errors"
	"sync"
	"testing"

	"academy/payment-processing-architecture/intent"
)

// Finding 3: two concurrent Confirm calls must not create two provider keys. Since round 2
// the second caller is refused with ErrInFlight while the first holds the payment.
func TestConcurrentConfirmChargesOnce(t *testing.T) {
	psp := &FakePSP{ID: "stripe"}
	s := newSvc(psp)
	p, _, _ := s.Create("m_1", "r1", 2_500, "USD", "r1")
	arrived, gate := make(chan struct{}, 1), make(chan struct{})
	s.testHook = func(pt string) {
		if pt == "confirm:after-lookup" {
			arrived <- struct{}{}
			<-gate
		}
	}
	var wg sync.WaitGroup
	wg.Add(1)
	go func() { defer wg.Done(); _, _ = s.Confirm(context.Background(), p.ID, "pm_x", false) }()
	<-arrived // A has chosen its attempt and is about to charge
	_, errB := s.Confirm(context.Background(), p.ID, "pm_x", false)
	close(gate)
	wg.Wait()
	if !errors.Is(errB, ErrInFlight) || psp.Charges != 1 || len(s.Ledger.Journal()) != 1 {
		t.Fatalf("errB=%v PSP charges=%d journal rows=%d, want ErrInFlight, 1, 1", errB, psp.Charges, len(s.Ledger.Journal()))
	}
}

// Finding 4a: the reservation must hold until the refund is booked.
func TestRefundReservationHeldUntilBooked(t *testing.T) {
	psp := &FakePSP{ID: "stripe"}
	s := newSvc(psp)
	p, _, _ := s.Create("m_1", "r2", 1_000, "USD", "r2")
	_, _ = s.Confirm(context.Background(), p.ID, "pm_x", false)
	var errB error
	s.testHook = func(pt string) {
		if pt == "refund:before-booking" {
			s.testHook = nil
			errB = s.Refund(context.Background(), p.ID, "rf-b", 700) // B runs while A is not booked yet
		}
	}
	errA := s.Refund(context.Background(), p.ID, "rf-a", 700)
	if errA != nil || !(errors.Is(errB, ErrRefund) || errors.Is(errB, ErrInFlight)) || len(psp.Refunds) != 1 {
		t.Fatalf("errA=%v errB=%v psp refunds=%d, want nil, ErrRefund, 1", errA, errB, len(psp.Refunds))
	}
}

// Finding 4b: an ambiguous PSP refund error keeps the amount reserved.
func TestAmbiguousRefundKeepsReservation(t *testing.T) {
	psp := &FakePSP{ID: "stripe", LoseRefundResponses: 1}
	s := newSvc(psp)
	p, _, _ := s.Create("m_1", "r3", 1_000, "USD", "r3")
	_, _ = s.Confirm(context.Background(), p.ID, "pm_x", false)
	if err := s.Refund(context.Background(), p.ID, "rf-a", 700); err == nil {
		t.Fatal("want an error for the lost refund response")
	}
	if err := s.Refund(context.Background(), p.ID, "rf-b", 700); !errors.Is(err, ErrRefund) {
		t.Fatalf("second refund after an unknown one: %v, want ErrRefund", err)
	}
	if len(psp.Refunds) != 1 {
		t.Fatalf("PSP refunds = %d, want 1", len(psp.Refunds))
	}
	if pr := s.PendingRefunds(); len(pr) != 1 || pr[0].Key != "rf-a" || pr[0].Amount != 700 {
		t.Fatalf("pending refunds: %+v", pr)
	}
	// the same key later resolves it: booked once, reservation released
	if err := s.Refund(context.Background(), p.ID, "rf-a", 700); err != nil {
		t.Fatal(err)
	}
	got, _ := s.Get(p.ID)
	if got.AmountRefunded != 700 || len(s.PendingRefunds()) != 0 || s.Ledger.Balance("refunds:USD") != 700 {
		t.Fatalf("refunded=%d pending=%d ledger=%d", got.AmountRefunded, len(s.PendingRefunds()), s.Ledger.Balance("refunds:USD"))
	}
}

// Finding 4c: a provable refusal frees the reservation again.
func TestRefusedRefundReleasesReservation(t *testing.T) {
	psp := &FakePSP{ID: "stripe"}
	s := newSvc(psp)
	p, _, _ := s.Create("m_1", "r6", 1_000, "USD", "r6")
	_, _ = s.Confirm(context.Background(), p.ID, "pm_x", false)
	psp.Down = true
	if err := s.Refund(context.Background(), p.ID, "rf-a", 700); !errors.Is(err, ErrUnavailable) {
		t.Fatalf("got %v, want ErrUnavailable", err)
	}
	psp.Down = false
	if err := s.Refund(context.Background(), p.ID, "rf-b", 700); err != nil {
		t.Fatalf("amount must be free again: %v", err)
	}
}

// Finding 9: a verified success webhook completes a manual-capture intent.
func TestSuccessWebhookCompletesManualCapture(t *testing.T) {
	s := newSvc(&FakePSP{ID: "stripe"})
	p, _, _ := s.Create("m_1", "r4", 5_000, "USD", "r4")
	got, _ := s.Confirm(context.Background(), p.ID, "pm_x", true)
	if got.Status != intent.RequiresCapture {
		t.Fatalf("got %s", got.Status)
	}
	ok, err := webhook(s, "evt_cap", p.ID, intent.PSPSucceeded, 5_000, refOf(s, p.ID))
	got, _ = s.Get(p.ID)
	if !ok || err != nil || got.Status != intent.Succeeded || s.Ledger.Balance("sales:USD") != 5_000 {
		t.Fatalf("applied=%v err=%v status=%s sales=%d", ok, err, got.Status, s.Ledger.Balance("sales:USD"))
	}
}

// Finding 10: Capture must call the PSP before booking, and book nothing if the PSP refuses.
func TestCaptureCallsPSPFirst(t *testing.T) {
	psp := &FakePSP{ID: "stripe"}
	s := newSvc(psp)
	p, _, _ := s.Create("m_1", "r5", 10_000, "USD", "r5")
	_, _ = s.Confirm(context.Background(), p.ID, "pm_x", true)
	psp.Down = true
	if _, err := s.Capture(context.Background(), p.ID, 8_250); err == nil {
		t.Fatal("PSP down: capture must fail")
	}
	if got, _ := s.Get(p.ID); got.Status != intent.RequiresCapture || len(s.Ledger.Journal()) != 0 {
		t.Fatalf("booked without the PSP: %s, %d rows", got.Status, len(s.Ledger.Journal()))
	}
	psp.Down = false
	if _, err := s.Capture(context.Background(), p.ID, 8_250); err != nil {
		t.Fatal(err)
	}
	if len(psp.Captures) != 1 || s.Ledger.Balance("sales:USD") != 8_250 {
		t.Fatalf("PSP captures=%d sales=%d", len(psp.Captures), s.Ledger.Balance("sales:USD"))
	}
}
go
package payment

import (
	"context"
	"errors"
	"math"
	"testing"

	"academy/payment-processing-architecture/intent"
)

var bg = context.Background()

// refused reports an error that means "not done, nothing sent": a business refusal or 409.
func refused(err error) bool { return errors.Is(err, ErrRefund) || errors.Is(err, ErrInFlight) }

// N1: A is refused by the primary and pauses before failing over; B runs the whole flow.
func TestFailoverRaceChargesOnce(t *testing.T) {
	primary, backup := &FakePSP{ID: "stripe", Down: true}, &FakePSP{ID: "adyen"}
	s := newSvc(primary, backup)
	p, _, _ := s.Create("m_1", "n1", 1_500, "GBP", "n1")
	s.testHook = func(pt string) {
		if pt == "confirm:before-fallback" {
			s.testHook = nil
			_, _ = s.Confirm(bg, p.ID, "pm_x", false) // B
		}
	}
	_, _ = s.Confirm(bg, p.ID, "pm_x", false) // A
	if backup.Charges != 1 {
		t.Fatalf("backup charged %d times, want 1", backup.Charges)
	}
}

// N2: an unknown attempt is never superseded because a later retry was refused.
func TestRefusalDoesNotProveAnEarlierUnknownAttempt(t *testing.T) {
	primary, backup := &FakePSP{ID: "stripe", LoseResponses: 5, LookupDown: true}, &FakePSP{ID: "adyen"}
	s := newSvc(primary, backup)
	p, _, _ := s.Create("m_1", "n2", 4_000, "EUR", "n2")
	_, _ = s.Confirm(bg, p.ID, "pm_x", false) // processed at the PSP, answer lost: unknown
	primary.LoseResponses, primary.LookupDown, primary.Down = 0, false, true
	_, _ = s.Confirm(bg, p.ID, "pm_x", false) // retry refused before processing
	primary.Down = false
	got, _ := s.Confirm(bg, p.ID, "pm_x", false) // recovery
	if primary.Charges != 1 || backup.Charges != 0 || got.Status != intent.Succeeded {
		t.Fatalf("primary=%d backup=%d status=%s, want 1, 0, succeeded", primary.Charges, backup.Charges, got.Status)
	}
}

func captured(t *testing.T, psp *FakePSP, key string, amount int64) (*Service, string) {
	t.Helper()
	s := newSvc(psp)
	p, _, _ := s.Create("m_1", key, amount, "USD", key)
	if got, _ := s.Confirm(bg, p.ID, "pm_x", false); got.Status != intent.Succeeded {
		t.Fatalf("setup: %s", got.Status)
	}
	return s, p.ID
}

// N3a: an unknown refund keeps its reservation even if a retry is refused.
func TestUnknownRefundSurvivesRetryRefusal(t *testing.T) {
	psp := &FakePSP{ID: "stripe"}
	s, id := captured(t, psp, "n3a", 1_000)
	psp.LoseRefundResponses = 1
	_ = s.Refund(bg, id, "rf-a", 700) // refunded at the PSP, answer lost
	psp.Down = true
	_ = s.Refund(bg, id, "rf-a", 700) // retry refused
	psp.Down = false
	if err := s.Refund(bg, id, "rf-b", 700); !refused(err) {
		t.Fatalf("second refund: %v, want refused", err)
	}
	if len(psp.Refunds) != 1 {
		t.Fatalf("PSP refunds %d, want 1", len(psp.Refunds))
	}
}

// N3b: an unclassified error after sending is an unknown outcome, not "not processed".
func TestUnclassifiedRefundErrorIsUnknown(t *testing.T) {
	psp := &FakePSP{ID: "stripe", RefundErr: errors.New("read tcp: connection reset by peer")}
	s, id := captured(t, psp, "n3b", 1_000)
	_ = s.Refund(bg, id, "rf-a", 700)
	psp.RefundErr = nil
	if err := s.Refund(bg, id, "rf-b", 700); !refused(err) {
		t.Fatalf("second refund: %v, want refused", err)
	}
}

// N4: two failing calls with the same key must not release one reservation twice.
func TestDuplicateRefundFailuresDoNotUnderflowReservation(t *testing.T) {
	psp := &FakePSP{ID: "stripe"}
	s, id := captured(t, psp, "n4", 1_000)
	psp.LoseRefundResponses = 1
	_ = s.Refund(bg, id, "rf-a", 700) // unknown: 700 reserved
	psp.Down = true
	s.testHook = func(pt string) {
		if pt == "refund:before-booking" {
			s.testHook = nil
			_ = s.Refund(bg, id, "rf-a", 700) // concurrent duplicate, also refused
		}
	}
	_ = s.Refund(bg, id, "rf-a", 700)
	psp.Down = false
	calls := psp.RefundCalls
	if err := s.Refund(bg, id, "rf-c", 1_500); !refused(err) {
		t.Fatalf("refund above the captured amount: %v", err)
	}
	if psp.RefundCalls != calls {
		t.Fatal("an over-refund reached the PSP")
	}
}

// N5: a partial capture reported by webhook books the captured amount, not the hold.
func TestPartialCaptureReportedByWebhookFirst(t *testing.T) {
	psp := &FakePSP{ID: "stripe"}
	s := newSvc(psp)
	p, _, _ := s.Create("m_1", "n5", 10_000, "USD", "n5")
	_, _ = s.Confirm(bg, p.ID, "pm_x", true)
	s.testHook = func(pt string) {
		if pt == "capture:after-psp" {
			s.testHook = nil
			_, _ = webhook(s, "evt_cap", p.ID, intent.PSPSucceeded, 8_250, refOf(s, p.ID)) // webhook beats the response
		}
	}
	_, _ = s.Capture(bg, p.ID, 8_250)
	got, _ := s.Get(p.ID)
	if got.AmountReceived != 8_250 || s.Ledger.Balance("sales:USD") != 8_250 {
		t.Fatalf("received=%d sales=%d, want 8250 both", got.AmountReceived, s.Ledger.Balance("sales:USD"))
	}
}

// N6: a competing capture with another amount for the same key is rejected.
func TestCompetingCaptureAmounts(t *testing.T) {
	psp := &FakePSP{ID: "stripe"}
	s := newSvc(psp)
	p, _, _ := s.Create("m_1", "n6", 10_000, "USD", "n6")
	_, _ = s.Confirm(bg, p.ID, "pm_x", true)
	var errB error
	s.testHook = func(pt string) {
		if pt == "capture:after-psp" {
			s.testHook = nil
			_, errB = s.Capture(bg, p.ID, 9_000)
		}
	}
	_, errA := s.Capture(bg, p.ID, 8_250)
	if errA != nil || errB == nil || s.Ledger.Balance("sales:USD") != 8_250 || psp.Captures["capture:"+p.ID] != 8_250 {
		t.Fatalf("errA=%v errB=%v sales=%d psp=%d", errA, errB, s.Ledger.Balance("sales:USD"), psp.Captures["capture:"+p.ID])
	}
}

// N10: a failed posting leaves the intent unchanged, and a later retry repairs it.
func TestFailedPostingDoesNotCompleteTheIntent(t *testing.T) {
	psp := &FakePSP{ID: "stripe"}
	s := newSvc(psp)
	big, _, _ := s.Create("m_1", "n10a", math.MaxInt64, "USD", "n10a")
	_, _ = s.Confirm(bg, big.ID, "pm_x", false)
	small, _, _ := s.Create("m_1", "n10b", 1, "USD", "n10b")
	if _, err := s.Confirm(bg, small.ID, "pm_x", false); err == nil {
		t.Fatal("posting overflowed: Confirm must report it")
	}
	if got, _ := s.Get(small.ID); got.Status == intent.Succeeded {
		t.Fatal("intent marked succeeded without its journal entry")
	}
	if _, err := s.Ledger.Reverse("capture:"+big.ID, "rev:"+big.ID, "make room"); err != nil {
		t.Fatal(err)
	}
	got, err := s.Confirm(bg, small.ID, "pm_x", false)
	if err != nil || got.Status != intent.Succeeded || psp.Charges != 2 {
		t.Fatalf("repair: err=%v status=%s charges=%d", err, got.Status, psp.Charges)
	}
	found := false
	for _, tx := range s.Ledger.Journal() {
		found = found || tx.ID == "capture:"+small.ID
	}
	if !found {
		t.Fatal("repair did not post the capture")
	}
}

// N11: one payment per merchant and order, whatever the client key.
func TestOnePaymentPerOrder(t *testing.T) {
	s := newSvc(&FakePSP{ID: "stripe"})
	if _, _, err := s.Create("m_1", "key-a", 100, "USD", "order-9"); err != nil {
		t.Fatal(err)
	}
	if _, _, err := s.Create("m_1", "key-b", 100, "USD", "order-9"); err == nil {
		t.Fatal("a second client key for the same order must be rejected")
	}
}

// N12: a completed refund key replays only for the same payment and amount.
func TestCompletedRefundKeyChecksParameters(t *testing.T) {
	psp := &FakePSP{ID: "stripe"}
	s, a := captured(t, psp, "n12a", 1_000)
	b, _, _ := s.Create("m_1", "n12b", 1_000, "USD", "n12b")
	_, _ = s.Confirm(bg, b.ID, "pm_x", false)
	if err := s.Refund(bg, a, "K", 100); err != nil {
		t.Fatal(err)
	}
	if err := s.Refund(bg, b.ID, "K", 100); err == nil {
		t.Fatal("key K on another payment must be rejected")
	}
	if err := s.Refund(bg, a, "K", 200); err == nil {
		t.Fatal("key K with another amount must be rejected")
	}
	if err := s.Refund(bg, a, "K", 100); err != nil {
		t.Fatalf("exact replay: %v", err)
	}
}

// The only exits for an unknown refund: the same key succeeds, or reconciliation resolves it.
func TestResolveRefundAfterLookup(t *testing.T) {
	psp := &FakePSP{ID: "stripe", TimeoutBeforeRefund: 1} // times out BEFORE processing
	s, id := captured(t, psp, "res", 1_000)
	_ = s.Refund(bg, id, "rf-a", 700)                      // unknown (nothing happened at the PSP)
	if err := s.ResolveRefund("rf-a", false); err != nil { // lookup: the PSP has no such refund
		t.Fatal(err)
	}
	if err := s.Refund(bg, id, "rf-b", 700); err != nil {
		t.Fatalf("amount must be free after a proven non-refund: %v", err)
	}
	psp.LoseRefundResponses = 1
	_ = s.Refund(bg, id, "rf-c", 300)                     // unknown again
	if err := s.ResolveRefund("rf-c", true); err != nil { // lookup: refunded
		t.Fatal(err)
	}
	if got, _ := s.Get(id); got.AmountRefunded != 1_000 || s.Ledger.Balance("refunds:USD") != 1_000 {
		t.Fatalf("refunded=%d ledger=%d", got.AmountRefunded, s.Ledger.Balance("refunds:USD"))
	}
	if ext := psp.RefundedTotal(); ext != 1_000 { // N26: the PSP's own total must agree
		t.Fatalf("PSP refunded %d in total, booked 1000", ext)
	}
}
go
package payment

import (
	"math"
	"sync"
	"testing"
	"time"

	"academy/payment-processing-architecture/intent"
)

// fillSales books a MaxInt64 USD payment so the next USD capture posting overflows.
func fillSales(t *testing.T, s *Service) string {
	t.Helper()
	big, _, _ := s.Create("m_1", "fill", math.MaxInt64, "USD", "fill")
	if got, err := s.Confirm(bg, big.ID, "pm_x", false); err != nil || got.Status != intent.Succeeded {
		t.Fatalf("fill: %v %s", err, got.Status)
	}
	return big.ID
}

func makeRoom(t *testing.T, s *Service, txID string) {
	t.Helper()
	if _, err := s.Ledger.Reverse(txID, "rev:"+txID, "make room"); err != nil {
		t.Fatal(err)
	}
}

// N16: a delayed decline for attempt 1 must not touch attempt 2's unbooked success.
func TestStaleDeclineWebhookDoesNotTouchLaterAttempt(t *testing.T) {
	psp := &FakePSP{ID: "stripe"}
	s := newSvc(psp)
	big := fillSales(t, s)
	x, _, _ := s.Create("m_1", "n16", 10, "USD", "n16")
	psp.DeclineCode = "insufficient_funds"
	_, _ = s.Confirm(bg, x.ID, "pm_x", false) // attempt 1 declined
	psp.DeclineCode = ""
	_, _ = s.Confirm(bg, x.ID, "pm_x", false) // attempt 2 charged, posting overflows: unbooked
	ref1 := s.attempts[x.ID][0].PSPRef
	_, _ = webhook(s, "evt_late_decline", x.ID, intent.PSPDeclined, 0, ref1)
	makeRoom(t, s, "capture:"+big)
	got, err := s.Confirm(bg, x.ID, "pm_x", false)
	if err != nil || got.Status != intent.Succeeded || psp.Charges != 2 {
		t.Fatalf("err=%v status=%s charges=%d, want succeeded and 2 charges (fill + one)", err, got.Status, psp.Charges)
	}
}

// N18: success webhook before the synchronous answer; the reference must survive.
func TestWebhookFirstSuccessKeepsReference(t *testing.T) {
	psp := &FakePSP{ID: "stripe"}
	s := newSvc(psp)
	p, _, _ := s.Create("m_1", "n18", 1_000, "USD", "n18")
	psp.BeforeAuthorizeReturn = func(r Result) {
		psp.BeforeAuthorizeReturn = nil
		_, _ = webhook(s, "evt_first", p.ID, intent.PSPSucceeded, r.Amount, r.PSPRef)
	}
	if got, err := s.Confirm(bg, p.ID, "pm_x", false); err != nil || got.Status != intent.Succeeded {
		t.Fatalf("confirm: %v %s", err, got.Status)
	}
	if err := s.Refund(bg, p.ID, "rf-1", 100); err != nil {
		t.Fatalf("refund after a webhook-first success: %v", err)
	}
}

// N19: a rejected capture must not read the intent after unlocking (run with -race).
func TestRejectedCaptureCloneIsRaceFree(t *testing.T) {
	psp := &FakePSP{ID: "stripe"}
	s := newSvc(psp)
	p, _, _ := s.Create("m_1", "n19", 10_000, "USD", "n19")
	_, _ = s.Confirm(bg, p.ID, "pm_x", true)
	var wg sync.WaitGroup
	psp.BeforeCaptureReturn = func() {
		psp.BeforeCaptureReturn = nil
		wg.Add(1)
		go func() { defer wg.Done(); _, _ = s.Capture(bg, p.ID, 8_250) }() // B: refused, busy
		time.Sleep(20 * time.Millisecond)                                  // no synchronisation with B on purpose
	}
	if _, err := s.Capture(bg, p.ID, 8_250); err != nil {
		t.Fatal(err)
	}
	wg.Wait()
}

// N31: UnknownAttempts must not expose the stored result.
func TestUnknownAttemptsReturnsCopies(t *testing.T) {
	psp := &FakePSP{ID: "stripe"}
	s := newSvc(psp)
	big := fillSales(t, s)
	x, _, _ := s.Create("m_1", "n31", 10, "USD", "n31")
	_, _ = s.Confirm(bg, x.ID, "pm_x", false) // unbooked
	for _, a := range s.UnknownAttempts() {
		if a.Result != nil {
			a.Result.Outcome = intent.PSPDeclined
		}
	}
	makeRoom(t, s, "capture:"+big)
	got, err := s.Confirm(bg, x.ID, "pm_x", false)
	if err != nil || got.Status != intent.Succeeded || psp.Charges != 2 {
		t.Fatalf("err=%v status=%s charges=%d", err, got.Status, psp.Charges)
	}
}

// N17: after the resend window an unknown attempt or refund is never sent again.
func TestNoResendAfterTheWindow(t *testing.T) {
	clock := time.Date(2026, 11, 28, 9, 0, 0, 0, time.UTC)
	psp := &FakePSP{ID: "stripe", LoseResponses: 5, LookupDown: true}
	s := newSvc(psp)
	s.now = func() time.Time { return clock }
	p, _, _ := s.Create("m_1", "n17", 1_000, "USD", "n17")
	_, _ = s.Confirm(bg, p.ID, "pm_x", false) // unknown
	clock = clock.Add(25 * time.Hour)
	psp.LoseResponses, psp.LookupDown = 0, false
	calls := psp.AuthorizeCalls
	if _, err := s.Confirm(bg, p.ID, "pm_x", false); err == nil || psp.AuthorizeCalls != calls {
		t.Fatalf("resent after the window: err=%v calls %d -> %d", err, calls, psp.AuthorizeCalls)
	}

	q := &FakePSP{ID: "stripe"}
	s2, id := captured(t, q, "n17r", 1_000)
	clk := time.Date(2026, 11, 28, 9, 0, 0, 0, time.UTC)
	s2.now = func() time.Time { return clk }
	q.LoseRefundResponses = 1
	_ = s2.Refund(bg, id, "rf-a", 300) // unknown
	clk = clk.Add(25 * time.Hour)
	rc := q.RefundCalls
	if err := s2.Refund(bg, id, "rf-a", 300); err == nil || q.RefundCalls != rc {
		t.Fatalf("refund resent after the window: err=%v calls %d -> %d", err, rc, q.RefundCalls)
	}
}

// N25: a capture whose PSP call succeeded but whose posting failed is booked on retry
// without calling the PSP again (it may be down by then).
func TestUnbookedCaptureIsBookedWithoutThePSP(t *testing.T) {
	psp := &FakePSP{ID: "stripe"}
	s := newSvc(psp)
	big := fillSales(t, s)
	x, _, _ := s.Create("m_1", "n25c", 10, "USD", "n25c")
	_, _ = s.Confirm(bg, x.ID, "pm_x", true) // hold, nothing posted
	if _, err := s.Capture(bg, x.ID, 10); err == nil {
		t.Fatal("posting overflow must be reported")
	}
	makeRoom(t, s, "capture:"+big)
	psp.Down = true
	if got, err := s.Capture(bg, x.ID, 10); err != nil || got.Status != intent.Succeeded {
		t.Fatalf("retry must book the known capture: %v %s", err, got.Status)
	}
}

// N25: the same for a refund.
func TestUnbookedRefundIsBookedWithoutThePSP(t *testing.T) {
	psp := &FakePSP{ID: "stripe"}
	s := newSvc(psp)
	big := fillSales(t, s)
	if err := s.Refund(bg, big, "rf-big", math.MaxInt64); err != nil { // refunds:USD = MaxInt64
		t.Fatal(err)
	}
	makeRoom(t, s, "capture:"+big)
	x, _, _ := s.Create("m_1", "n25r", 10, "USD", "n25r")
	_, _ = s.Confirm(bg, x.ID, "pm_x", false)
	if err := s.Refund(bg, x.ID, "rf-x", 5); err == nil {
		t.Fatal("refund posting overflow must be reported")
	}
	makeRoom(t, s, "refund:rf-big")
	psp.Down = true
	if err := s.Refund(bg, x.ID, "rf-x", 5); err != nil {
		t.Fatalf("retry must book the known refund: %v", err)
	}
	if got, _ := s.Get(x.ID); got.AmountRefunded != 5 {
		t.Fatalf("refunded %d", got.AmountRefunded)
	}
}
go
package payment

import (
	"testing"

	"academy/payment-processing-architecture/intent"
)

// N32: a delayed synchronous answer must not erase a success the webhook retained.
func TestDelayedResponseKeepsRetainedWebhookSuccess(t *testing.T) {
	psp := &FakePSP{ID: "stripe"}
	s := newSvc(psp)
	big := fillSales(t, s)
	x, _, _ := s.Create("m_1", "n32", 10, "USD", "n32")
	psp.BeforeAuthorizeReturn = func(r Result) { // the hold exists; it is captured at the PSP and
		psp.BeforeAuthorizeReturn = nil // the success webhook arrives before our authorize answer
		if _, err := webhook(s, "evt_cap", x.ID, intent.PSPSucceeded, 10, r.PSPRef); err == nil {
			t.Error("webhook posting should overflow")
		}
	}
	_, _ = s.Confirm(bg, x.ID, "pm_x", true) // the late PSPAuthorized answer is applied now
	makeRoom(t, s, "capture:"+big)
	got, err := s.Confirm(bg, x.ID, "pm_x", true)
	if err != nil || got.Status != intent.Succeeded || got.AmountReceived != 10 {
		t.Fatalf("retained success lost: err=%v status=%s received=%d", err, got.Status, got.AmountReceived)
	}
}

// N33: a webhook validated while its attempt was latest must not apply after supersession.
func TestWebhookCannotApplyAfterItsAttemptWasSuperseded(t *testing.T) {
	psp := &FakePSP{ID: "stripe"}
	s := newSvc(psp)
	big := fillSales(t, s)
	x, _, _ := s.Create("m_1", "n33", 10, "USD", "n33")
	arrived, release, done := make(chan struct{}), make(chan struct{}), make(chan struct{})
	s.testHook = func(pt string) {
		if pt == "webhook:window" {
			close(arrived)
			<-release
		}
	}
	psp.DeclineCode = "insufficient_funds"
	psp.BeforeAuthorizeReturn = func(r Result) {
		psp.BeforeAuthorizeReturn = nil
		go func() { _, _ = webhook(s, "evt_a_decline", x.ID, intent.PSPDeclined, 0, r.PSPRef); close(done) }()
		<-arrived // A's decline webhook is past its checks
	}
	_, _ = s.Confirm(bg, x.ID, "pm_x", false) // A: declined synchronously
	s.testHook = nil
	psp.DeclineCode = ""
	_, _ = s.Confirm(bg, x.ID, "pm_x", false) // B: charged, posting overflows -> unbooked
	close(release)
	<-done
	makeRoom(t, s, "capture:"+big)
	got, err := s.Confirm(bg, x.ID, "pm_x", false)
	if err != nil || got.Status != intent.Succeeded || psp.Charges != 2 {
		t.Fatalf("err=%v status=%s charges=%d, want succeeded, 2", err, got.Status, psp.Charges)
	}
}

// N35: Capture repair books a success the webhook retained, without calling the PSP.
func TestCaptureRepairUsesWebhookRetainedSuccess(t *testing.T) {
	psp := &FakePSP{ID: "stripe"}
	s := newSvc(psp)
	big := fillSales(t, s)
	x, _, _ := s.Create("m_1", "n35", 10, "USD", "n35")
	_, _ = s.Confirm(bg, x.ID, "pm_x", true)
	psp.LoseCaptureResponses = 1
	_, _ = s.Capture(bg, x.ID, 10) // captured at the PSP, answer lost
	if _, err := webhook(s, "evt_cap", x.ID, intent.PSPSucceeded, 10, refOf(s, x.ID)); err == nil {
		t.Fatal("webhook posting should overflow")
	}
	makeRoom(t, s, "capture:"+big)
	psp.Down = true
	got, err := s.Capture(bg, x.ID, 10)
	if err != nil || got.Status != intent.Succeeded {
		t.Fatalf("capture retry must book the retained success: %v %s", err, got.Status)
	}
}
go
package payment

import "academy/payment-processing-architecture/intent"

// webhook delivers a verified event carrying its PSP reference.
func webhook(s *Service, evt, id string, ev intent.Event, amount int64, ref string) (bool, error) {
	return s.HandleWebhook(evt, id, ev, amount, ref)
}

// refOf returns the reference of the payment's latest attempt (what the PSP's event carries).
func refOf(s *Service, id string) string {
	s.mu.Lock()
	defer s.mu.Unlock()
	if a := s.lastAttempt(id); a != nil {
		return a.PSPRef
	}
	return "ref_unknown"
}

Webhook signature verification by Stripe's manual scheme (raw body, every v1, constant time, tolerance):

go
// Package webhook verifies Stripe-Signature headers by the manual scheme in
// docs.stripe.com/webhooks ("Verify webhook signatures manually"):
// split on ",", keep t and every v1, HMAC-SHA256(secret, t + "." + raw body),
// constant-time compare, then check the timestamp against a tolerance.
// In production prefer stripe-go's webhook.ConstructEvent (DefaultTolerance 300 s).
package webhook

import (
	"crypto/hmac"
	"crypto/sha256"
	"encoding/hex"
	"errors"
	"strconv"
	"strings"
	"time"
)

var (
	ErrNoTimestamp  = errors.New("webhook: header has no t= entry")
	ErrNoSignatures = errors.New("webhook: header has no v1= entry")
	ErrNoMatch      = errors.New("webhook: no v1 signature matches")
	ErrTooOld       = errors.New("webhook: timestamp outside tolerance")
	ErrBadTolerance = errors.New("webhook: tolerance must be > 0 (0 disables the replay check)")
)

// Verifier holds every active secret: during a secret roll Stripe keeps the old one
// valid for up to 7 days and sends one v1 per secret.
type Verifier struct {
	Secrets   [][]byte
	Tolerance time.Duration
	Now       func() time.Time
}

// Verify authenticates the raw, unmodified body.
func (v Verifier) Verify(body []byte, header string) error {
	if v.Tolerance <= 0 {
		return ErrBadTolerance
	}
	now := time.Now
	if v.Now != nil {
		now = v.Now
	}
	var ts int64
	var haveTS bool
	var sigs [][]byte
	for _, item := range strings.Split(header, ",") {
		k, val, ok := strings.Cut(strings.TrimSpace(item), "=")
		if !ok {
			continue
		}
		switch k {
		case "t":
			n, err := strconv.ParseInt(val, 10, 64)
			if err != nil {
				return ErrNoTimestamp
			}
			ts, haveTS = n, true
		case "v1":
			if b, err := hex.DecodeString(val); err == nil {
				sigs = append(sigs, b)
			}
		default:
			// v0 (sandbox only), secret, destination, payload: debug data, never trusted
		}
	}
	if !haveTS {
		return ErrNoTimestamp
	}
	if len(sigs) == 0 {
		return ErrNoSignatures
	}
	matched := false
	for _, secret := range v.Secrets {
		want := sign(secret, ts, body)
		for _, got := range sigs {
			if hmac.Equal(want, got) { // constant time
				matched = true
			}
		}
	}
	if !matched {
		return ErrNoMatch
	}
	age := now().Sub(time.Unix(ts, 0))
	if age > v.Tolerance || age < -v.Tolerance {
		return ErrTooOld
	}
	return nil
}

// Header builds a header the way Stripe does (for tests and the Stripe CLI-style lab).
func Header(secret []byte, ts time.Time, body []byte) string {
	return "t=" + strconv.FormatInt(ts.Unix(), 10) + ",v1=" + hex.EncodeToString(sign(secret, ts.Unix(), body))
}

func sign(secret []byte, ts int64, body []byte) []byte {
	m := hmac.New(sha256.New, secret)
	m.Write([]byte(strconv.FormatInt(ts, 10)))
	m.Write([]byte("."))
	m.Write(body)
	return m.Sum(nil)
}
go
package webhook

import (
	"errors"
	"testing"
	"time"
)

var (
	secret = []byte("whsec_test_secret")
	body   = []byte(`{"id":"evt_1","type":"payment_intent.succeeded","data":{"object":{"id":"pi_1"}}}`)
	t0     = time.Unix(1798765432, 0)
)

func verifier(now time.Time, secrets ...[]byte) Verifier {
	if len(secrets) == 0 {
		secrets = [][]byte{secret}
	}
	return Verifier{Secrets: secrets, Tolerance: 5 * time.Minute, Now: func() time.Time { return now }}
}

func TestValid(t *testing.T) {
	if err := verifier(t0.Add(30*time.Second)).Verify(body, Header(secret, t0, body)); err != nil {
		t.Fatal(err)
	}
}

func TestTamperedBody(t *testing.T) {
	h := Header(secret, t0, body)
	changed := []byte(`{"id":"evt_1", "type":"payment_intent.succeeded","data":{"object":{"id":"pi_1"}}}`) // one extra space
	if err := verifier(t0).Verify(changed, h); !errors.Is(err, ErrNoMatch) {
		t.Fatalf("got %v", err)
	}
}

func TestReplayOutsideTolerance(t *testing.T) {
	if err := verifier(t0.Add(6*time.Minute)).Verify(body, Header(secret, t0, body)); !errors.Is(err, ErrTooOld) {
		t.Fatalf("got %v", err)
	}
}

func TestOnlyV0IsRejected(t *testing.T) {
	h := "t=1798765432,v0=6ffbb59b2300aae63f272406069a9788598b792a944a07aba816edb039989a39"
	if err := verifier(t0).Verify(body, h); !errors.Is(err, ErrNoSignatures) {
		t.Fatalf("got %v", err)
	}
}

func TestUnknownEntriesAndAnyOrder(t *testing.T) {
	h := "payload=a25aefc6,destination=we_123," + Header(secret, t0, body) + ",secret=whsec_****"
	if err := verifier(t0).Verify(body, h); err != nil {
		t.Fatal(err)
	}
}

func TestSecretRollTwoV1(t *testing.T) {
	old, cur := []byte("whsec_old"), []byte("whsec_new")
	h := Header(old, t0, body) + ",v1=" + Header(cur, t0, body)[len("t=1798765432,v1="):]
	if err := verifier(t0, cur).Verify(body, h); err != nil {
		t.Fatalf("new secret alone must verify: %v", err)
	}
	if err := verifier(t0, []byte("whsec_other")).Verify(body, h); !errors.Is(err, ErrNoMatch) {
		t.Fatalf("got %v", err)
	}
}

func TestZeroToleranceIsAConfigError(t *testing.T) {
	v := verifier(t0)
	v.Tolerance = 0
	if err := v.Verify(body, Header(secret, t0, body)); !errors.Is(err, ErrBadTolerance) {
		t.Fatalf("got %v", err)
	}
}

Outbox and inbox:

go
// Package outbox gives exactly-once effects from at-least-once delivery: events are
// written in the same transaction as the state change, a relay publishes them (maybe twice),
// and consumers drop duplicates by event ID. Mechanics: /messaging/outbox-pattern.
package outbox

import (
	"context"
	"sync"
	"time"
)

// Event is one row of the outbox table.
type Event struct {
	ID          string // unique, used by consumers for dedup
	Topic       string // e.g. payments.payment_succeeded
	Key         string // partition key: the payment ID keeps per-payment order
	Payload     string
	CreatedAt   time.Time
	PublishedAt time.Time
}

// Outbox is the table; Append is called inside the business transaction.
type Outbox struct {
	mu     sync.Mutex
	events []Event
}

// Append adds an event (caller holds the business transaction).
func (o *Outbox) Append(e Event) {
	o.mu.Lock()
	defer o.mu.Unlock()
	o.events = append(o.events, e)
}

// Pending returns unpublished events in insertion order.
func (o *Outbox) Pending(limit int) []Event {
	o.mu.Lock()
	defer o.mu.Unlock()
	var out []Event
	for _, e := range o.events {
		if e.PublishedAt.IsZero() {
			out = append(out, e)
			if len(out) == limit {
				break
			}
		}
	}
	return out
}

func (o *Outbox) markPublished(id string, at time.Time) {
	o.mu.Lock()
	defer o.mu.Unlock()
	for i := range o.events {
		if o.events[i].ID == id {
			o.events[i].PublishedAt = at
		}
	}
}

// Publisher is the broker client (Kafka, RabbitMQ, SNS...).
type Publisher interface {
	Publish(ctx context.Context, e Event) error
}

// RelayOnce publishes pending events; a crash between Publish and markPublished
// re-sends the event on the next run, which is why consumers must dedupe.
func RelayOnce(ctx context.Context, o *Outbox, p Publisher, now func() time.Time) (int, error) {
	n := 0
	for _, e := range o.Pending(100) {
		if err := p.Publish(ctx, e); err != nil {
			return n, err // stop to keep per-key order; retry later
		}
		o.markPublished(e.ID, now())
		n++
	}
	return n, nil
}

// Inbox is the consumer-side dedup table (unique event_id).
type Inbox struct {
	mu   sync.Mutex
	seen map[string]bool
}

// FirstTime records id and reports whether it is new. In SQL this is
// INSERT ... ON CONFLICT DO NOTHING in the same transaction as the side effect.
func (in *Inbox) FirstTime(id string) bool {
	in.mu.Lock()
	defer in.mu.Unlock()
	if in.seen == nil {
		in.seen = map[string]bool{}
	}
	if in.seen[id] {
		return false
	}
	in.seen[id] = true
	return true
}

// Forget removes id so a redelivery is processed again (the side effect failed).
func (in *Inbox) Forget(id string) {
	in.mu.Lock()
	defer in.mu.Unlock()
	delete(in.seen, id)
}

Checkout saga with void as the compensation and a dead-letter list:

go
// Package checkout runs an order checkout as an orchestrated saga: reserve stock,
// authorize the card (manual capture), book the shipment, capture. Each step has a
// compensation; when a later step fails, the completed steps are undone in reverse order
// (release stock, void the authorization). A compensation that keeps failing is parked
// on a dead-letter list for a human or a later sweep. Mechanics: /messaging/saga-pattern.
package checkout

import (
	"context"
	"errors"
	"fmt"
)

// Step is one local transaction and its compensation. Both must be idempotent: the
// orchestrator may run either again after a crash, with the same key.
type Step struct {
	Name string
	Do   func(ctx context.Context, key string) error
	Undo func(ctx context.Context, key string) error // nil: nothing to undo (e.g. capture is last)
}

// Parked is a compensation that did not succeed.
type Parked struct {
	Saga, Step string
	Err        error
}

// Orchestrator runs sagas and keeps a dead-letter list.
type Orchestrator struct {
	UndoTries  int
	DeadLetter []Parked
	Log        []string
}

var ErrCompensated = errors.New("checkout: saga failed and was compensated")

// Run executes steps in order. key is the saga id; each step receives key+":"+name as its
// idempotency key, so a retried step never double-reserves or double-authorizes.
func (o *Orchestrator) Run(ctx context.Context, key string, steps []Step) error {
	tries := o.UndoTries
	if tries <= 0 {
		tries = 3
	}
	for i, s := range steps {
		if err := s.Do(ctx, key+":"+s.Name); err != nil {
			o.Log = append(o.Log, "fail "+s.Name)
			for j := i - 1; j >= 0; j-- {
				u := steps[j]
				if u.Undo == nil {
					continue
				}
				var uerr error
				for t := 0; t < tries; t++ {
					if uerr = u.Undo(ctx, key+":"+u.Name); uerr == nil {
						break
					}
				}
				if uerr != nil {
					o.DeadLetter = append(o.DeadLetter, Parked{Saga: key, Step: u.Name, Err: uerr})
					o.Log = append(o.Log, "parked undo "+u.Name)
					continue
				}
				o.Log = append(o.Log, "undo "+u.Name)
			}
			return fmt.Errorf("%w: step %s: %v", ErrCompensated, s.Name, err)
		}
		o.Log = append(o.Log, "do "+s.Name)
	}
	return nil
}
go
package checkout

import (
	"context"
	"errors"
	"strings"
	"testing"
)

type fakes struct {
	reserved, authorized map[string]bool
	voids                int
	voidFails            int
	shipFails            bool
}

func (f *fakes) steps() []Step {
	return []Step{
		{Name: "reserve_stock",
			Do:   func(_ context.Context, k string) error { f.reserved[k] = true; return nil },
			Undo: func(_ context.Context, k string) error { delete(f.reserved, k); return nil }},
		{Name: "authorize",
			Do: func(_ context.Context, k string) error { f.authorized[k] = true; return nil },
			Undo: func(_ context.Context, k string) error { // void the hold
				if f.voidFails > 0 {
					f.voidFails--
					return errors.New("psp: timeout")
				}
				f.voids++
				delete(f.authorized, k)
				return nil
			}},
		{Name: "book_shipment", Do: func(context.Context, string) error {
			if f.shipFails {
				return errors.New("carrier: no slot")
			}
			return nil
		}},
		{Name: "capture", Do: func(context.Context, string) error { return nil }},
	}
}

func newFakes() *fakes { return &fakes{reserved: map[string]bool{}, authorized: map[string]bool{}} }

func TestHappyPath(t *testing.T) {
	f, o := newFakes(), &Orchestrator{}
	if err := o.Run(context.Background(), "order-1", f.steps()); err != nil {
		t.Fatal(err)
	}
	if strings.Join(o.Log, ",") != "do reserve_stock,do authorize,do book_shipment,do capture" {
		t.Fatal(o.Log)
	}
}

func TestShipmentFailureVoidsAndReleases(t *testing.T) {
	f, o := newFakes(), &Orchestrator{}
	f.shipFails = true
	err := o.Run(context.Background(), "order-2", f.steps())
	if !errors.Is(err, ErrCompensated) {
		t.Fatal(err)
	}
	if f.voids != 1 || len(f.reserved) != 0 || len(f.authorized) != 0 {
		t.Fatalf("voids=%d reserved=%v authorized=%v", f.voids, f.reserved, f.authorized)
	}
	if got := strings.Join(o.Log, ","); got != "do reserve_stock,do authorize,fail book_shipment,undo authorize,undo reserve_stock" {
		t.Fatal(got)
	}
}

func TestVoidThatKeepsFailingIsDeadLettered(t *testing.T) {
	f, o := newFakes(), &Orchestrator{UndoTries: 2}
	f.shipFails, f.voidFails = true, 5
	_ = o.Run(context.Background(), "order-3", f.steps())
	if len(o.DeadLetter) != 1 || o.DeadLetter[0].Step != "authorize" {
		t.Fatalf("dead letter: %+v", o.DeadLetter)
	}
	if len(f.reserved) != 0 {
		t.Fatal("the other compensations must still run")
	}
}

Chargebacks booked in the ledger (fee kept on a win):

go
// Package dispute books a card chargeback in the double-entry ledger. When a cardholder
// disputes a payment, the PSP debits the disputed amount plus a dispute fee from the
// merchant balance at once (Stripe: "Debits the disputed amount, plus a dispute fee");
// winning returns the amount, and Stripe never returns the dispute received fee.
package dispute

import (
	"errors"
	"fmt"

	"academy/payment-processing-architecture/ledger"
)

// Status mirrors Stripe's dispute statuses for a formal chargeback.
type Status string

const (
	NeedsResponse Status = "needs_response"
	UnderReview   Status = "under_review"
	Won           Status = "won"
	Lost          Status = "lost"
)

var ErrState = errors.New("dispute: invalid transition")

// Dispute is one chargeback against one captured payment.
type Dispute struct {
	ID, PaymentID, PSP, Currency string
	Amount, Fee                  int64
	Status                       Status
}

// accounts opens the accounts it needs (idempotent) and returns their ids.
func accounts(l *ledger.Ledger, psp, cur string) (receivable, losses, fees string) {
	receivable = "psp_receivable:" + psp + ":" + cur
	losses, fees = "chargeback_losses:"+cur, "dispute_fees:"+cur
	_ = l.Open(ledger.Account{ID: receivable, Currency: cur, Kind: ledger.Asset, AllowNegative: true})
	_ = l.Open(ledger.Account{ID: losses, Currency: cur, Kind: ledger.Expense})
	_ = l.Open(ledger.Account{ID: fees, Currency: cur, Kind: ledger.Expense})
	return
}

// Open books the immediate debit. The posting id is derived from the dispute id, so a
// duplicate charge.dispute.created webhook posts nothing.
func Open(l *ledger.Ledger, d *Dispute) error {
	recv, losses, fees := accounts(l, d.PSP, d.Currency)
	entries := []ledger.Entry{{Account: losses, Direction: ledger.Debit, Amount: d.Amount}}
	if d.Fee > 0 { // some networks (e.g. Cartes Bancaires in SEPA on Stripe) charge no received fee
		entries = append(entries, ledger.Entry{Account: fees, Direction: ledger.Debit, Amount: d.Fee})
	}
	entries = append(entries, ledger.Entry{Account: recv, Direction: ledger.Credit, Amount: d.Amount + d.Fee})
	_, _, err := l.Post(ledger.Transaction{ID: "dispute_opened:" + d.ID, Description: "chargeback " + d.PaymentID, Entries: entries})
	if err == nil {
		d.Status = NeedsResponse
	}
	return err
}

// SubmitEvidence moves the dispute to review (the issuer decides, typically in 60-75 days).
func SubmitEvidence(d *Dispute) error {
	if d.Status != NeedsResponse {
		return fmt.Errorf("%w: evidence in %s", ErrState, d.Status)
	}
	d.Status = UnderReview
	return nil
}

// Close books the outcome. Won: the disputed amount comes back, the fee does not.
// Lost: nothing moves; the loss booked at Open stays.
func Close(l *ledger.Ledger, d *Dispute, won bool) error {
	if d.Status != UnderReview && d.Status != NeedsResponse {
		return fmt.Errorf("%w: close in %s", ErrState, d.Status)
	}
	if !won {
		d.Status = Lost
		return nil
	}
	recv, losses, _ := accounts(l, d.PSP, d.Currency)
	_, _, err := l.Post(ledger.Transaction{ID: "dispute_won:" + d.ID, Description: "chargeback reversed " + d.PaymentID,
		Entries: []ledger.Entry{
			{Account: recv, Direction: ledger.Debit, Amount: d.Amount},
			{Account: losses, Direction: ledger.Credit, Amount: d.Amount},
		}})
	if err == nil {
		d.Status = Won
	}
	return err
}
go
package dispute

import (
	"testing"

	"academy/payment-processing-architecture/ledger"
)

func TestWonDisputeReturnsAmountButNotFee(t *testing.T) {
	l := ledger.New(nil)
	d := &Dispute{ID: "dp_1", PaymentID: "pi_1", PSP: "stripe", Currency: "USD", Amount: 5_000, Fee: 1_500}
	if err := Open(l, d); err != nil {
		t.Fatal(err)
	}
	if err := Open(l, d); err != nil { // duplicate webhook
		t.Fatal(err)
	}
	if got := l.Balance("psp_receivable:stripe:USD"); got != -6_500 {
		t.Fatalf("receivable after open: %d", got)
	}
	if err := SubmitEvidence(d); err != nil {
		t.Fatal(err)
	}
	if err := Close(l, d, true); err != nil {
		t.Fatal(err)
	}
	if l.Balance("chargeback_losses:USD") != 0 || l.Balance("dispute_fees:USD") != 1_500 {
		t.Fatalf("losses %d fees %d", l.Balance("chargeback_losses:USD"), l.Balance("dispute_fees:USD"))
	}
	if len(l.Journal()) != 2 || l.TrialBalance()["USD"] != 0 {
		t.Fatal("want exactly two balanced postings")
	}
}

func TestLostDisputeKeepsTheLoss(t *testing.T) {
	l := ledger.New(nil)
	d := &Dispute{ID: "dp_2", PaymentID: "pi_2", PSP: "adyen", Currency: "EUR", Amount: 2_000, Fee: 0}
	if err := Open(l, d); err != nil { // no fee line when the fee is zero
		t.Fatal(err)
	}
	if err := Close(l, d, false); err != nil || d.Status != Lost {
		t.Fatal(err)
	}
	if err := SubmitEvidence(d); err == nil {
		t.Fatal("no evidence after the outcome")
	}
	if l.Balance("chargeback_losses:EUR") != 2_000 {
		t.Fatal("loss must stay booked")
	}
}

Fraud and risk engine: velocity, rules, score thresholds, model budget:

go
// Package fraud is a small real-time decision engine: velocity counters, ordered rules,
// a risk score with a hard latency budget, and four outcomes (allow, request 3DS, review, block).
// The default thresholds mirror Stripe Radar's documented ones: 65+ elevated, 75+ high.
package fraud

import (
	"context"
	"sort"
	"strings"
	"sync"
	"time"
)

// Action is the decision.
type Action string

const (
	Allow     Action = "allow"
	Request3D Action = "request_3ds" // step-up: SCA challenge, liability shift to the issuer
	Review    Action = "review"      // human review queue
	Block     Action = "block"
)

// Payment holds the features known at decision time.
type Payment struct {
	AmountUSD       int64  // minor units, normalized
	CardFingerprint string // PSP's stable card id, never the PAN
	BIN             string // first 6-8 digits: issuer, country, debit/credit/prepaid
	CardCountry     string
	IPCountry       string
	IP              string
	DeviceID        string // device fingerprint from the checkout SDK
	Email           string
	CustomerAgeDays int
	Is3DSCapable    bool
	At              time.Time
}

// Velocity counts events per key in a sliding window.
type Velocity struct {
	mu     sync.Mutex
	window time.Duration
	hits   map[string][]time.Time
}

// NewVelocity returns a counter with the given window.
func NewVelocity(w time.Duration) *Velocity {
	return &Velocity{window: w, hits: map[string][]time.Time{}}
}

// Add records one event and returns the count in the window, including this one.
func (v *Velocity) Add(key string, at time.Time) int {
	v.mu.Lock()
	defer v.mu.Unlock()
	keep := v.hits[key][:0]
	for _, t := range v.hits[key] {
		if at.Sub(t) < v.window {
			keep = append(keep, t)
		}
	}
	keep = append(keep, at)
	v.hits[key] = keep
	return len(keep)
}

// Signals are derived features.
type Signals struct {
	CardsPerDevice  int // distinct attempts per device in the window: card testing
	AttemptsPerCard int
	AttemptsPerIP   int
	Score           int // 0-99, -1 when the model missed its budget
}

// Rule is one line of the rules engine.
type Rule struct {
	Name   string
	Action Action
	When   func(p Payment, s Signals) bool
}

// Scorer is the ML model behind a network call.
type Scorer interface {
	Score(ctx context.Context, p Payment) (int, error)
}

// Engine evaluates in a fixed order: allow-list, block, review, request-3DS, then score.
type Engine struct {
	Allowlist   map[string]bool // trusted card fingerprints
	Rules       []Rule
	Model       Scorer
	ModelBudget time.Duration // e.g. 50 ms of a ~300 ms checkout budget
	ReviewAt    int           // default 65
	BlockAt     int           // default 75
	byDevice    *Velocity
	byCard      *Velocity
	byIP        *Velocity
}

// NewEngine uses 10-minute velocity windows and Radar-like thresholds.
func NewEngine(model Scorer, rules ...Rule) *Engine {
	return &Engine{Allowlist: map[string]bool{}, Rules: rules, Model: model, ModelBudget: 50 * time.Millisecond,
		ReviewAt: 65, BlockAt: 75,
		byDevice: NewVelocity(10 * time.Minute), byCard: NewVelocity(10 * time.Minute), byIP: NewVelocity(10 * time.Minute)}
}

// Decision is the answer with its reasons (store it: you need it for disputes and tuning).
type Decision struct {
	Action  Action
	Score   int
	Reasons []string
}

// Decide never blocks longer than the model budget; if the model is late it decides on rules.
func (e *Engine) Decide(ctx context.Context, p Payment) Decision {
	e.byDevice.Add("dev:"+p.DeviceID+"|"+p.CardFingerprint, p.At)
	s := Signals{
		CardsPerDevice:  e.distinctCards(p.DeviceID, p.At),
		AttemptsPerCard: e.byCard.Add("card:"+p.CardFingerprint, p.At),
		AttemptsPerIP:   e.byIP.Add("ip:"+p.IP, p.At),
		Score:           -1,
	}
	if e.Allowlist[p.CardFingerprint] {
		return Decision{Action: Allow, Score: -1, Reasons: []string{"allowlist"}}
	}
	if e.Model != nil {
		mctx, cancel := context.WithTimeout(ctx, e.ModelBudget)
		if sc, err := e.Model.Score(mctx, p); err == nil {
			s.Score = sc
		}
		cancel()
	}
	var reasons []string
	best := Allow
	for _, r := range e.ordered() {
		if r.When(p, s) {
			reasons = append(reasons, r.Name)
			if rank(r.Action) > rank(best) {
				best = r.Action
			}
		}
	}
	switch {
	case s.Score >= e.BlockAt:
		reasons = append(reasons, "score>=block")
		best = Block
	case s.Score >= e.ReviewAt && rank(best) < rank(Review):
		reasons = append(reasons, "score>=review")
		if p.Is3DSCapable {
			best = Request3D // cheaper than a human: let the issuer authenticate
		} else {
			best = Review
		}
	case s.Score < 0:
		reasons = append(reasons, "model_timeout:rules_only")
	}
	return Decision{Action: best, Score: s.Score, Reasons: reasons}
}

// distinctCards counts card fingerprints seen on one device inside the window.
func (e *Engine) distinctCards(device string, at time.Time) int {
	e.byDevice.mu.Lock()
	defer e.byDevice.mu.Unlock()
	n := 0
	prefix := "dev:" + device + "|"
	for k, v := range e.byDevice.hits {
		if !strings.HasPrefix(k, prefix) {
			continue
		}
		for _, t := range v {
			if at.Sub(t) < e.byDevice.window {
				n++
				break
			}
		}
	}
	return n
}

func (e *Engine) ordered() []Rule {
	rs := append([]Rule(nil), e.Rules...)
	sort.SliceStable(rs, func(i, j int) bool { return rank(rs[i].Action) > rank(rs[j].Action) })
	return rs
}

func rank(a Action) int {
	switch a {
	case Block:
		return 3
	case Review:
		return 2
	case Request3D:
		return 1
	}
	return 0
}

// DefaultRules is a starting set; tune each with backtests before turning it on.
func DefaultRules() []Rule {
	return []Rule{
		{"card_testing: >5 cards on one device in 10m", Block, func(p Payment, s Signals) bool { return s.CardsPerDevice > 5 }},
		{"velocity: >3 attempts per card in 10m", Review, func(p Payment, s Signals) bool { return s.AttemptsPerCard > 3 }},
		{"geo: card country != IP country and amount > 250 USD", Request3D, func(p Payment, s Signals) bool {
			return p.CardCountry != p.IPCountry && p.AmountUSD > 25_000
		}},
		{"new customer, large first order", Request3D, func(p Payment, s Signals) bool {
			return p.CustomerAgeDays < 1 && p.AmountUSD > 50_000
		}},
	}
}
go
package fraud

import (
	"context"
	"fmt"
	"testing"
	"time"
)

type fixedScore int

func (f fixedScore) Score(context.Context, Payment) (int, error) { return int(f), nil }

type slowModel struct{}

func (slowModel) Score(ctx context.Context, _ Payment) (int, error) {
	select {
	case <-ctx.Done():
		return 0, ctx.Err()
	case <-time.After(time.Second):
		return 10, nil
	}
}

var t0 = time.Date(2026, 11, 26, 12, 0, 0, 0, time.UTC)

func base() Payment {
	return Payment{AmountUSD: 4_999, CardFingerprint: "fp_1", BIN: "424242", CardCountry: "US", IPCountry: "US",
		IP: "203.0.113.7", DeviceID: "dev_1", CustomerAgeDays: 400, Is3DSCapable: true, At: t0}
}

func TestLowRiskAllowed(t *testing.T) {
	d := NewEngine(fixedScore(12), DefaultRules()...).Decide(context.Background(), base())
	if d.Action != Allow {
		t.Fatalf("got %+v", d)
	}
}

func TestScoreThresholds(t *testing.T) {
	if d := NewEngine(fixedScore(70), DefaultRules()...).Decide(context.Background(), base()); d.Action != Request3D {
		t.Fatalf("elevated + 3DS-capable card should step up, got %+v", d)
	}
	p := base()
	p.Is3DSCapable = false
	if d := NewEngine(fixedScore(70), DefaultRules()...).Decide(context.Background(), p); d.Action != Review {
		t.Fatalf("elevated without 3DS should go to review, got %+v", d)
	}
	if d := NewEngine(fixedScore(80), DefaultRules()...).Decide(context.Background(), base()); d.Action != Block {
		t.Fatalf("got %+v", d)
	}
}

func TestCardTestingIsBlocked(t *testing.T) {
	e := NewEngine(fixedScore(5), DefaultRules()...)
	var d Decision
	for i := 0; i < 7; i++ {
		p := base()
		p.CardFingerprint = fmt.Sprintf("fp_%d", i)
		p.AmountUSD = 100
		p.At = t0.Add(time.Duration(i) * time.Second)
		d = e.Decide(context.Background(), p)
	}
	if d.Action != Block {
		t.Fatalf("7 cards on one device in seconds: got %+v", d)
	}
}

func TestGeoMismatchStepsUp(t *testing.T) {
	p := base()
	p.IPCountry, p.AmountUSD = "NL", 30_000
	if d := NewEngine(fixedScore(20), DefaultRules()...).Decide(context.Background(), p); d.Action != Request3D {
		t.Fatalf("got %+v", d)
	}
}

func TestModelTimeoutFallsBackToRules(t *testing.T) {
	e := NewEngine(slowModel{}, DefaultRules()...)
	start := time.Now()
	d := e.Decide(context.Background(), base())
	if time.Since(start) > 200*time.Millisecond {
		t.Fatal("decision exceeded the latency budget")
	}
	if d.Action != Allow || d.Score != -1 {
		t.Fatalf("got %+v", d)
	}
}

func TestAllowlistWins(t *testing.T) {
	e := NewEngine(fixedScore(99), DefaultRules()...)
	e.Allowlist["fp_1"] = true
	if d := e.Decide(context.Background(), base()); d.Action != Allow {
		t.Fatalf("got %+v", d)
	}
}

Dunning: soft vs hard declines, a bounded schedule:

go
// Package dunning decides whether and when to retry a failed recurring charge.
// Hard declines need a new payment method; soft declines are retried on a schedule
// that stops after a maximum number of attempts or a maximum duration (Stripe's default
// Smart Retries policy for new accounts: up to 8 retries within 2 weeks).
package dunning

import "time"

// hard is the list Stripe documents as "can't automatically retry" for subscriptions.
var hard = map[string]bool{
	"incorrect_number": true, "lost_card": true, "pickup_card": true, "stolen_card": true,
	"revocation_of_authorization": true, "revocation_of_all_authorizations": true,
	"authentication_required": true, "highest_risk_level": true, "transaction_not_allowed": true,
}

// Kind of a decline.
type Kind int

const (
	Soft Kind = iota // retry later: insufficient_funds, try_again_later, processing_error...
	Hard             // stop: ask the customer for a new card (or for authentication)
)

// Classify maps a decline code to Soft or Hard. Unknown codes are Soft but count toward the cap.
func Classify(code string) Kind {
	if hard[code] {
		return Hard
	}
	return Soft
}

// Policy is a fixed retry schedule (a "smart" schedule replaces Delays with a model's choice).
type Policy struct {
	Delays      []time.Duration // delay after attempt 1, 2, 3...
	MaxAttempts int             // including the first attempt
	MaxDuration time.Duration   // from the first failure
}

// Default retries 1, 2, 4 and 6 days after each failure (days 1, 3, 7 and 13):
// at most 5 attempts, all inside 14 days.
func Default() Policy {
	d := 24 * time.Hour
	return Policy{Delays: []time.Duration{d, 2 * d, 4 * d, 6 * d}, MaxAttempts: 5, MaxDuration: 14 * d}
}

// Decision tells the billing job what to do next.
type Decision struct {
	Retry   bool
	At      time.Time
	Notify  bool   // e-mail the customer (update card / authenticate)
	Outcome string // retry, needs_new_payment_method, exhausted
}

// Next is called after attempt number `attempt` (1-based) failed with `code`.
func (p Policy) Next(attempt int, code string, firstFailure, now time.Time) Decision {
	if Classify(code) == Hard {
		return Decision{Notify: true, Outcome: "needs_new_payment_method"}
	}
	if attempt >= p.MaxAttempts || attempt > len(p.Delays) {
		return Decision{Notify: true, Outcome: "exhausted"}
	}
	at := now.Add(p.Delays[attempt-1])
	if at.Sub(firstFailure) > p.MaxDuration {
		return Decision{Notify: true, Outcome: "exhausted"}
	}
	return Decision{Retry: true, At: at, Notify: attempt == 1, Outcome: "retry"}
}
go
package dunning

import (
	"testing"
	"time"
)

func TestHardDeclineStopsImmediately(t *testing.T) {
	now := time.Date(2026, 11, 1, 9, 0, 0, 0, time.UTC)
	d := Default().Next(1, "stolen_card", now, now)
	if d.Retry || d.Outcome != "needs_new_payment_method" || !d.Notify {
		t.Fatalf("got %+v", d)
	}
}

func TestSoftDeclineFollowsScheduleThenStops(t *testing.T) {
	p := Default()
	first := time.Date(2026, 11, 1, 9, 0, 0, 0, time.UTC)
	now := first
	var outcomes []string
	for attempt := 1; attempt <= 6; attempt++ {
		d := p.Next(attempt, "insufficient_funds", first, now)
		outcomes = append(outcomes, d.Outcome)
		if !d.Retry {
			break
		}
		now = d.At
	}
	want := []string{"retry", "retry", "retry", "retry", "exhausted"}
	if len(outcomes) != len(want) {
		t.Fatalf("got %v", outcomes)
	}
	for i := range want {
		if outcomes[i] != want[i] {
			t.Fatalf("got %v, want %v", outcomes, want)
		}
	}
	// retries on days 1, 3, 7 and 13; attempt 5 fails on day 13: exhausted by the attempt cap.
	if now.Sub(first) != 13*24*time.Hour {
		t.Fatalf("last retry at %v", now.Sub(first))
	}
}

Reconciliation against a settlement file:

go
// Package recon matches our payment records against a PSP settlement file
// (for example a Stripe payout reconciliation report or an Adyen settlement detail report,
// reduced here to five columns). It finds what each side has that the other does not.
package recon

import (
	"encoding/csv"
	"errors"
	"fmt"
	"io"
	"sort"
	"strconv"
	"time"
)

// Row is one settled line: psp_ref,type,gross,fee,currency.
type Row struct {
	PSPRef   string
	Type     string // charge, refund, chargeback, fee
	Gross    int64
	Fee      int64
	Currency string
}

// Record is what our database says.
type Record struct {
	PSPRef    string // empty when the attempt is "unknown" (no answer from the PSP)
	IntentKey string // our provider idempotency key
	Amount    int64
	Currency  string
	CreatedAt time.Time
}

// Report is the outcome; every non-empty list is a ticket or an automatic fix.
type Report struct {
	Matched        int
	MissingAtPSP   []Record // we booked it, PSP did not settle it (yet): investigate after the cutoff
	MissingLocally []Row    // PSP settled money we never booked: ambiguous outcome or a bug
	AmountMismatch []string
	Fees           int64
}

// ParseCSV reads the file with a header line.
func ParseCSV(r io.Reader) ([]Row, error) {
	cr := csv.NewReader(r)
	all, err := cr.ReadAll()
	if err != nil {
		return nil, err
	}
	if len(all) == 0 {
		return nil, errors.New("recon: empty file")
	}
	var out []Row
	for i, rec := range all[1:] {
		if len(rec) != 5 {
			return nil, fmt.Errorf("recon: line %d: want 5 columns", i+2)
		}
		gross, err1 := strconv.ParseInt(rec[2], 10, 64)
		fee, err2 := strconv.ParseInt(rec[3], 10, 64)
		if err1 != nil || err2 != nil {
			return nil, fmt.Errorf("recon: line %d: amounts must be integer minor units", i+2)
		}
		out = append(out, Row{PSPRef: rec[0], Type: rec[1], Gross: gross, Fee: fee, Currency: rec[4]})
	}
	return out, nil
}

// Reconcile compares charges. Records newer than cutoff are not yet expected in the file.
func Reconcile(ours []Record, file []Row, cutoff time.Time) Report {
	var rep Report
	byRef := map[string]Row{}
	for _, r := range file {
		rep.Fees += r.Fee
		if r.Type == "charge" {
			byRef[r.PSPRef] = r
		}
	}
	seen := map[string]bool{}
	for _, o := range ours {
		r, ok := byRef[o.PSPRef]
		switch {
		case !ok && o.CreatedAt.Before(cutoff):
			rep.MissingAtPSP = append(rep.MissingAtPSP, o)
		case !ok:
		case r.Gross != o.Amount || r.Currency != o.Currency:
			rep.AmountMismatch = append(rep.AmountMismatch,
				fmt.Sprintf("%s: ours %d %s, psp %d %s", o.PSPRef, o.Amount, o.Currency, r.Gross, r.Currency))
			seen[o.PSPRef] = true
		default:
			rep.Matched++
			seen[o.PSPRef] = true
		}
	}
	for ref, r := range byRef {
		if !seen[ref] {
			rep.MissingLocally = append(rep.MissingLocally, r)
		}
	}
	sort.Slice(rep.MissingLocally, func(i, j int) bool { return rep.MissingLocally[i].PSPRef < rep.MissingLocally[j].PSPRef })
	return rep
}
go
package recon

import (
	"strings"
	"testing"
	"time"
)

const file = `psp_ref,type,gross,fee,currency
ch_1,charge,1099,62,USD
ch_2,charge,2500,103,USD
ch_9,charge,4000,146,USD
re_1,refund,-500,0,USD
`

func TestReconcile(t *testing.T) {
	rows, err := ParseCSV(strings.NewReader(file))
	if err != nil {
		t.Fatal(err)
	}
	day := time.Date(2026, 11, 25, 0, 0, 0, 0, time.UTC)
	ours := []Record{
		{PSPRef: "ch_1", Amount: 1099, Currency: "USD", CreatedAt: day},
		{PSPRef: "ch_2", Amount: 2000, Currency: "USD", CreatedAt: day},                    // we booked less
		{PSPRef: "ch_3", Amount: 700, Currency: "USD", CreatedAt: day},                     // PSP never settled it
		{PSPRef: "ch_4", Amount: 800, Currency: "USD", CreatedAt: day.Add(48 * time.Hour)}, // too new to judge
	}
	rep := Reconcile(ours, rows, day.Add(24*time.Hour))
	if rep.Matched != 1 || len(rep.AmountMismatch) != 1 || len(rep.MissingAtPSP) != 1 || rep.MissingAtPSP[0].PSPRef != "ch_3" {
		t.Fatalf("got %+v", rep)
	}
	// ch_9: money moved that we never booked, the classic "unknown attempt" that succeeded
	if len(rep.MissingLocally) != 1 || rep.MissingLocally[0].PSPRef != "ch_9" {
		t.Fatalf("got %+v", rep.MissingLocally)
	}
	if rep.Fees != 311 {
		t.Fatalf("fees %d", rep.Fees)
	}
}

func TestRejectsDecimalAmounts(t *testing.T) {
	_, err := ParseCSV(strings.NewReader("psp_ref,type,gross,fee,currency\nch_1,charge,10.99,0.62,USD\n"))
	if err == nil {
		t.Fatal("a settlement file in major units must be converted explicitly, not parsed as float")
	}
}

The lab program that runs every scenario in one process:

go
// Command demo runs the chapter's lab in one process: no PSP, no database, no broker.
package main

import (
	"context"
	"fmt"
	"strings"
	"time"

	"academy/payment-processing-architecture/checkout"
	"academy/payment-processing-architecture/dispute"
	"academy/payment-processing-architecture/dunning"
	"academy/payment-processing-architecture/fraud"
	"academy/payment-processing-architecture/money"
	"academy/payment-processing-architecture/payment"
	"academy/payment-processing-architecture/recon"
	"academy/payment-processing-architecture/webhook"
)

func main() {
	ctx := context.Background()

	fmt.Println("== 1. lost response, same key, one charge")
	stripe := &payment.FakePSP{ID: "stripe", LoseResponses: 1}
	adyen := &payment.FakePSP{ID: "adyen"}
	svc := payment.NewService(200*time.Millisecond, stripe, adyen)
	p, _, _ := svc.Create("m_1", "order-1001", 2500, "USD", "order-1001")
	got, _ := svc.Confirm(ctx, p.ID, "pm_card_visa", false)
	again, replayed, _ := svc.Create("m_1", "order-1001", 2500, "USD", "order-1001")
	fmt.Printf("intent=%s status=%s psp_charges=%d replayed_create=%v same_id=%v\n",
		got.ID, got.Status, stripe.Charges, replayed, again.ID == got.ID)

	fmt.Println("== 2. ambiguous outcome: park, do not fail over")
	stripe.LoseResponses, stripe.LookupDown = 9, true
	q, _, _ := svc.Create("m_1", "order-1002", 4000, "USD", "order-1002")
	got, _ = svc.Confirm(ctx, q.ID, "pm_card_visa", false)
	fmt.Printf("status=%s unknown_attempts=%d adyen_charges=%d\n", got.Status, len(svc.UnknownAttempts()), adyen.Charges)
	stripe.LoseResponses, stripe.LookupDown = 0, false
	got, _ = svc.Confirm(ctx, q.ID, "pm_card_visa", false)
	fmt.Printf("after recovery: status=%s stripe_charges=%d\n", got.Status, stripe.Charges)

	fmt.Println("== 3. hold, partial capture, refund, trial balance")
	h, _, _ := svc.Create("m_1", "hotel-7", 10000, "USD", "hotel-7")
	_, _ = svc.Confirm(ctx, h.ID, "pm_card_visa", true)
	_, _ = svc.Capture(ctx, h.ID, 8250)
	_ = svc.Refund(ctx, h.ID, "rf-hotel-7-1", 1000)
	fmt.Printf("sales=%d refunds=%d receivable=%d trial=%v journal_rows=%d outbox=%d\n",
		svc.Ledger.Balance("sales:USD"), svc.Ledger.Balance("refunds:USD"),
		svc.Ledger.Balance("psp_receivable:stripe:USD"), svc.Ledger.TrialBalance(),
		len(svc.Ledger.Journal()), len(svc.Outbox.Pending(100)))

	fmt.Println("== 4. money")
	parts, _ := money.Money{Amount: 100, Currency: "USD"}.Allocate(1, 1, 1)
	eur, _ := money.Convert(money.Money{Amount: 1000, Currency: "USD"}, "EUR", "0.9235")
	fmt.Printf("split 1.00 USD three ways: %v %v %v | 10.00 USD @0.9235 = %v\n", parts[0], parts[1], parts[2], eur)

	fmt.Println("== 5. webhook signature")
	secret := []byte("whsec_lab")
	body := []byte(`{"id":"evt_1","type":"payment_intent.succeeded"}`)
	now := time.Unix(1798765432, 0)
	v := webhook.Verifier{Secrets: [][]byte{secret}, Tolerance: 5 * time.Minute, Now: func() time.Time { return now }}
	fmt.Println("valid:", v.Verify(body, webhook.Header(secret, now, body)))
	fmt.Println("tampered:", v.Verify([]byte(strings.Replace(string(body), "evt_1", "evt_2", 1)), webhook.Header(secret, now, body)))
	fmt.Println("replayed 10m later:", v.Verify(body, webhook.Header(secret, now.Add(-10*time.Minute), body)))

	fmt.Println("== 6. fraud decisions")
	eng := fraud.NewEngine(nil, fraud.DefaultRules()...)
	base := fraud.Payment{AmountUSD: 4999, CardFingerprint: "fp_a", CardCountry: "US", IPCountry: "US",
		IP: "203.0.113.7", DeviceID: "dev_9", CustomerAgeDays: 300, Is3DSCapable: true, At: now}
	fmt.Println("normal:", eng.Decide(ctx, base).Action)
	geo := base
	geo.IPCountry, geo.AmountUSD = "NL", 30000
	fmt.Println("geo mismatch, 300 USD:", eng.Decide(ctx, geo).Action)
	var last fraud.Decision
	for i := 0; i < 7; i++ {
		c := base
		c.CardFingerprint, c.AmountUSD, c.DeviceID = fmt.Sprintf("fp_t%d", i), 100, "dev_bot"
		last = eng.Decide(ctx, c)
	}
	fmt.Println("7 cards, one device:", last.Action, last.Reasons)

	fmt.Println("== 7. reconciliation")
	rows, _ := recon.ParseCSV(strings.NewReader("psp_ref,type,gross,fee,currency\nstripe_ch_1,charge,2500,103,USD\nstripe_ch_2,charge,4000,146,USD\nstripe_ch_9,charge,1200,65,USD\n"))
	rep := recon.Reconcile([]recon.Record{
		{PSPRef: "stripe_ch_1", Amount: 2500, Currency: "USD"},
		{PSPRef: "stripe_ch_2", Amount: 4000, Currency: "USD"},
	}, rows, now)
	fmt.Printf("matched=%d missing_locally=%d (%s) fees=%d\n", rep.Matched, len(rep.MissingLocally), rep.MissingLocally[0].PSPRef, rep.Fees)

	fmt.Println("== 8. chargeback: open, win")
	d := &dispute.Dispute{ID: "dp_1", PaymentID: "pi_0001", PSP: "stripe", Currency: "USD", Amount: 2500, Fee: 1500}
	_ = dispute.Open(svc.Ledger, d)
	opened := svc.Ledger.Balance("psp_receivable:stripe:USD")
	_ = dispute.SubmitEvidence(d)
	_ = dispute.Close(svc.Ledger, d, true)
	fmt.Printf("receivable after open=%d after win=%d fee_kept=%d status=%s trial=%v\n",
		opened, svc.Ledger.Balance("psp_receivable:stripe:USD"), svc.Ledger.Balance("dispute_fees:USD"), d.Status, svc.Ledger.TrialBalance())

	fmt.Println("== 9. dunning")
	pol := dunning.Default()
	fmt.Println("stolen_card:", pol.Next(1, "stolen_card", now, now).Outcome)
	nd := pol.Next(1, "insufficient_funds", now, now)
	fmt.Println("insufficient_funds:", nd.Outcome, "in", nd.At.Sub(now))

	fmt.Println("== 10. checkout saga: shipment fails, hold is voided")
	var log []string
	o := &checkout.Orchestrator{}
	err := o.Run(ctx, "order-77", []checkout.Step{
		{Name: "reserve_stock", Do: func(context.Context, string) error { return nil },
			Undo: func(context.Context, string) error { log = append(log, "released"); return nil }},
		{Name: "authorize", Do: func(context.Context, string) error { return nil },
			Undo: func(context.Context, string) error { log = append(log, "voided"); return nil }},
		{Name: "book_shipment", Do: func(context.Context, string) error { return fmt.Errorf("carrier: no slot") }},
	})
	fmt.Println(err, log)
}

The Go angle ​

Go featureUse for paymentsNote
int64 minor units in a structThe money typeOverflow-checked Add; never float64
math/big.Rat, math/big.IntExact FX conversion, half-even roundingbig.Rat.SetString("0.9235") is exact
github.com/shopspring/decimalDecimal arithmetic (stripe-go v87 depends on it)Not used here: math/big suffices
context.WithTimeoutPer-PSP-call budget, fraud model budgetcontext.DeadlineExceeded is an unknown outcome after sending
errors.Is with sentinel errorsErrTimeout, ErrUnavailable, ErrAmbiguous drive failover decisionsWrap with %w
crypto/hmac + crypto/sha256, hmac.EqualWebhook signaturesConstant-time compare
encoding/csvSettlement filesParse amounts as integers
database/sql / pgx with BEGIN ... COMMITOne transaction for state + ledger + outboxsync.Mutex stands in for it in this module
github.com/stripe/stripe-go/v87stripe.NewClient, sc.V1PaymentIntents, webhook.ConstructEventgo 1.24; automatic retries (2 by default) with idempotency keys
go test -raceConcurrent ledger postings and webhook deliveriesTestInvariantsUnderConcurrentTransfers

Laravel ​

The Laravel side uses Laravel Cashier (Stripe) for the integration, raw query-builder code for the ledger and the inbox, and queued jobs for webhooks and reconciliation. All files pass php -l; no Laravel application was booted for this chapter.

Before ​

The card number posted to the server and logged with the CVV, float money, Http::retry(3, 200) that re-sends a charge after a timeout, a mutable balance and a synchronous e-mail:

php
<?php

namespace App\Http\Controllers;

use App\Models\Order;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Mail;

// The naive checkout: every comment is a production incident.
class BeforeCheckoutController extends Controller
{
    public function pay(Request $request, Order $order)
    {
        // Raw card number posted to our server: the whole app is now in PCI DSS scope (SAQ D).
        $card = $request->input('card_number');

        // Float money, no idempotency key, a retry policy that re-sends a charge after a timeout.
        $response = Http::retry(3, 200)->post('https://psp.example.test/charge', [
            'amount' => $order->total * 1.0,
            'card' => $card,
        ]);

        logger()->info('charge', ['card' => $card, 'cvv' => $request->input('cvv')]); // PAN and CVV in logs

        $order->update(['status' => 'paid', 'balance' => $order->balance - $order->total]); // mutable balance
        Mail::to($request->user())->send(new \App\Mail\Receipt($order)); // lost if the process dies here

        return response()->json($response->json());
    }
}

After ​

Checkout through Cashier's Stripe client, in an order where every crash point is recoverable: (1) the payments row (pay_<order>, one per order) exists before any PSP call; (2) the PaymentIntent is created with the idempotency key pay_<order>:intent and metadata.payment_id, always with the same parameters, so a retry after a crash gets the same intent back (within Stripe's 24-hour key window) and the webhook worker can find the row through the metadata even if step 3 never ran; (3) the intent id is attached only whereNull('stripe_payment_intent_id'), never overwritten, and a second checkout for the order reuses the attached intent. A saved card is confirmed in a separate call with its own key. The refund route checks Gate::authorize('refund', $order), requires the client's Idempotency-Key header (stored on the refunds row; a retry replays the row, a different amount is 422), reserves the amount in that row (pending, first_sent_at) before calling Stripe with the row's id as Stripe's key, and books nothing itself. A replay resends to Stripe only while the row has no Stripe refund id and is younger than 23 hours (below Stripe's 24-hour key retention); after that the row becomes needs_reconciliation, the route answers 409 and nothing is sent, so an expired key can never create a second refund. A row maps to exactly one Stripe refund: if the worker sees a second provider refund for the same row it throws (retry, then dead letter) instead of acking it. The controller never sets a status: the worker does, from verified webhooks. Limit: after Stripe's key window a crash between steps 2 and 3 is only found by the webhook fallback or by reconciliation:

php
<?php

namespace App\Http\Controllers;

use App\Models\Order;
use Illuminate\Http\Request;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Gate;
use Illuminate\Support\Str;
use Laravel\Cashier\Cashier;
use RuntimeException;

// Checkout on Stripe through Cashier's Stripe client. The card never touches our server
// (Payment Element in an iframe), so the server sees pm_... ids only.
// Order of steps, so every crash point is recoverable:
//   1. the payments row exists before any PSP call (pay_<order>, one per order);
//   2. the PSP call carries a key derived from that row and metadata.payment_id, so a retry
//      after a crash gets the SAME PaymentIntent back (Stripe keeps keys at least 24 h) and a
//      webhook can find the row even if step 3 never ran;
//   3. the intent id is attached only if the row has none: it is never overwritten.
class CheckoutController extends Controller
{
    private const MERCHANT = 'shop';                              // single-merchant monolith

    private const RESEND_WINDOW_HOURS = 23;                       // below Stripe's 24 h key retention

    // Payment Element flow: the browser confirms with the client secret.
    public function start(Request $request, Order $order)
    {
        $intent = $this->intentFor($request, $order);

        return view('checkout', ['clientSecret' => $intent->client_secret, 'order' => $order]);
    }

    // Saved card, confirmed on the server; 3-D Secure sends the customer to Cashier's page.
    public function charge(Request $request, Order $order)
    {
        $intent = $this->intentFor($request, $order);
        if (in_array($intent->status, ['requires_payment_method', 'requires_confirmation'], true)) {
            $pm = (string) $request->input('payment_method');
            $intent = Cashier::stripe()->paymentIntents->confirm($intent->id, ['payment_method' => $pm],
                ['idempotency_key' => "{$this->paymentId($order)}:confirm:{$pm}"]);   // a double click confirms once
        }
        if ($intent->status === 'requires_action') {
            return redirect()->route('cashier.payment', [$intent->id, 'redirect' => route('orders.show', $order)]);
        }

        return response()->json(['status' => $intent->status]);   // the webhook books the result
    }

    // Refunds need an Idempotency-Key header from the client (400 without it). The key is
    // stored on the refund row: a retry with the same key and amount replays that row (and
    // resends to Stripe with the row id as Stripe's key if the first call never stored a
    // refund id); the same key with another amount is 422. The amount is reserved (row
    // `pending`) BEFORE calling Stripe; the worker books it from refund.* events. A Stripe
    // error leaves the row pending: reserved until the webhook or reconciliation resolves it.
    public function refund(Request $request, Order $order)
    {
        Gate::authorize('refund', $order);                       // OrderPolicy: 403 otherwise
        $clientKey = (string) $request->header('Idempotency-Key', '');
        if ($clientKey === '' || strlen($clientKey) > 255) {
            abort(400, 'Idempotency-Key header required');
        }
        $amount = (int) $request->input('amount');
        $refund = DB::transaction(function () use ($order, $amount, $clientKey) {
            $payment = DB::table('payments')->where('id', $this->paymentId($order))->lockForUpdate()->first();
            if ($payment === null) {
                abort(422, 'no payment');
            }
            $existing = DB::table('refunds')->where(['payment_id' => $payment->id, 'client_key' => $clientKey])->first();
            if ($existing !== null) {
                abort_if((int) $existing->amount !== $amount, 422, 'Idempotency-Key reused with another amount');

                return $existing;                                   // replay: no new row, no new key
            }
            $open = (int) DB::table('refunds')->where('payment_id', $payment->id)
                ->whereIn('state', ['pending', 'needs_reconciliation'])->sum('amount');      // reserved
            if ($payment->status !== 'succeeded' || $amount <= 0
                || $payment->amount_refunded + $open + $amount > $payment->amount_received) {
                abort(422, 'refund not allowed');
            }
            $row = ['id' => 'rf_'.Str::ulid(), 'payment_id' => $payment->id, 'client_key' => $clientKey, 'amount' => $amount,
                'currency' => $payment->currency, 'state' => 'pending', 'stripe_refund_id' => null,
                'first_sent_at' => now(), 'created_at' => now(), 'updated_at' => now()];
            DB::table('refunds')->insert($row);

            return (object) $row;
        });
        if ($refund->stripe_refund_id === null && $refund->state === 'pending'
            && Carbon::parse($refund->first_sent_at)->lt(now()->subHours(self::RESEND_WINDOW_HOURS))) {
            // Past Stripe's key retention a resend could create a SECOND refund: stop, keep the
            // amount reserved, and let reconciliation (or the webhook) settle what happened.
            DB::table('refunds')->where('id', $refund->id)->where('state', 'pending')
                ->update(['state' => 'needs_reconciliation', 'updated_at' => now()]);

            return response()->json(['refund' => $refund->id, 'state' => 'needs_reconciliation'], 409);
        }
        if ($refund->stripe_refund_id === null && $refund->state === 'pending') {
            $intentId = DB::table('payments')->where('id', $this->paymentId($order))->value('stripe_payment_intent_id');
            $created = Cashier::stripe()->refunds->create(
                ['payment_intent' => $intentId, 'amount' => $amount, 'metadata' => ['refund_id' => $refund->id]],
                ['idempotency_key' => $refund->id],                 // the same Stripe refund on every replay
            );
            DB::table('refunds')->where('id', $refund->id)->whereNull('stripe_refund_id')->update(['stripe_refund_id' => $created->id]);
        }
        $state = DB::table('refunds')->where('id', $refund->id)->value('state');

        return response()->json(['refund' => $refund->id, 'state' => $state], 202);
    }

    private function paymentId(Order $order): string
    {
        return 'pay_'.$order->id;
    }

    // Returns the order's one PaymentIntent: the attached one, or one created with a key
    // derived from the payment row. Never a second intent for the same order.
    private function intentFor(Request $request, Order $order): object
    {
        $id = $this->paymentId($order);
        DB::table('payments')->insertOrIgnore([                    // step 1 (rerun-safe)
            'id' => $id, 'merchant_id' => self::MERCHANT, 'order_id' => (string) $order->id,
            'amount' => $order->total_minor, 'currency' => 'USD', 'status' => 'requires_payment_method',
            'created_at' => now(), 'updated_at' => now(),
        ]);
        $payment = DB::table('payments')->where('id', $id)->first();
        if ((int) $payment->amount !== (int) $order->total_minor) {
            throw new RuntimeException("order {$order->id} changed amount after its payment was created");
        }
        if ($payment->stripe_payment_intent_id !== null) {         // reuse, never replace
            return Cashier::stripe()->paymentIntents->retrieve($payment->stripe_payment_intent_id);
        }
        $intent = Cashier::stripe()->paymentIntents->create([      // step 2
            'amount' => $payment->amount,
            'currency' => 'usd',
            'customer' => $request->user()->stripe_id,
            'metadata' => ['payment_id' => $id, 'order_id' => (string) $order->id],
        ], ['idempotency_key' => "{$id}:intent"]);                // same parameters on every retry
        $attached = DB::table('payments')->where('id', $id)->whereNull('stripe_payment_intent_id')
            ->update(['stripe_payment_intent_id' => $intent->id, 'updated_at' => now()]);   // step 3
        if ($attached === 0 && DB::table('payments')->where('id', $id)->value('stripe_payment_intent_id') !== $intent->id) {
            throw new RuntimeException("payment {$id} already mapped to another intent");
        }

        return $intent;
    }
}

Refund authorization: the route calls Gate::authorize('refund', $order); the discovered OrderPolicy allows support staff or the order's owner, and a denial is a 403:

php
<?php

namespace App\Policies;

use App\Models\Order;
use App\Models\User;

// Discovered automatically (app/Policies next to app/Models). CheckoutController::refund
// calls Gate::authorize('refund', $order): a denial is an AuthorizationException, i.e. 403.
class OrderPolicy
{
    public function refund(User $user, Order $order): bool
    {
        // Support staff, or the order's owner if your business allows self-service refunds.
        return (bool) $user->is_support || $user->id === $order->user_id;
    }
}

The state machine as a backed enum with Stripe event mapping. canBecome() accepts a table edge or forward progress by rank, because webhooks arrive out of order and the local row may never have seen requires_confirmation: a payment still at requires_payment_method accepts payment_intent.succeeded. Nothing leaves succeeded or canceled:

php
<?php

namespace App\Payments;

use DomainException;

// Stripe PaymentIntent statuses as a backed enum with the legal transitions.
enum PaymentStatus: string
{
    case RequiresPaymentMethod = 'requires_payment_method';
    case RequiresConfirmation = 'requires_confirmation';
    case RequiresAction = 'requires_action';
    case Processing = 'processing';
    case RequiresCapture = 'requires_capture';
    case Succeeded = 'succeeded';
    case Canceled = 'canceled';

    /** @return list<self> */
    public function next(): array
    {
        return match ($this) {
            self::RequiresPaymentMethod => [self::RequiresConfirmation, self::Canceled],
            self::RequiresConfirmation => [self::RequiresAction, self::Processing, self::RequiresCapture,
                self::Succeeded, self::RequiresPaymentMethod, self::Canceled],
            self::RequiresAction => [self::Processing, self::RequiresCapture, self::Succeeded,
                self::RequiresPaymentMethod, self::Canceled],
            self::Processing => [self::Succeeded, self::RequiresPaymentMethod],
            self::RequiresCapture => [self::Succeeded, self::Canceled],
            self::Succeeded, self::Canceled => [],
        };
    }

    public function isTerminal(): bool
    {
        return $this === self::Succeeded || $this === self::Canceled;
    }

    // How far along the lifecycle a status is; skipped intermediate states are normal
    // because webhooks arrive out of order and we may never see requires_confirmation.
    public function rank(): int
    {
        return match ($this) {
            self::RequiresPaymentMethod => 0,
            self::RequiresConfirmation => 1,
            self::RequiresAction => 2,
            self::Processing, self::RequiresCapture => 3,
            self::Succeeded, self::Canceled => 4,
        };
    }

    // A verified PSP event may move the payment along a table edge OR forward past states
    // we never recorded (requires_payment_method -> succeeded). Nothing leaves a terminal state.
    public function canBecome(self $to): bool
    {
        if ($this->isTerminal()) {
            return false;
        }

        return in_array($to, $this->next(), true) || $to->rank() > $this->rank();
    }

    public function to(self $to): self
    {
        if (! $this->canBecome($to)) {
            throw new DomainException("invalid transition {$this->value} -> {$to->value}");
        }

        return $to;
    }

    // Map a Stripe event type to the status it implies.
    public static function fromStripeEvent(string $type): ?self
    {
        return match ($type) {
            'payment_intent.succeeded' => self::Succeeded,
            'payment_intent.processing' => self::Processing,
            'payment_intent.requires_action' => self::RequiresAction,
            'payment_intent.amount_capturable_updated' => self::RequiresCapture,
            'payment_intent.payment_failed' => self::RequiresPaymentMethod,
            'payment_intent.canceled' => self::Canceled,
            default => null,
        };
    }
}

The ledger service: balanced, idempotent postings in DB::transaction(..., attempts: 3), accounts locked in sorted order:

php
<?php

namespace App\Payments;

use Illuminate\Support\Facades\DB;
use InvalidArgumentException;
use RuntimeException;

// Double-entry postings inside DB::transaction. Callers that also change a payment row
// or write an outbox event call post() from inside their own transaction (nested = savepoint).
class LedgerService
{
    private const DEBIT_NORMAL = ['asset', 'expense'];

    /**
     * @param  list<array{account: string, direction: 'D'|'C', amount: int}>  $entries
     * @return bool true when posted now, false when the id was already posted (idempotent)
     */
    public function post(string $transactionId, string $description, array $entries): bool
    {
        if (count($entries) < 2) {
            throw new InvalidArgumentException('a transaction needs at least two entries');
        }

        return DB::transaction(function () use ($transactionId, $description, $entries) {
            if (DB::table('journal_transactions')->where('id', $transactionId)->exists()) {
                return false;
            }

            // Lock accounts in a fixed order so two postings never deadlock each other.
            $ids = array_values(array_unique(array_column($entries, 'account')));
            sort($ids);
            $accounts = DB::table('ledger_accounts')->whereIn('id', $ids)
                ->orderBy('id')->lockForUpdate()->get()->keyBy('id');

            $perCurrency = [];
            $delta = [];
            foreach ($entries as $e) {
                $acct = $accounts[$e['account']] ?? throw new RuntimeException("unknown account {$e['account']}");
                if (! is_int($e['amount']) || $e['amount'] <= 0) {
                    throw new InvalidArgumentException('amounts are positive integers in minor units');
                }
                $signed = $e['direction'] === 'D' ? $e['amount'] : -$e['amount'];
                $perCurrency[$acct->currency] = ($perCurrency[$acct->currency] ?? 0) + $signed;
                $normal = in_array($acct->kind, self::DEBIT_NORMAL, true) ? $signed : -$signed;
                $delta[$acct->id] = ($delta[$acct->id] ?? 0) + $normal;
            }
            foreach ($perCurrency as $currency => $sum) {
                if ($sum !== 0) {
                    throw new RuntimeException("unbalanced: {$currency} off by {$sum}");
                }
            }
            foreach ($delta as $id => $d) {
                if (! $accounts[$id]->allow_negative && $accounts[$id]->balance + $d < 0) {
                    throw new RuntimeException("insufficient balance on {$id}");
                }
            }

            DB::table('journal_transactions')->insert(['id' => $transactionId, 'description' => $description]);
            foreach ($entries as $e) {
                DB::table('ledger_entries')->insert([
                    'transaction_id' => $transactionId,
                    'account_id' => $e['account'],
                    'direction' => $e['direction'],
                    'amount' => $e['amount'],
                    'currency' => $accounts[$e['account']]->currency,
                ]);
            }
            foreach ($delta as $id => $d) {
                DB::table('ledger_accounts')->where('id', $id)->increment('balance', $d);
            }

            return true;
        }, attempts: 3);
    }
}

Webhook endpoint: raw body, every v1 signature against every active secret, tolerance, insertOrIgnore into the inbox, then a job is dispatched whenever the row is still unprocessed (not only on the first insert), so a redelivery after a crash between insert and dispatch still gets processed; any exception returns 500 and Stripe retries:

php
<?php

namespace App\Http\Controllers;

use App\Jobs\ProcessStripeEvent;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

// Custom endpoint (Cashier users get the same checks from its webhook middleware).
// Verify -> store in the inbox (dedup by event id) -> dispatch if unprocessed -> 200 fast.
// DispatchPendingWebhooks sweeps rows that were stored but never got a job.
class StripeWebhookController extends Controller
{
    private const TOLERANCE_SECONDS = 300;

    public function __invoke(Request $request): JsonResponse
    {
        $payload = $request->getContent();                   // the raw body: never re-encoded JSON
        $header = (string) $request->header('Stripe-Signature', '');

        if (! $this->verify($payload, $header, config('services.stripe.webhook_secrets', []))) {
            return response()->json(['error' => 'invalid signature'], 400);
        }

        $event = json_decode($payload, true, flags: JSON_THROW_ON_ERROR);

        DB::table('webhooks_inbox')->insertOrIgnore([
            'psp' => 'stripe',
            'event_id' => $event['id'],
            'event_type' => $event['type'],
            'object_id' => $event['data']['object']['id'] ?? null,
            'payload' => $payload,
        ]);

        // Dispatch whenever the row is still unprocessed, not only on the first insert: if the
        // process died (or the queue was down) after the insert last time, this redelivery is
        // what gets the event processed. A duplicate job is harmless: the job locks the row
        // and returns when processed_at is set. Exceptions here mean 500, so Stripe retries.
        $processed = DB::table('webhooks_inbox')
            ->where(['psp' => 'stripe', 'event_id' => $event['id']])->value('processed_at');
        if ($processed === null) {
            ProcessStripeEvent::dispatch($event['id']);
        }

        return response()->json(['received' => true]);       // processed duplicates also get 200
    }

    /** @param  list<string>  $secrets  current and, during a roll, previous secret */
    private function verify(string $payload, string $header, array $secrets): bool
    {
        $timestamp = null;
        $signatures = [];
        foreach (explode(',', $header) as $item) {
            [$key, $value] = array_pad(explode('=', trim($item), 2), 2, '');
            if ($key === 't' && ctype_digit($value)) {
                $timestamp = (int) $value;
            } elseif ($key === 'v1') {
                $signatures[] = $value;                       // ignore v0 and debug entries
            }
        }
        if ($timestamp === null || $signatures === []) {
            return false;
        }

        $matched = false;
        foreach ($secrets as $secret) {
            $expected = hash_hmac('sha256', $timestamp.'.'.$payload, $secret);
            foreach ($signatures as $sig) {
                $matched = hash_equals($expected, $sig) || $matched;   // constant time, no short circuit
            }
        }

        return $matched && abs(time() - $timestamp) <= self::TOLERANCE_SECONDS;
    }
}

The webhook job: one transaction for inbox, payment, refund, ledger and outbox; it finds the payment by intent id or, if checkout crashed before attaching it, by metadata.payment_id (and refuses a row already mapped to another intent); refund.created / refund.updated with status succeeded book the refund once (journal id = Stripe refund id, amount_refunded, outbox), refund.failed or a failed / canceled status frees the reservation if the refund was pending and reverses the booking (journal refund_failed:<id>, amount_refunded reduced, payments.refund_failed event) if it had already been booked, a Dashboard refund unknown to us gets its own row; charge.refunded only checks the running total and throws (retry, then dead letter) while a refund is not booked; forward progress applied, stale events acked; a conflict between terminal states (local succeeded, PSP canceled) throws instead of being acked; an event for a payment we do not have yet is retried with backoff; on requires_capture it stores the hold's capture_before from the charge (one Stripe API call inside the transaction, acceptable at this scale); after the last try the row keeps last_error (the dead-letter record):

php
<?php

namespace App\Jobs;

use App\Payments\LedgerService;
use App\Payments\PaymentStatus;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
use Illuminate\Queue\Attributes\Backoff;
use Illuminate\Queue\Attributes\Tries;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use Laravel\Cashier\Cashier;
use RuntimeException;
use Throwable;

// Applies one stored webhook exactly once: inbox row, payment row, refund row, ledger and
// outbox change in ONE transaction, so a crash anywhere leaves either all or nothing.
// Anything it cannot explain throws: the queue retries, and after the last try failed()
// leaves the row as a dead letter. It never acks an event it did not apply or prove stale.
#[Tries(8)]
#[Backoff([10, 30, 60, 300])]
class ProcessStripeEvent implements ShouldQueue
{
    use Queueable;

    public function __construct(public string $eventId) {}

    public function handle(LedgerService $ledger): void
    {
        DB::transaction(function () use ($ledger) {
            $row = DB::table('webhooks_inbox')
                ->where(['psp' => 'stripe', 'event_id' => $this->eventId])
                ->lockForUpdate()->first();
            if ($row === null || $row->processed_at !== null) {
                return;                                        // duplicate job or already done
            }

            $event = json_decode($row->payload, true);
            $object = $event['data']['object'];

            match (true) {
                str_starts_with($event['type'], 'payment_intent.') => $this->paymentIntentEvent($ledger, $event['type'], $object),
                in_array($event['type'], ['refund.created', 'refund.updated', 'refund.failed'], true) => $this->refundEvent($ledger, $object),
                $event['type'] === 'charge.refunded' => $this->checkRefundTotal($object),
                default => null,                               // not a money event for this service
            };

            DB::table('webhooks_inbox')->where(['psp' => 'stripe', 'event_id' => $this->eventId])
                ->update(['processed_at' => now(), 'attempts' => $row->attempts + 1]);
        });
    }

    private function paymentIntentEvent(LedgerService $ledger, string $type, array $intent): void
    {
        $target = PaymentStatus::fromStripeEvent($type);
        if ($target === null) {
            return;
        }
        $payment = $this->paymentFor($intent['id'], $intent['metadata']['payment_id'] ?? null);
        $current = PaymentStatus::from($payment->status);
        if ($current->canBecome($target)) {
            $this->apply($ledger, $payment, $target, $intent);     // edge or forward progress
        } elseif ($current->isTerminal() && $target->isTerminal() && $current !== $target) {
            throw new RuntimeException("conflict: local {$current->value}, PSP {$target->value} for {$intent['id']}");
        }
        // else: a stale event the current state already covers (e.g. processing after succeeded)
    }

    // Find the payment by intent id; if checkout crashed before storing the id, recover the
    // mapping from metadata.payment_id (set BEFORE the PSP call). Never overwrite another id.
    private function paymentFor(string $intentId, ?string $paymentId): object
    {
        $payment = DB::table('payments')->where('stripe_payment_intent_id', $intentId)->lockForUpdate()->first();
        if ($payment === null && $paymentId !== null) {
            $payment = DB::table('payments')->where('id', $paymentId)->lockForUpdate()->first();
            if ($payment !== null && $payment->stripe_payment_intent_id === null) {
                DB::table('payments')->where('id', $paymentId)->whereNull('stripe_payment_intent_id')
                    ->update(['stripe_payment_intent_id' => $intentId, 'updated_at' => now()]);
                $payment->stripe_payment_intent_id = $intentId;
            } elseif ($payment !== null) {
                throw new RuntimeException("payment {$paymentId} is mapped to {$payment->stripe_payment_intent_id}, not {$intentId}");
            }
        }
        // No row yet (the webhook beat our commit) or not ours: retry, never ack.
        return $payment ?? throw new RuntimeException("no payment for {$intentId} yet");
    }

    private function apply(LedgerService $ledger, object $payment, PaymentStatus $to, array $intent): void
    {
        $received = (int) ($intent['amount_received'] ?? 0);
        $changes = [
            'status' => $to->value,
            'amount_received' => $received,
            'version' => $payment->version + 1,
            'updated_at' => now(),
        ];
        if ($to === PaymentStatus::RequiresCapture && isset($intent['latest_charge'])) {
            // The hold's real expiry lives on the Charge (Visa MIT about 5 days, not 7):
            // the capture scheduler works from this column, never from a fixed window.
            $charge = Cashier::stripe()->charges->retrieve($intent['latest_charge']);
            $before = $charge->payment_method_details->card->capture_before ?? null;
            $changes['capture_before'] = $before ? Carbon::createFromTimestamp($before) : null;
        }
        DB::table('payments')->where('id', $payment->id)->where('version', $payment->version)->update($changes);

        if ($to === PaymentStatus::Succeeded) {
            $cur = strtoupper($payment->currency);
            $ledger->post("capture:{$payment->id}", "capture {$payment->id}", [
                ['account' => "psp_receivable:stripe:{$cur}", 'direction' => 'D', 'amount' => $received],
                ['account' => "sales:{$cur}", 'direction' => 'C', 'amount' => $received],
            ]);
        }
        $this->outbox('payments.payment_'.$to->value, $payment->id, ['status' => $to->value, 'amount_received' => $received]);
    }

    // refund.created / refund.updated / refund.failed. A succeeded refund is booked exactly once
    // (journal id = Stripe refund id). A failed or canceled one releases the reservation if it
    // was still pending; if it had already been booked (the bank returned the money later),
    // the booking is reversed: a reversing journal entry, amount_refunded reduced, an outbox
    // event so support can refund the customer another way.
    private function refundEvent(LedgerService $ledger, array $refund): void
    {
        $payment = $this->paymentFor($refund['payment_intent'], null);
        $local = DB::table('refunds')->where('stripe_refund_id', $refund['id'])->lockForUpdate()->first()
            ?? (isset($refund['metadata']['refund_id'])
                ? DB::table('refunds')->where('id', $refund['metadata']['refund_id'])->lockForUpdate()->first()
                : null);
        if ($local === null) {                                   // created outside the app (Dashboard)
            $local = (object) ['id' => 'rf_'.$refund['id'], 'state' => 'pending', 'amount' => (int) $refund['amount'],
                'stripe_refund_id' => $refund['id']];
            DB::table('refunds')->insert(['id' => $local->id, 'payment_id' => $payment->id, 'client_key' => 'psp:'.$refund['id'],
                'amount' => $local->amount, 'currency' => strtoupper($refund['currency']), 'state' => 'pending',
                'stripe_refund_id' => $refund['id'], 'created_at' => now(), 'updated_at' => now()]);
        }
        if ($local->stripe_refund_id !== null && $local->stripe_refund_id !== $refund['id']) {
            // One row, one provider refund. A second provider refund for the same row means a
            // resend created another refund: never ack it as "already final" (that under-counts).
            throw new RuntimeException("refund row {$local->id} is {$local->stripe_refund_id}; second provider refund {$refund['id']}");
        }
        if ((int) $local->amount !== (int) $refund['amount']) {
            throw new RuntimeException("refund {$refund['id']}: local {$local->amount}, PSP {$refund['amount']}");
        }
        $cur = strtoupper($payment->currency);
        $failed = in_array($refund['status'], ['failed', 'canceled'], true);

        $open = in_array($local->state, ['pending', 'needs_reconciliation'], true);
        if ($failed && $open) {                                  // never booked: free the reservation
            DB::table('refunds')->where('id', $local->id)->update(['state' => 'failed', 'stripe_refund_id' => $refund['id'], 'updated_at' => now()]);

            return;
        }
        if ($failed && $local->state === 'succeeded') {          // booked, then returned by the bank
            $ledger->post("refund_failed:{$refund['id']}", "refund failed {$payment->id}", [
                ['account' => "psp_receivable:stripe:{$cur}", 'direction' => 'D', 'amount' => $local->amount],
                ['account' => "refunds:{$cur}", 'direction' => 'C', 'amount' => $local->amount],
            ]);
            DB::table('payments')->where('id', $payment->id)->decrement('amount_refunded', $local->amount);
            DB::table('refunds')->where('id', $local->id)->update(['state' => 'failed', 'updated_at' => now()]);
            $this->outbox('payments.refund_failed', $payment->id, ['refund' => $refund['id'], 'amount' => $local->amount,
                'reason' => $refund['failure_reason'] ?? null]);

            return;
        }
        if (! $open || $refund['status'] !== 'succeeded') {
            return;                                              // already final here, or still pending at Stripe
        }
        if ($payment->amount_refunded + $local->amount > $payment->amount_received) {
            throw new RuntimeException("refund {$refund['id']} exceeds what {$payment->id} received");
        }
        $ledger->post("refund:{$refund['id']}", "refund {$payment->id}", [
            ['account' => "refunds:{$cur}", 'direction' => 'D', 'amount' => $local->amount],
            ['account' => "psp_receivable:stripe:{$cur}", 'direction' => 'C', 'amount' => $local->amount],
        ]);
        DB::table('payments')->where('id', $payment->id)->increment('amount_refunded', $local->amount);
        DB::table('refunds')->where('id', $local->id)->update(['state' => 'succeeded', 'stripe_refund_id' => $refund['id'], 'updated_at' => now()]);
        $this->outbox('payments.payment_refunded', $payment->id, ['refund' => $refund['id'], 'amount' => $local->amount]);
    }

    // charge.refunded carries the charge's running total. If it is ahead of what we booked,
    // a refund.* event is still on its way (or was lost): throw so the job retries, and after
    // the last try the row becomes a dead letter for a human. Equal totals: nothing to do.
    private function checkRefundTotal(array $charge): void
    {
        $payment = $this->paymentFor($charge['payment_intent'], null);
        if ((int) $charge['amount_refunded'] > (int) $payment->amount_refunded) {
            throw new RuntimeException("charge {$charge['id']} refunded {$charge['amount_refunded']}, booked {$payment->amount_refunded}");
        }
    }

    private function outbox(string $topic, string $paymentId, array $data): void
    {
        DB::table('outbox')->insert([
            'event_id' => (string) Str::uuid(),
            'topic' => $topic,
            'aggregate_id' => $paymentId,
            'payload' => json_encode(['id' => $paymentId] + $data),
        ]);
    }

    // After the last try the inbox row stays unprocessed with the error: the dead letter a human reads.
    public function failed(?Throwable $exception): void
    {
        DB::table('webhooks_inbox')->where(['psp' => 'stripe', 'event_id' => $this->eventId])
            ->update(['last_error' => Str::limit((string) $exception?->getMessage(), 500)]);
    }
}

Pending-webhook sweeper: an Artisan command, scheduled every five minutes, that dispatches jobs for inbox rows older than ten minutes that are neither processed nor dead-lettered (the PSP may have stopped redelivering):

php
<?php

namespace App\Console\Commands;

use App\Jobs\ProcessStripeEvent;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;

// Safety net for inbox rows that were stored but never got a job (crash after the insert,
// queue outage, a PSP that gave up redelivering). Rows with last_error are dead letters
// for a human and are not re-dispatched. Schedule it in routes/console.php:
//   Schedule::command('payments:dispatch-pending-webhooks')->everyFiveMinutes();
class DispatchPendingWebhooks extends Command
{
    protected $signature = 'payments:dispatch-pending-webhooks {--older-than=10 : minutes}';

    protected $description = 'Dispatch ProcessStripeEvent for unprocessed webhook inbox rows';

    public function handle(): void
    {
        $count = 0;
        DB::table('webhooks_inbox')
            ->where('psp', 'stripe')
            ->whereNull('processed_at')
            ->whereNull('last_error')
            ->where('received_at', '<', now()->subMinutes((int) $this->option('older-than')))
            ->orderBy('received_at')
            ->limit(500)
            ->pluck('event_id')
            ->each(function (string $eventId) use (&$count) {
                ProcessStripeEvent::dispatch($eventId);            // idempotent job: duplicates are no-ops
                $count++;
            });
        $this->info("dispatched {$count}");
    }
}

Daily reconciliation of the settlement file against the rows the app writes: charges are matched to payments on provider identity (psp + intent id) and compared on amount, currency and status; refund lines are matched to refunds (Stripe refund id) and, through the refund's payment, to the same provider; succeeded payments missing from every batch after three days are listed too. The file contract is this chapter's reduced five-column format; map your PSP's report columns to it:

php
<?php

namespace App\Jobs;

use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
use Illuminate\Queue\Attributes\Tries;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Storage;

// Daily queued job: load the PSP settlement file, then diff it against the rows checkout
// and the webhook worker actually write: payments (charges) and refunds.
// File contract (this chapter's reduced format): psp_ref,type,gross,fee,currency where
// psp_ref is the PaymentIntent id for charges and the refund id (re_...) for refunds;
// map your PSP's report columns to that before loading.
// Schedule it with Schedule::job(new ReconcileSettlementFile(...))->dailyAt('06:00').
#[Tries(3)]
class ReconcileSettlementFile implements ShouldQueue
{
    use Queueable;

    public function __construct(public string $psp, public string $batchId, public string $path) {}

    public function handle(): void
    {
        $stream = Storage::disk('local')->readStream($this->path);
        $header = fgetcsv($stream);                         // psp_ref,type,gross,fee,currency
        DB::transaction(function () use ($stream, $header) {
            while (($line = fgetcsv($stream)) !== false) {
                $row = array_combine($header, $line);
                DB::table('settlement_lines')->insertOrIgnore([   // re-running the job is safe
                    'psp' => $this->psp,
                    'batch_id' => $this->batchId,
                    'psp_reference' => $row['psp_ref'],
                    'line_type' => $row['type'],
                    'gross' => (int) $row['gross'],             // file is in minor units
                    'fee' => (int) $row['fee'],
                    'currency' => strtoupper($row['currency']),
                ]);
            }
        });
        fclose($stream);

        $lines = fn (string $type) => DB::table('settlement_lines as s')
            ->where(['s.psp' => $this->psp, 's.batch_id' => $this->batchId, 's.line_type' => $type]);

        // Charges: matched on provider identity (psp + intent id), then amount AND currency.
        $charges = $lines('charge')
            ->leftJoin('payments as p', fn ($j) => $j->on('p.stripe_payment_intent_id', '=', 's.psp_reference')
                ->on('p.psp', '=', 's.psp'))
            ->select('s.psp_reference', 's.gross', 's.currency', 'p.id', 'p.amount_received', 'p.currency as our_currency', 'p.status')
            ->get();
        $missingLocally = $charges->whereNull('id')->pluck('psp_reference');
        $mismatch = $charges->whereNotNull('id')->filter(fn ($c) => (int) $c->gross !== (int) $c->amount_received
            || $c->currency !== strtoupper($c->our_currency) || $c->status !== 'succeeded')->pluck('psp_reference');

        // Refunds: the PSP refunded money we did not book (or booked differently).
        // Refunds: matched on provider identity through the refund's payment (psp + refund id).
        $refunds = $lines('refund')
            ->leftJoin('refunds as r', 'r.stripe_refund_id', '=', 's.psp_reference')
            ->leftJoin('payments as rp', fn ($j) => $j->on('rp.id', '=', 'r.payment_id')->on('rp.psp', '=', 's.psp'))
            ->select('s.psp_reference', 's.gross', 's.currency', 'r.id', 'rp.id as payment', 'r.amount',
                'r.currency as our_currency', 'r.state')
            ->get();
        $refundIssues = $refunds->filter(fn ($r) => $r->id === null || $r->payment === null || $r->state !== 'succeeded'
            || abs((int) $r->gross) !== (int) $r->amount || $r->currency !== strtoupper($r->our_currency))
            ->pluck('psp_reference');

        // Booked here, absent from every loaded batch of this PSP: investigate after the cutoff.
        $missingAtPsp = DB::table('payments as p')->where('p.psp', $this->psp)->where('p.status', 'succeeded')
            ->where('p.updated_at', '<', now()->subDays(3))
            ->whereNotExists(fn ($q) => $q->from('settlement_lines as s')->whereColumn('s.psp_reference', 'p.stripe_payment_intent_id')
                ->whereColumn('s.psp', 'p.psp')->where('s.line_type', 'charge'))
            ->pluck('p.id');

        Log::channel('payments')->warning('settlement reconciliation', [
            'psp' => $this->psp,
            'batch' => $this->batchId,
            'missing_locally' => $missingLocally->all(),
            'amount_or_currency_mismatch' => $mismatch->all(),
            'refund_issues' => $refundIssues->all(),
            'missing_at_psp' => $missingAtPsp->all(),
        ]);
    }
}

Routes (the webhook route is excluded from CSRF with preventRequestForgery(except: [...])):

php
<?php

// routes/web.php: payment routes. Webhooks bypass CSRF; in bootstrap/app.php:
//   ->withMiddleware(function (Middleware $middleware): void {
//       $middleware->preventRequestForgery(except: ['stripe/*', 'webhooks/*']);
//   })

use App\Http\Controllers\CheckoutController;
use App\Http\Controllers\StripeWebhookController;
use Illuminate\Support\Facades\Route;

Route::middleware('auth')->group(function () {
    Route::post('/orders/{order}/pay', [CheckoutController::class, 'start']);
    Route::post('/orders/{order}/charge', [CheckoutController::class, 'charge']);
    Route::post('/orders/{order}/refund', [CheckoutController::class, 'refund']);
});

// Our own endpoint (Cashier registers its own /stripe/webhook route with signature middleware).
Route::post('/webhooks/stripe', StripeWebhookController::class)->middleware('throttle:600,1');

Migration for the same tables as the SQL schema (triggers excluded):

php
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;

// Laravel 13 migration kept in sync with sql/schema.sql: same tables, columns and recovery
// states (psp_result, first_sent_at, refused/unbooked, needs_reconciliation), so the recovery
// and reconciliation queries on the page run against either. The PostgreSQL triggers (append-only,
// balanced, entry currency) belong in a raw DB::unprepared() migration of their own.
return new class extends Migration
{
    public function up(): void
    {
        Schema::create('idempotency_keys', function (Blueprint $table) {
            $table->string('merchant_id');
            $table->string('key');
            $table->string('fingerprint');                  // sha256 of the canonical request
            $table->string('status');                       // in_progress, completed
            $table->unsignedSmallInteger('response_code')->nullable();
            $table->json('response_body')->nullable();
            $table->timestamp('created_at')->useCurrent();
            $table->timestamp('expires_at')->index();
            $table->primary(['merchant_id', 'key']);
        });

        Schema::create('payments', function (Blueprint $table) {
            $table->string('id')->primary();
            $table->string('merchant_id');
            $table->string('order_id');
            $table->unsignedBigInteger('amount');           // minor units
            $table->char('currency', 3);
            $table->string('status')->default('requires_payment_method');
            $table->string('capture_method')->default('automatic');
            $table->unsignedBigInteger('amount_capturable')->default(0);
            $table->unsignedBigInteger('amount_received')->default(0);
            $table->unsignedBigInteger('amount_refunded')->default(0);
            $table->string('psp')->default('stripe');       // provider identity for reconciliation
            $table->string('stripe_payment_intent_id')->nullable()->unique();
            $table->timestamp('capture_before')->nullable()->index();  // hold expiry from the PSP
            $table->unsignedInteger('version')->default(0);
            $table->timestamps();
            $table->unique(['merchant_id', 'order_id']);
        });

        Schema::create('payment_attempts', function (Blueprint $table) {
            $table->id();
            $table->string('payment_id');
            $table->string('psp');                          // stripe, adyen
            $table->string('psp_idem_key')->unique();       // pi_...:attempt:N, reused on every retry
            $table->string('psp_reference')->nullable()->index();
            $table->string('state');                        // sent, unknown, refused, done, unbooked
            $table->json('psp_result')->nullable();         // kept while 'unbooked': booked later, never re-sent
            $table->string('decline_code')->nullable();
            $table->timestamp('first_sent_at')->useCurrent()->index();  // resend window starts here (< 24 h)
            $table->timestamp('created_at')->useCurrent();
            $table->foreign('payment_id')->references('id')->on('payments');
        });

        Schema::create('ledger_accounts', function (Blueprint $table) {
            $table->string('id')->primary();                // psp_receivable:stripe:USD
            $table->char('currency', 3);
            $table->string('kind');                         // asset, expense, liability, revenue, equity
            $table->boolean('allow_negative')->default(false);
            $table->bigInteger('balance')->default(0);      // cached, derived from entries
        });

        // The accounts every posting in this chapter uses (LedgerService throws on an unknown
        // account, so they must exist before the first capture). One set per currency.
        foreach (['USD'] as $cur) {
            DB::table('ledger_accounts')->insert([
                ['id' => "psp_receivable:stripe:{$cur}", 'currency' => $cur, 'kind' => 'asset', 'allow_negative' => true, 'balance' => 0],
                ['id' => "sales:{$cur}", 'currency' => $cur, 'kind' => 'revenue', 'allow_negative' => false, 'balance' => 0],
                ['id' => "refunds:{$cur}", 'currency' => $cur, 'kind' => 'expense', 'allow_negative' => false, 'balance' => 0],
                ['id' => "psp_fees:{$cur}", 'currency' => $cur, 'kind' => 'expense', 'allow_negative' => false, 'balance' => 0],
                ['id' => "cash:bank:{$cur}", 'currency' => $cur, 'kind' => 'asset', 'allow_negative' => false, 'balance' => 0],
            ]);
        }

        Schema::create('journal_transactions', function (Blueprint $table) {
            $table->string('id')->primary();                // capture:pi_..., idempotent posting id
            $table->string('description');
            $table->timestamp('posted_at')->useCurrent();
        });

        Schema::create('ledger_entries', function (Blueprint $table) {
            $table->id();
            $table->string('transaction_id');
            $table->string('account_id');
            $table->char('direction', 1);                   // D or C
            $table->unsignedBigInteger('amount');
            $table->char('currency', 3);
            $table->foreign('transaction_id')->references('id')->on('journal_transactions');
            $table->foreign('account_id')->references('id')->on('ledger_accounts');
            $table->index(['account_id', 'id']);
        });

        Schema::create('outbox', function (Blueprint $table) {
            $table->id();
            $table->string('event_id')->unique();
            $table->string('topic');
            $table->string('aggregate_id');
            $table->json('payload');
            $table->timestamp('created_at')->useCurrent();
            $table->timestamp('published_at')->nullable()->index();
        });

        Schema::create('webhooks_inbox', function (Blueprint $table) {
            $table->string('psp');
            $table->string('event_id');
            $table->string('event_type');
            $table->string('object_id')->nullable();
            $table->json('payload');
            $table->timestamp('received_at')->useCurrent();
            $table->timestamp('processed_at')->nullable()->index();
            $table->unsignedInteger('attempts')->default(0);
            $table->text('last_error')->nullable();
            $table->primary(['psp', 'event_id']);
        });

        Schema::create('refunds', function (Blueprint $table) {
            $table->string('id')->primary();                // rf_<ulid>: also the Stripe idempotency key
            $table->string('payment_id');
            $table->string('client_key');                   // the client's Idempotency-Key
            $table->unsignedBigInteger('amount');
            $table->char('currency', 3);
            $table->string('state');                        // pending, needs_reconciliation (both reserved), succeeded, failed
            $table->string('stripe_refund_id')->nullable()->unique();  // exactly one provider refund per row
            $table->timestamp('first_sent_at')->nullable(); // provider key retention counts from here
            $table->timestamps();
            $table->foreign('payment_id')->references('id')->on('payments');
            $table->unique(['payment_id', 'client_key']);   // one refund per client key and payment
        });

        Schema::create('settlement_lines', function (Blueprint $table) {
            $table->string('psp');
            $table->string('batch_id');                     // payout / settlement batch
            $table->string('psp_reference');
            $table->string('line_type');                    // charge, refund, chargeback, fee
            $table->bigInteger('gross');
            $table->bigInteger('fee');
            $table->char('currency', 3);
            $table->primary(['psp', 'batch_id', 'psp_reference', 'line_type']);
        });
    }

    public function down(): void
    {
        foreach (['settlement_lines', 'refunds', 'webhooks_inbox', 'outbox', 'ledger_entries', 'journal_transactions',
            'ledger_accounts', 'payment_attempts', 'payments', 'idempotency_keys'] as $t) {
            Schema::dropIfExists($t);
        }
    }
};

The PostgreSQL schema with the append-only triggers and the deferred balance check:

sql
-- PostgreSQL 16+ schema for a payment service. Money is BIGINT minor units + ISO 4217 code.

CREATE TABLE idempotency_keys (
    merchant_id   TEXT        NOT NULL,
    key           TEXT        NOT NULL CHECK (length(key) BETWEEN 1 AND 255),
    fingerprint   TEXT        NOT NULL,              -- sha256 of the canonical request
    status        TEXT        NOT NULL CHECK (status IN ('in_progress', 'completed')),
    response_code INT,
    response_body JSONB,
    created_at    TIMESTAMPTZ NOT NULL DEFAULT now(),
    expires_at    TIMESTAMPTZ NOT NULL DEFAULT now() + interval '24 hours',
    PRIMARY KEY (merchant_id, key)
);

CREATE TABLE payments (                              -- one row per payment intent
    id                TEXT        PRIMARY KEY,       -- pi_...
    merchant_id       TEXT        NOT NULL,
    order_id          TEXT        NOT NULL,
    amount            BIGINT      NOT NULL CHECK (amount > 0),
    currency          CHAR(3)     NOT NULL,
    status            TEXT        NOT NULL CHECK (status IN ('requires_payment_method', 'requires_confirmation',
                          'requires_action', 'processing', 'requires_capture', 'succeeded', 'canceled')),
    capture_method    TEXT        NOT NULL DEFAULT 'automatic' CHECK (capture_method IN ('automatic', 'manual')),
    amount_capturable BIGINT      NOT NULL DEFAULT 0,
    amount_received   BIGINT      NOT NULL DEFAULT 0,
    amount_refunded   BIGINT      NOT NULL DEFAULT 0 CHECK (amount_refunded <= amount_received),
    psp               TEXT        NOT NULL DEFAULT 'stripe',  -- provider identity (reconciliation)
    stripe_payment_intent_id TEXT UNIQUE,            -- Laravel flow: attached once, never overwritten
    capture_before    TIMESTAMPTZ,                   -- hold expiry from the PSP (Stripe charge:
                                                     -- payment_method_details.card.capture_before)
    version           INT         NOT NULL DEFAULT 0,            -- optimistic lock
    created_at        TIMESTAMPTZ NOT NULL DEFAULT now(),
    updated_at        TIMESTAMPTZ NOT NULL DEFAULT now(),
    UNIQUE (merchant_id, order_id)                    -- one live intent per order
);

CREATE INDEX payments_capture_due ON payments (capture_before) WHERE status = 'requires_capture';

CREATE TABLE payment_attempts (                      -- one row per call to a PSP
    id              BIGSERIAL   PRIMARY KEY,
    payment_id      TEXT        NOT NULL REFERENCES payments (id),
    psp             TEXT        NOT NULL,            -- stripe, adyen
    psp_idem_key    TEXT        NOT NULL UNIQUE,     -- pi_...:attempt:N, reused on every retry
    psp_reference   TEXT,                            -- ch_... / pspReference
    state           TEXT        NOT NULL CHECK (state IN ('sent', 'unknown', 'refused', 'done', 'unbooked')),
    psp_result      JSONB,                           -- kept while 'unbooked': booked later, never re-sent
    decline_code    TEXT,                            -- insufficient_funds, do_not_honor...
    first_sent_at   TIMESTAMPTZ NOT NULL DEFAULT now(),  -- resend window starts here (< 24 h)
    created_at      TIMESTAMPTZ NOT NULL DEFAULT now(),
    CHECK (state <> 'unbooked' OR psp_result IS NOT NULL)
);
CREATE INDEX payment_attempts_open ON payment_attempts (first_sent_at)
    WHERE state IN ('sent', 'unknown', 'unbooked');

CREATE TABLE ledger_accounts (
    id             TEXT    PRIMARY KEY,              -- psp_receivable:stripe:USD
    currency       CHAR(3) NOT NULL,
    kind           TEXT    NOT NULL CHECK (kind IN ('asset', 'expense', 'liability', 'revenue', 'equity')),
    allow_negative BOOLEAN NOT NULL DEFAULT false,
    balance        BIGINT  NOT NULL DEFAULT 0,       -- cached normal-side balance, derived from entries
    version        BIGINT  NOT NULL DEFAULT 0,
    CHECK (allow_negative OR balance >= 0)
);

CREATE TABLE journal_transactions (                  -- immutable header
    id          TEXT        PRIMARY KEY,             -- capture:pi_..., refund:<key>: idempotent posting
    description TEXT        NOT NULL,
    posted_at   TIMESTAMPTZ NOT NULL DEFAULT now(),
    reverses    TEXT        REFERENCES journal_transactions (id)
);

CREATE TABLE ledger_entries (                        -- immutable lines
    id             BIGSERIAL PRIMARY KEY,
    transaction_id TEXT      NOT NULL REFERENCES journal_transactions (id),
    account_id     TEXT      NOT NULL REFERENCES ledger_accounts (id),
    direction      CHAR(1)   NOT NULL CHECK (direction IN ('D', 'C')),
    amount         BIGINT    NOT NULL CHECK (amount > 0),
    currency       CHAR(3)   NOT NULL
);
CREATE INDEX ledger_entries_account ON ledger_entries (account_id, id);

-- Append-only: nobody may UPDATE or DELETE journal rows; corrections are reversing transactions.
CREATE FUNCTION forbid_change() RETURNS trigger LANGUAGE plpgsql AS $$
BEGIN RAISE EXCEPTION 'ledger is append-only (%)', TG_TABLE_NAME; END $$;
CREATE TRIGGER entries_immutable BEFORE UPDATE OR DELETE ON ledger_entries
    FOR EACH ROW EXECUTE FUNCTION forbid_change();
CREATE TRIGGER journal_immutable BEFORE UPDATE OR DELETE ON journal_transactions
    FOR EACH ROW EXECUTE FUNCTION forbid_change();

-- An entry's currency must be its account's currency: no silent cross-currency transfer
-- (an FX conversion is two balanced transactions through an FX account per currency).
CREATE FUNCTION check_entry_currency() RETURNS trigger LANGUAGE plpgsql AS $$
BEGIN
    IF NOT EXISTS (SELECT 1 FROM ledger_accounts WHERE id = NEW.account_id AND currency = NEW.currency) THEN
        RAISE EXCEPTION 'entry currency % does not match account %', NEW.currency, NEW.account_id;
    END IF;
    RETURN NEW;
END $$;
CREATE TRIGGER entries_currency BEFORE INSERT ON ledger_entries
    FOR EACH ROW EXECUTE FUNCTION check_entry_currency();

-- Debits = credits per currency, checked at COMMIT (deferred): the trigger fires once per
-- inserted entry, but only after all entries of the transaction exist.
CREATE FUNCTION check_balanced() RETURNS trigger LANGUAGE plpgsql AS $$
DECLARE bad RECORD;
BEGIN
    SELECT currency, sum(CASE direction WHEN 'D' THEN amount ELSE -amount END) AS diff
      INTO bad
      FROM ledger_entries WHERE transaction_id = NEW.transaction_id
     GROUP BY currency HAVING sum(CASE direction WHEN 'D' THEN amount ELSE -amount END) <> 0
     LIMIT 1;
    IF FOUND THEN
        RAISE EXCEPTION 'unbalanced journal transaction % (% off by %)', NEW.transaction_id, bad.currency, bad.diff;
    END IF;
    RETURN NULL;
END $$;
CREATE CONSTRAINT TRIGGER entries_balanced AFTER INSERT ON ledger_entries
    DEFERRABLE INITIALLY DEFERRED FOR EACH ROW EXECUTE FUNCTION check_balanced();

CREATE TABLE outbox (                                -- written in the same transaction as payments/ledger
    id           BIGSERIAL   PRIMARY KEY,
    event_id     TEXT        NOT NULL UNIQUE,
    topic        TEXT        NOT NULL,               -- payments.payment_succeeded
    aggregate_id TEXT        NOT NULL,               -- payment id: partition key
    payload      JSONB       NOT NULL,
    created_at   TIMESTAMPTZ NOT NULL DEFAULT now(),
    published_at TIMESTAMPTZ
);
CREATE INDEX outbox_unpublished ON outbox (id) WHERE published_at IS NULL;

CREATE TABLE webhooks_inbox (                        -- raw PSP events, stored before processing
    psp          TEXT        NOT NULL,
    event_id     TEXT        NOT NULL,               -- evt_... / Adyen pspReference+eventCode
    event_type   TEXT        NOT NULL,
    object_id    TEXT,                               -- data.object.id: second dedup key
    payload      JSONB       NOT NULL,
    received_at  TIMESTAMPTZ NOT NULL DEFAULT now(),
    processed_at TIMESTAMPTZ,
    attempts     INT         NOT NULL DEFAULT 0,
    last_error   TEXT,                               -- after N attempts: dead letter for a human
    PRIMARY KEY (psp, event_id)
);
CREATE INDEX webhooks_inbox_pending ON webhooks_inbox (received_at) WHERE processed_at IS NULL;

CREATE TABLE refunds (                               -- Laravel flow: one row per refund request
    id               TEXT        PRIMARY KEY,           -- rf_<ulid>, also the PSP idempotency key
    payment_id       TEXT        NOT NULL REFERENCES payments (id),
    client_key       TEXT        NOT NULL,              -- the client's Idempotency-Key
    amount           BIGINT      NOT NULL CHECK (amount > 0),
    currency         CHAR(3)     NOT NULL,
    state            TEXT        NOT NULL CHECK (state IN ('pending', 'needs_reconciliation', 'succeeded', 'failed')),
    stripe_refund_id TEXT        UNIQUE,                -- re_...: exactly one provider refund per row
    first_sent_at    TIMESTAMPTZ,                       -- provider key retention counts from here
    created_at       TIMESTAMPTZ NOT NULL DEFAULT now(),
    updated_at       TIMESTAMPTZ NOT NULL DEFAULT now(),
    UNIQUE (payment_id, client_key)
);

CREATE TABLE settlement_lines (                      -- loaded from the PSP settlement file
    psp           TEXT    NOT NULL,
    batch_id      TEXT    NOT NULL,                  -- payout / settlement batch
    psp_reference TEXT    NOT NULL,
    line_type     TEXT    NOT NULL,                  -- charge, refund, chargeback, fee
    gross         BIGINT  NOT NULL,
    fee           BIGINT  NOT NULL,
    currency      CHAR(3) NOT NULL,
    PRIMARY KEY (psp, batch_id, psp_reference, line_type)
);

The Laravel angle ​

Laravel 13 featureBehaviour (from the docs)Use here
Cashier $user->pay($amount)Creates a payment intent wrapped in Laravel\Cashier\Payment; amounts "in the lowest denominator"One-off checkout with the Payment Element
Cashier $user->charge($amount, $paymentMethod, $options)"will throw an exception if the charge fails"; returns Laravel\Cashier\PaymentSaved cards
Laravel\Cashier\Exceptions\IncompletePaymentThrown when extra action such as 3DS is neededRedirect to cashier.payment with redirect
Cashier $user->refund($paymentIntentId)Accepts "the Stripe Payment Intent ID as its first argument"Full refund
Cashier::stripe()The underlying Stripe PHP SDK clientIdempotency keys, Checkout sessions
Cashier webhooksController at /stripe/webhook; STRIPE_WEBHOOK_SECRET; php artisan cashier:webhookCashier-managed tables stay in sync
$middleware->preventRequestForgery(except: ['stripe/*'])Excludes URIs from CSRF protection (PreventRequestForgery middleware)Webhook routes
DB::transaction(fn, attempts: 3)Retries the closure on deadlockLedger postings
lockForUpdate()SELECT ... FOR UPDATEAccounts, inbox row, payment row
insertOrIgnore()"will ignore errors while inserting records"; "duplicate record errors will be ignored and other types of errors may also be ignored depending on the database engine"Inbox, settlement lines, the checkout's payments row
dispatch(...)->afterCommit()Dispatch after open transactions commitJob never runs before the inbox row exists
#[Tries(8)], #[Backoff([10, 30, 60, 300])]Attribute form of tries and backoff; "the last value is used" beyond the arrayWebhook job
Job failed(?Throwable $e)Called after the last attemptWrite last_error: dead-letter record
Schedule::job(...)->dailyAt('06:00'), Schedule::command(...)->everyFiveMinutes()Scheduler (Schedule::job(new Heartbeat)->everyFiveMinutes() and ->dailyAt('13:00') in the docs)Reconciliation; the pending-webhook sweeper

Solving the classic problems ​

Double charge after a timeout ​

SolutionHowAdvantageCost / limitation
Derived provider keypi_...:attempt:N, same on every retryPSP returns the first resultOnly within the PSP's key window (24 h Stripe v1)
Query-then-retryLook up the attempt, then resend with the same keyResolves most unknowns in secondsNeeds a lookup path (or a saved-response replay)
Park unknown, no failoverstate = 'unknown', sweep laterNo second PSP chargeCustomer sees "pending" for minutes
Unique (merchant_id, order_id)DB constraintTwo client keys cannot create two intentsOne live intent per order

A webhook arrives before our own commit ​

Create the payments row before calling the PSP (as CheckoutController does), so the row normally exists before any webhook. If a webhook still wins the race, return 200 after storing it; the job finds no payment row and throws, so the queue retries with backoff (#[Backoff]) until the row exists. Never mark it processed. If the job was never dispatched (crash after the insert), the next redelivery dispatches it because the row is unprocessed, and payments:dispatch-pending-webhooks catches the rest.

Out-of-order webhooks overwrite a final status ​

The state machine has no edge out of succeeded; the job acks and ignores the stale event. The opposite case matters as much: a payment_intent.succeeded that arrives while the local row is still at requires_payment_method (the intermediate events were late or never subscribed) is forward progress and must be applied and booked, not acked as stale; Stripe says to make sure your destination "isn’t dependent on receiving events in a specific order". Never order by created: Stripe "Snapshot events record created in seconds, so distinct events can share a timestamp"; when in doubt, retrieve the object from the API.

Forged or replayed webhooks ​

Verify the signature over the raw body with hash_equals / hmac.Equal, check the timestamp against the tolerance, accept any active secret during a roll, then dedupe by event id.

Refund larger than the payment, or refunded twice ​

Count every refund that is not booked yet as already taken: amount_refunded + open refunds + amount <= amount_received before calling the PSP; give each refund its own key, bound to one payment and one amount (a reuse with other parameters is an error, an exact replay returns the first result: in Go Refund(id, key, amount), in Laravel the client's Idempotency-Key header stored on the refunds row, so a retried HTTP request never creates a second Stripe refund); never free a reserved amount because a retry was refused or failed in an unclassified way, only after a lookup proves the refund did not happen; a refund that the bank returns later (refund.failed, or refund.updated with status failed) is reversed in the journal and in amount_refunded; CHECK (amount_refunded <= amount_received) in SQL as the last line of defence. In Laravel the route only reserves (refunds row pending) and the worker books from refund.* events.

Books drift from the PSP ​

Daily reconciliation on the settlement file; fees and payouts posted as journal entries; clearing accounts must return to zero; every unmatched line is a ticket.

A balance was "fixed" with UPDATE ​

Triggers reject UPDATE and DELETE on journal tables; corrections are reversing entries (Ledger.Reverse), so the audit trail shows the error, the fix and who posted it.

Card numbers in logs ​

Collect cards in PSP iframes (SAQ A), send tokens only, strip request bodies from logs on payment routes, scan logs for PAN patterns, and treat any PAN found as an incident.

Card testing attack ​

Rate limit the checkout endpoint per IP and session, velocity rules on distinct cards per device, block the device, add CAPTCHA, and watch the authorization rate.

Capture forgotten, hold expired ​

Store the PSP's expiry with the payment (payments.capture_before, read from the charge's payment_method_details.card.capture_before when the intent reaches requires_capture) and run the capture/void job against it: capture or void everything whose capture_before is within the next 24 hours, and alert on anything within 12 hours or with no capture_before at all. A fixed "7 days, alert at day 5" rule is wrong: a Visa merchant-initiated hold on Stripe expires after 4 days and 18 hours, card-present Mastercard after 2 days. For longer needs use extended authorization where supported, or re-authorize.

A compensation (void) fails ​

Retry it a bounded number of times, then park it on the dead-letter list; the hold will expire by itself, but the customer sees it until then, so a human or a sweep should retry.

Choosing ​

Which capture mode ​

SituationRecommendationExtra techniqueReason
Digital goods delivered instantlyAutomatic captureFraud check before confirmNothing to cancel later
Physical goods shipped in daysManual capture on shipmentCapture/void job driven by each payment's capture_beforeNo refund for out-of-stock
Final amount unknown (hotel, rental, delivery)Authorize more, partial captureOne capture only on most cardsRelease the rest automatically
Multi-step checkout across servicesAuthorize first, capture lastSaga with void as compensationCompensation is free before capture
SubscriptionsSaved payment method (SetupIntent), off-session MITDunning, smart retriesCustomer not present

Which integration ​

SituationIntegrationPCITrade-off
Small team, standard checkoutPSP-hosted page (Stripe Checkout)SAQ ALeast control over UX
Custom checkout UXPSP iframe fields (Payment Element, Adyen Drop-in)SAQ A + script criterionYour page scripts must be controlled
Laravel app on StripeLaravel Cashier + Stripe PHP SDK for gapsSAQ ACashier does not build your ledger
Go services on Stripestripe-go behind your own PSP interfaceSAQ AYou write state, ledger, outbox
Need two PSPsRouter + network tokens or a third-party vaultDepends on the vaultDouble reconciliation
Own card formAvoidSAQ DHundreds of controls

Which retry policy ​

FailurePolicyReason
Timeout / 5xx during checkoutSame key, same PSP, a few seconds; then parkUnknown outcome
Connect refusedFail over with a new attempt and keyProvably not processed
Soft decline at checkoutAsk the customer for another methodCustomer is present
Soft decline on renewalDunning schedule or smart retriesFunds may arrive
Hard declineStop; request a new payment methodRetrying cannot work
Webhook processing errorQueue retries with backoff, then dead-letterPSP already got 200

Which fraud action ​

SignalActionReason
Many cards on one device in minutesBlockCard testing
Score 75+ (Radar default "high")BlockHigh risk
Score 65–74, 3DS-capable cardRequest 3DSLiability shift, cheaper than a human
Score 65–74, no 3DSManual review queueA human decides before capture
Trusted customer on the allowlistAllowAvoid false positives
Model timed outRules onlyNever block checkout on the model

In architecture: from a single process to a distributed system ​

Monolith: one process, one database ​

A Laravel shop with Cashier: the checkout controller, the webhook controller, the queue worker and the ledger tables all live in one database, so the payment row, the journal entry and the outbox row commit in one DB::transaction. This is the simplest correct design and the one in this chapter's PHP files. Example: CheckoutController writes the payments row (pay_<order>), creates the PaymentIntent with key pay_<order>:intent and metadata.payment_id, then attaches its id if none is attached; StripeWebhookController stores the event and dispatches the job; ProcessStripeEvent finds the row by stripe_payment_intent_id, moves its status, posts capture:pay_... and inserts an outbox row for the receipt e-mail in one transaction; the e-mail job reads the outbox; the sweeper and the daily reconciliation catch anything that fell through.

Modular monolith: boundaries without the network ​

Split modules: payments (intents, attempts, PSP adapters), ledger (accounts and journal; the only writer of entries), risk (decisions), orders. Other modules call payments through an interface and receive events; nobody else writes payments or ledger tables. Example: orders asks payments.createIntent(order, key) and listens for payment_succeeded; finance reports read the ledger, never the payments table.

Microservices: every arrow is a decision ​

A payment service owns intents, attempts, the PSP adapters and the webhook endpoint; a ledger service owns journal entries; order and fulfilment services consume events. Across services there is no shared transaction: the payment service writes its state and an outbox row together, the relay publishes payments.payment_succeeded with the payment id as partition key, the ledger service posts capture:pi_... idempotently from that event, the order service ships after payment_succeeded. The checkout itself is a saga: inventory reserve → authorize → ship → capture, with void as the compensation. Each hop carries an idempotency key derived from the saga id.

Distributed data: replicas, caches, regions ​

Never read balances or payment status from a replica for a decision (refund allowed? wallet balance?): replica lag turns into double refunds. Keep the idempotency store on the primary or a strongly consistent store, because a key that is not yet visible on a replica is a duplicate charge waiting to happen. Multi-region: pin a payment to its home region (by merchant or by intent id) so its state machine, keys and ledger postings are written in one place; webhooks from the PSP can land in any region, so route them by object id to the home region or store them in a global inbox. Ledger shards by account; a journal entry that touches two shards needs a two-phase posting (pending → posted) or a single shard per merchant.

Scaling path: 1x, 10x, 100x ​

LoadDesignWhat changes
1x (a few payments per minute)Monolith with Cashier, one PostgreSQL, daily reconciliation jobNothing to optimise; correctness first
10x (tens per second, sales peaks)Payment service + queue workers, webhook inbox drained by many workers, fraud engine with velocity in RedisHot accounts (the sales account) serialise postings: use per-merchant or sharded sub-accounts and aggregate
100x (thousands per second, many regions)Ledger as its own service with sharded accounts, outbox via CDC, two PSPs with routing, regional homes, streaming reconciliationHot-account contention, reconciliation volume (millions of lines a day) and PSP rate limits become the bottlenecks

Lab ​

Experiments 1 to 4 are single-process Go and were run for this chapter on Go 1.27.4 (go version go1.27.4 darwin/arm64; go1.27.4 is in the Go release history) (output pasted). Experiments 5 and 6 are expected, not run: they need a Stripe test account and a Laravel application.

1. The naive handler.

text
$ cd docs/snippets/system-design/payment-processing-architecture/go
$ go run ./before
charges sent to PSP: 3 (customer paid twice for the first order)
balance: 0.30000000000000004 (expected 0.3)

Two orders, three charges: the first order's retry after the lost answer was a second real payment. The balance is the float pitfall.

2. Every scenario in one process.

text
$ go run ./cmd/demo
== 1. lost response, same key, one charge
intent=pi_0001 status=succeeded psp_charges=1 replayed_create=true same_id=true
== 2. ambiguous outcome: park, do not fail over
status=requires_confirmation unknown_attempts=1 adyen_charges=0
after recovery: status=succeeded stripe_charges=2
== 3. hold, partial capture, refund, trial balance
sales=14750 refunds=1000 receivable=13750 trial=map[USD:0] journal_rows=4 outbox=5
== 4. money
split 1.00 USD three ways: 0.34 USD 0.33 USD 0.33 USD | 10.00 USD @0.9235 = 9.24 EUR
== 5. webhook signature
valid: <nil>
tampered: webhook: no v1 signature matches
replayed 10m later: webhook: timestamp outside tolerance
== 6. fraud decisions
normal: allow
geo mismatch, 300 USD: request_3ds
7 cards, one device: block [card_testing: >5 cards on one device in 10m model_timeout:rules_only]
== 7. reconciliation
matched=2 missing_locally=1 (stripe_ch_9) fees=314
== 8. chargeback: open, win
receivable after open=9750 after win=12250 fee_kept=1500 status=won trial=map[USD:0]
== 9. dunning
stolen_card: needs_new_payment_method
insufficient_funds: retry in 24h0m0s
== 10. checkout saga: shipment fails, hold is voided
checkout: saga failed and was compensated: step book_shipment: carrier: no slot [voided released]

Read it section by section: (1) the lost response costs one charge, not two, and the replayed create returns the same intent; (2) with Stripe "down after charging", the attempt is parked and Adyen is never called, then the same key resolves it (the counter 2 is cumulative over both orders); (3) the hotel flow leaves a zero trial balance; (4) 1.00 USD splits 34/33/33 and the FX conversion rounds half-even; (5) a tampered body and a 10-minute-old signature are rejected; (6) normal, step-up and block decisions, with the model absent so rules decide; (7) stripe_ch_9 was settled by the PSP but unknown to us; (8) the won chargeback returns 2500 and keeps the 1500 fee; (9) a hard and a soft decline; (10) a failed shipment voids the hold and releases stock in reverse order.

3. The tests.

text
$ gofmt -l . && go vet ./... && go test -race -count=1 ./...
?   	academy/payment-processing-architecture/before	[no test files]
ok  	academy/payment-processing-architecture/checkout	1.198s
?   	academy/payment-processing-architecture/cmd/demo	[no test files]
ok  	academy/payment-processing-architecture/dispute	1.167s
ok  	academy/payment-processing-architecture/dunning	1.172s
ok  	academy/payment-processing-architecture/fraud	1.222s
?   	academy/payment-processing-architecture/idem	[no test files]
ok  	academy/payment-processing-architecture/intent	1.204s
ok  	academy/payment-processing-architecture/ledger	1.265s
ok  	academy/payment-processing-architecture/money	1.263s
?   	academy/payment-processing-architecture/outbox	[no test files]
ok  	academy/payment-processing-architecture/payment	1.313s
ok  	academy/payment-processing-architecture/recon	1.235s
ok  	academy/payment-processing-architecture/webhook	1.234s
$ go test -v ./payment/
--- PASS: TestConcurrentConfirmChargesOnce (0.00s)
--- PASS: TestRefundReservationHeldUntilBooked (0.00s)
--- PASS: TestAmbiguousRefundKeepsReservation (0.00s)
--- PASS: TestRefusedRefundReleasesReservation (0.00s)
--- PASS: TestSuccessWebhookCompletesManualCapture (0.00s)
--- PASS: TestCaptureCallsPSPFirst (0.00s)
--- PASS: TestFailoverRaceChargesOnce (0.00s)
--- PASS: TestRefusalDoesNotProveAnEarlierUnknownAttempt (0.00s)
--- PASS: TestUnknownRefundSurvivesRetryRefusal (0.00s)
--- PASS: TestUnclassifiedRefundErrorIsUnknown (0.00s)
--- PASS: TestDuplicateRefundFailuresDoNotUnderflowReservation (0.00s)
--- PASS: TestPartialCaptureReportedByWebhookFirst (0.00s)
--- PASS: TestCompetingCaptureAmounts (0.00s)
--- PASS: TestFailedPostingDoesNotCompleteTheIntent (0.00s)
--- PASS: TestOnePaymentPerOrder (0.00s)
--- PASS: TestCompletedRefundKeyChecksParameters (0.00s)
--- PASS: TestResolveRefundAfterLookup (0.00s)
--- PASS: TestStaleDeclineWebhookDoesNotTouchLaterAttempt (0.00s)
--- PASS: TestWebhookFirstSuccessKeepsReference (0.00s)
--- PASS: TestRejectedCaptureCloneIsRaceFree (0.02s)
--- PASS: TestUnknownAttemptsReturnsCopies (0.00s)
--- PASS: TestNoResendAfterTheWindow (0.00s)
--- PASS: TestUnbookedCaptureIsBookedWithoutThePSP (0.00s)
--- PASS: TestUnbookedRefundIsBookedWithoutThePSP (0.00s)
--- PASS: TestDelayedResponseKeepsRetainedWebhookSuccess (0.00s)
--- PASS: TestWebhookCannotApplyAfterItsAttemptWasSuperseded (0.00s)
--- PASS: TestCaptureRepairUsesWebhookRetainedSuccess (0.00s)
--- PASS: TestCreateIsIdempotent (0.00s)
--- PASS: TestLostResponseChargesOnce (0.00s)
--- PASS: TestAmbiguousOutcomeIsParkedNotFailedOver (0.00s)
--- PASS: TestFailoverOnlyWhenProvablyNotProcessed (0.00s)
--- PASS: TestDeclineEmitsFailureAndNoLedger (0.00s)
--- PASS: TestAuthorizePartialCaptureRefund (0.00s)
--- PASS: TestWebhookDuplicatesAndStaleEvents (0.00s)
--- PASS: TestOutboxRelayAndConsumerDedup (0.00s)
--- PASS: TestRefundIsCheckedBeforeThePSPAndReplaySafe (0.00s)
--- PASS: TestWebhookForUnknownIntentIsRetriedLater (0.00s)
--- PASS: TestConcurrentRefundsCannotOverRefund (0.00s)

4. Break the ledger on purpose. TestUnbalancedIsRejected posts 1099 debit against 1000 credit; Post returns ledger: debits != credits and nothing is appended (run):

text
$ go test -v -run Unbalanced ./ledger/
=== RUN   TestUnbalancedIsRejected
--- PASS: TestUnbalancedIsRejected (0.00s)

Editing the test to post a single line gives ledger: a transaction needs at least two entries (expected from the code, not run).

5. Stripe test mode, end to end through the app (expected, not run). stripe events resend needs a registered endpoint (--webhook-endpoint=<endpoint_id>), so this lab runs against a staging deployment: create an event destination in the Dashboard (Workbench → Webhooks → Create an event destination → Webhook endpoint, URL https://staging.example.com/webhooks/stripe), which shows its id we_... and its whsec_... secret for services.stripe.webhook_secrets. The payment is created by the app's own checkout, so the row the worker needs exists.

text
0  $ php artisan migrate --force                     # creates the tables AND seeds the ledger accounts
     ...  create_payment_tables ........................ DONE
   $ psql -c "SELECT id FROM ledger_accounts ORDER BY id"   # cash:bank:USD, psp_fees:USD,
                                                         # psp_receivable:stripe:USD, refunds:USD, sales:USD
   $ curl -s -c jar -b jar -o /dev/null https://staging.example.com/orders/42   # jar holds a logged-in session
   $ XSRF=$(awk '$6=="XSRF-TOKEN"{print $7}' jar | python3 -c 'import sys,urllib.parse as u; print(u.unquote(sys.stdin.read().strip()))')
1  $ curl -s -b jar -c jar -H "X-XSRF-TOKEN: $XSRF" -X POST https://staging.example.com/orders/42/charge -d payment_method=pm_card_visa
   {"status":"succeeded"}                                # payments row pay_42 first, then pi_A with
                                                         # metadata.payment_id=pay_42, key pay_42:intent
2  (Stripe -> staging) POST /webhooks/stripe  evt_A payment_intent.succeeded   200
   worker: pay_42 requires_payment_method -> succeeded (forward progress), journal capture:pay_42,
   outbox payments.payment_succeeded, inbox processed_at set
3  $ stripe events resend evt_A --webhook-endpoint=we_staging
   (Stripe -> staging) POST /webhooks/stripe  200        # row exists, processed_at set -> no job
4  $ curl -s -b jar -c jar -H "X-XSRF-TOKEN: $XSRF" -X POST https://staging.example.com/orders/42/charge -d payment_method=pm_card_visa
   {"status":"succeeded"}                                # same order: the attached pi_A is reused, no new charge
5  $ stripe trigger payment_intent.succeeded             # an intent the app never created
   worker: "no payment for pi_B yet" -> retried with backoff -> after 8 tries last_error set (dead letter)
6  $ curl -s -X POST https://staging.example.com/webhooks/stripe -H 'Stripe-Signature: t=1,v1=00' -d '{}'
   {"error":"invalid signature"}                         # 400

The routes are in the web group, so PreventRequestForgery applies: a script has no Sec-Fetch-Site header, so the middleware falls back to token validation, and Laravel "stores the current CSRF token in an encrypted XSRF-TOKEN cookie" whose value goes into the X-XSRF-TOKEN header (step 0). Step 5 is what failing closed looks like: an event that maps to no payment is never acked as processed. For local development, stripe login and stripe listen --all-snapshot --forward-to localhost:8000/webhooks/stripe forward events without a registered URL (the listener prints its own signing secret); resend needs the registered endpoint. Stripe documents stripe events resend <event_id> --webhook-endpoint=<endpoint_id> as working "for up to 30 days after the event creation", and the Dashboard's Resend "for up to 15 days". pm_card_visa is a Stripe test payment method (used in the stripe-php README).

6. Idempotency against Stripe (expected, not run).

text
$ curl https://api.stripe.com/v1/payment_intents -u sk_test_...: \
    -H "Idempotency-Key: lab-order-1001-attempt-1" -d amount=2500 -d currency=usd \
    -d "payment_method_types[]=card"
{ "id": "pi_A...", "status": "requires_payment_method", ... }
$ (same command again)
{ "id": "pi_A...", ... }                                # same object: the saved response
$ (same key, -d amount=9999)
{ "error": { ... } }                                    # parameters differ from the original request

Stripe documents the last case as: the idempotency layer "compares incoming parameters to those of the original request and errors if they’re not the same"; the exact error body was not captured for this chapter.

Common misconceptions ​

BeliefReality
"Money is a float with two decimals"Integer minor units + ISO 4217 code; JPY has 0 decimals, BHD 3, CLF 4; floats lose cents
"A timeout means the payment failed"It is an unknown outcome; resolve it with the same key before anything else
"Fail over to the backup PSP on any error"Only when the first PSP provably did nothing; otherwise you double-charge
"A new idempotency key per retry is safer"A new key is a new payment; derive the key from the intent and attempt
"Authorization means we got paid"It is a hold that expires at the PSP's capture_before (Visa MIT about 5 days, most online cards 7); capture it
"Refund is the compensation for an authorization"Void it; refund only captured money
"The latest webhook wins"Webhooks are at-least-once and unordered; a state machine decides
"Parse JSON then verify the signature"Verify the raw body; re-encoded JSON does not match
"Tolerance 0 is the strictest setting"It disables the replay check entirely
"A balance column with an audit log is a ledger"A ledger derives balances from immutable, balanced entries
"Fix a wrong entry with UPDATE"Post a reversing entry; the audit trail keeps both
"Our webhooks make reconciliation unnecessary"Fees, payouts, dashboard refunds and lost events only show up in the settlement file
"Using a PSP removes PCI DSS"It can reduce scope to SAQ A; scripts on the checkout page are still your problem
"3-D Secure stops all disputes"It shifts fraud liability; "item not received" disputes remain
"Winning a dispute returns everything"Stripe never returns the dispute received fee (Mexico excepted)
"Retry every declined renewal hourly"Hard declines never succeed; soft declines follow a bounded schedule
"The fraud model decides"Rules, velocity and a timeout fallback decide when the model is late

Cheat sheet ​

TopicWhat to remember
MoneyBIGINT minor units + CHAR(3); decimal for rates; round once, half-even or as the business rule says
StateStripe's 7 PaymentIntent statuses; one transition table; version column
MovementsAuthorize → capture (once, ≤ hold, before capture_before) or void; refunds ≤ captured, each with its own key
Client keyIdempotency-Key header; 409 in flight, 422 mismatch, 400 missing
Provider keypi_...:attempt:N; Stripe keeps 24 h (v1), Adyen 7 to 14 days
Unknown outcomeQuery or resend with the same key; a later refusal proves nothing; park; never fail over; reconcile
LedgerDebits = credits per currency; append-only; reversals; derived balances
WebhooksRaw body, HMAC, constant time, 300 s tolerance, multiple secrets, inbox, 200 fast
Order and duplicatesAt-least-once, unordered; dedupe by event id; state machine ignores stale events
OutboxEvent row in the same transaction; relay at least once; consumers dedupe
SagaAuthorize early, capture last; void is the free compensation; dead-letter failed undos
ReconciliationDaily, by psp_reference and payout id; fees and payouts as entries; clearing to zero
DisputesAmount + fee debited at once; 7–21 days to respond; fee kept on a win
SCAPSD2 / RTS 2018/389; 3DS2 frictionless or challenge; MIT needs a mandate
PCIPSP iframe → SAQ A (+ script criterion since 31 Mar 2025); never log PAN/CVV
FraudVelocity + rules + score (Radar 65/75) + 3DS step-up + review queue; 50 ms model budget
DunningHard declines stop; soft declines on a bounded schedule; Stripe Smart Retries up to 8 in 2 weeks
LibrariesCashier for Stripe in Laravel, Stripe PHP SDK for keys and constructEvent, stripe-go v87 (go 1.24)

Known limitations of the sample ​

The code on this page is a teaching sample that fails closed: where a production-grade mechanism is out of scope, the sample detects the situation and refuses (an error, an unknown state, a dead letter) instead of charging or booking wrongly. What it does instead, item by item:

AreaA production system wouldThe sample does instead
Per-payment exclusion (Go)Hold a row lock or a processing status in the database across the PSP callAn in-memory single-flight token; a second caller gets ErrInFlight (409)
Unknown outcomes past the key window (Go)Run an automated lookup and resolution workflowNever resends after ResendWindow (23 h); returns ErrNeedsReconciliation; UnknownAttempts, PendingRefunds and ResolveRefund are the manual exits
Error classification (Go)Map each PSP error code to "processed / not processed / unknown"Only ErrUnavailable on a fresh key counts as "not processed"; everything else is unknown
Webhook attribution (Go)Use the PSP's object ids for every event typeMatches on one payment reference per attempt; an unmatched or contradictory event is ErrNotFound / ErrMismatch and is retried, never acked
Partial captures by webhook (Go)Read the captured amount from the PSP objectRequires the amount on the event; without it the success is refused
Multi-capture, extended authorizationTrack several captures per holdOne capture per hold; a second amount is ErrMismatch
FX and multi-currency postingsFX accounts and rates per transactionRejected: the SQL trigger refuses an entry whose currency differs from its account's
Laravel integration testsFeature tests against Stripe test modephp -l only; the flows are traced in prose and in the lab (expected, not run)
Laravel refund replay after the key windowAn automated lookup of the refund at the PSPThe row becomes needs_reconciliation (amount stays reserved), the route answers 409 and never resends; a second provider refund for one row is thrown to the dead-letter path
Ledger accountsAccount opening as part of merchant onboarding, per currencyThe migration seeds the USD accounts the sample posts to; another currency needs its own rows (an unknown account makes LedgerService::post throw: the event is retried, then dead-lettered)
Laravel checkout crash windowA transactional outbox for the PSP call itselfStable key pay_<order>:intent + metadata.payment_id; after Stripe's 24 h key retention a gap is found by the webhook fallback or by reconciliation
Refunds returned by the bank (Laravel)Re-refund through another channel automaticallyReverses the journal and amount_refunded, emits payments.refund_failed for support
Refund permissions (Laravel)Fine-grained roles and audit of who refundedOrderPolicy::refund: support staff or the order's owner; 403 otherwise
Reconciliation fileThe PSP's full report formatsA reduced five-column contract; map your PSP's columns to it
SQLExecuted migrations and tests on PostgreSQLWritten against the schema file and checked by reading (no PostgreSQL on the build host)

Self-check: questions & answers ​

Show:
  • Must-know asked in almost every interview
  • Important frequent; expected at senior level
  • Good to know extra depth that sets you apart

1 — Why must money never be stored as a float, and what do you store instead? Must-know ​

Answer

Answer: Binary floats cannot represent most decimal fractions (0.1 + 0.2 = 0.30000000000000004), so sums and comparisons drift. Store an integer amount in the currency's minor units plus the ISO 4217 code, take the exponent from the ISO list (JPY 0, USD 2, BHD 3), and use a decimal type only for rates, rounding once into minor units by an explicit rule.

2 — Your call to the PSP times out. What do you do, and what must you never do? Must-know ​

Answer

Answer: Treat it as an unknown outcome: query the PSP or resend the same request with the same provider idempotency key; if still unknown, mark the attempt unknown, show "pending" and let a sweep or reconciliation resolve it. Never retry with a new key and never fail over to another PSP, because the first one may have charged.

3 — How do you derive the idempotency key you send to the PSP, and why not a fresh UUID per call? Must-know ​

Answer

Answer: From stable business identity: the intent id plus the attempt number (pi_42:attempt:1), stored in a unique column, so every retry and every restarted worker sends the same key. A fresh UUID per call makes each retry a new payment; the key must also outlive your retries (Stripe API v1 keys can be pruned after 24 hours).

4 — What is the difference between void and refund, and when is each the compensation in a checkout saga? Must-know ​

Answer

Answer: A void cancels an authorization that was never captured: the hold is released and no money moved. A refund returns captured money and takes days to reach the card. Authorize early and capture last so that every failure before capture is compensated by a cheap void; a refund is the compensation only after capture.

5 — List what a webhook handler must do, in order. Must-know ​

Answer

Answer: Read the raw body; verify the signature (HMAC over t.body, every v1, every active secret, constant time); check the timestamp against the replay window (a tolerance of 0 would reject every real delivery); insert into the inbox keyed by event id (a processed duplicate ends here; an unprocessed duplicate re-dispatches the job); return 2xx quickly; process in a queued job inside one transaction that respects the state machine; after the last retry keep the row with its error as the dead-letter record.

6 — Why does a payment system need a double-entry ledger instead of a balance column? Important ​

Answer

Answer: Every movement is a balanced journal entry (debits = credits), so money cannot appear or vanish through a bug; entries are append-only, so balances can be recomputed and audited at any date; corrections are reversals that keep the history; and clearing accounts such as the PSP receivable show unfinished flows. A mutable balance can drift from its own log with no way to prove which is right.

7 — Stripe sends payment_intent.processing after payment_intent.succeeded. What happens in your system? Important ​

Answer

Answer: Nothing: the state machine has no edge from succeeded to processing, so the job acks the event, marks it processed and changes no state. Stripe does not guarantee order and says not to use created to order events; if you need the latest truth, retrieve the object from the API.

8 — How does the outbox give an exactly-once effect when delivery is only at least once? Important ​

Answer

Answer: The event row is written in the same transaction as the payment and ledger change, so it exists if and only if the change committed. The relay may publish it twice after a crash, so consumers record each event id in an inbox inside the same transaction as their side effect and skip duplicates. At-least-once delivery plus idempotent consumers gives one effect.

9 — What does reconciliation catch that webhooks do not? Important ​

Answer

Answer: Charges the PSP settled that you never booked (often unknown outcomes that succeeded), refunds made in the dashboard, fees and FX, chargebacks you missed, amount mismatches, and whether the payout that reached the bank equals the batch. Match by PSP reference and payout id (Stripe: automatic_payout_id), not by date.

10 — How does accepting cards in a PSP iframe change your PCI DSS scope, and what still applies? Important ​

Answer

Answer: If account data functions are completely outsourced and your systems never store, process or transmit card data, you can validate with SAQ A instead of the full assessment. Since the SAQ A effective on 31 March 2025 you must also confirm your site is not susceptible to script attacks that could affect the e-commerce system; and your acquirer or card brand decides which validation you need.

11 — A medium-risk payment arrives: score 70, card supports 3DS. What does the risk engine do, and why not block? Good to know ​

Answer

Answer: Request 3-D Secure: the issuer authenticates the cardholder and fraud liability typically shifts to the issuer. Blocking loses a probably legitimate sale and sending it to the manual review queue costs a human; step-up is the cheapest safe action. Without 3DS support the same score goes to review (Radar's default thresholds: 65 elevated, 75 high).

12 — A renewal fails with stolen_card; another with insufficient_funds. What does dunning do with each? Good to know ​

Answer

Answer: stolen_card is a hard decline (on Stripe's list): no automatic retry, ask the customer for a new payment method. insufficient_funds is soft: retry on a bounded schedule (attempts and total duration capped), e-mail the customer, and cancel or mark unpaid when the schedule is exhausted.

Glossary ​

TermMeaning
PSPPayment service provider (Stripe, Adyen): your single API to cards and other methods
IssuerThe cardholder's bank; approves or declines
AcquirerThe merchant's bank that accepts card payments on the network
Card networkVisa, Mastercard, etc.; routes authorizations and disputes
Payment intentOne attempt to collect one amount for one order; Stripe's object is the PaymentIntent
PaymentIntentStripe API object with statuses requires_payment_method … succeeded / canceled
State machineFixed set of statuses and allowed transitions; illegal events are rejected
AuthorizationIssuer hold on the amount; expires if not captured
CaptureTurning an authorization into a charge (full or partial)
VoidCancelling an uncaptured authorization; releases the hold
RefundReturning captured money to the payment method
Partial refundA refund of part of the captured amount; several are allowed
Manual captureAuthorize now, capture later (capture_method=manual)
Idempotency keyClient-chosen unique key; the server performs the operation once per key
Idempotency-Key headerThe HTTP header carrying the key (IETF draft, Stripe)
Provider idempotency keyThe key you send to the PSP, derived from intent and attempt
FingerprintHash of the canonical request, to detect a key reused with other parameters (422)
Unknown outcomeTimeout or 5xx after sending: the effect may or may not have happened
TimeoutsPer-call deadlines; must be short and fit the checkout budget
RetriesRe-sending with the same key; bounded, with backoff and jitter
AttemptOne call to one PSP with one key: sent, done, unknown
FailoverTrying another PSP; only after a provably-not-processed failure
Minor unitsThe smallest currency unit (cents, yen, fils) stored as an integer
ISO 4217The standard for currency codes and minor-unit exponents
Money typeValue object of integer amount + currency code with safe arithmetic
DecimalExact base-10 number type (NUMERIC, big.Rat, bcmath) for rates and fractions
Float pitfallsBinary floating point cannot represent 0.1; sums and comparisons drift
Currency roundingThe explicit rule (half-up, half-even) that maps an exact value to minor units
AllocationSplitting an amount so the parts always sum to the whole
Double-entry ledgerLedger where every journal entry has equal debits and credits
Journal entryOne balanced, atomic set of ledger lines (journal transaction)
DebitEntry that increases debit-normal accounts (assets, expenses)
CreditEntry that increases credit-normal accounts (liabilities, revenue, equity)
Debit normal / credit normalWhich side increases an account's balance
Clearing accountAccount for money in transit (PSP receivable) that should return to zero
Trial balanceSum of all debits minus credits; zero in a sound ledger
Ledger immutabilityEntries are never updated or deleted
Append-onlyOnly inserts are allowed; enforced by triggers here
ReversalA new journal entry that mirrors a wrong one
Audit trailThe complete, immutable history of who posted what and when
WebhookHTTP callback from the PSP announcing an event
Signature verificationChecking the webhook's HMAC over the raw body with the signing secret
Stripe-SignatureStripe's header: t= timestamp and one v1= HMAC-SHA256 per active secret
HMACHash-based message authentication code (HMAC-SHA256 for Stripe and Adyen)
Replay windowTolerance on the signed timestamp (5 minutes in Stripe's libraries)
Secret rollChanging the signing secret with an overlap (up to 7 days on Stripe)
At-least-once deliveryEvery event arrives one or more times
Out-of-order webhooksEvents arrive in a different order than they were created
Webhook idempotency tableInbox table keyed by (PSP, event id); a duplicate insert is a no-op
InboxConsumer-side dedup table recording processed event ids
Dead-letterWhere a message goes after the last failed retry, for a human or a sweep
OutboxTable of events written in the business transaction, published by a relay
Exactly-once effectOne business effect despite duplicate deliveries
SagaSequence of local transactions with compensations instead of one global transaction
CompensationThe action that semantically undoes a completed saga step (void, release)
ReconciliationMatching your records against the PSP's settlement file and the bank
Settlement filePSP report of settled lines (gross, fee, net) per batch
PayoutTransfer of your PSP balance to your bank account
ChargebackIssuer-initiated reversal of a card payment
DisputeThe case around a chargeback or inquiry, with evidence and outcome
InquiryPre-dispute request for information (retrieval)
Liability shiftFraud-dispute liability moves to the issuer after successful 3DS
3-D SecureCard authentication protocol (EMV 3DS2) with frictionless and challenge flows
SCAStrong Customer Authentication: two-factor authentication required in the EEA
PSD2EU Payment Services Directive 2; its RTS (Regulation 2018/389) define SCA
MITMerchant-initiated transaction: off-session charge under a mandate
PCI DSSPayment Card Industry Data Security Standard (current v4.0.1)
SAQ AShortest PCI self-assessment, for fully outsourced card data functions
PANPrimary account number: the card number
TokenizationReplacing the PAN with a token usable only through the PSP
Network tokensTokens issued by the card network (Visa Token Service) that survive card reissue
Card vaultingStoring cards for reuse; with a PSP, the PSP's vault holds the PAN
Risk engineComponent that combines rules, velocity and a model into a decision
Fraud scoreModel output (Radar: 0–99)
Velocity rulesLimits on attempts per card, device, IP or e-mail in a time window
Device fingerprintStable identifier of the customer's device from the checkout SDK
Card testingBots trying many stolen cards with small charges
Manual review queuePayments held for a human decision
Soft declineDecline that may succeed later (insufficient_funds)
Hard declineDecline that needs a new payment method (stolen_card)
DunningRetrying failed recurring charges and contacting the customer
Smart retriesModel-chosen retry times (Stripe: up to 8 retries in 2 weeks by default)
Laravel CashierLaravel's Stripe billing package on top of the Stripe PHP SDK
Stripe PHP SDKstripe/stripe-php; Webhook::constructEvent, idempotency_key option
stripe-gogithub.com/stripe/stripe-go/v87; stripe.NewClient, webhook.ConstructEvent

References ​

Built by Morteza Negahi