Sub topic 13
Integrating and routing across PSPs
This chapter assumes you know the payment lifecycle (authorize, capture, settle), idempotency keys, and the payment state machine from earlier chapters. You should also be comfortable reading short Python snippets.
A payment service rarely talks to one payment service provider (PSP) forever. Teams add a second PSP for resilience, lower fees, local payment methods, or better approval rates in a region. This chapter covers how to isolate PSP-specific code, how to choose a PSP for each payment, and when it is safe to try another one.
Why more than one PSP
- Availability. A PSP outage should not stop all revenue.
- Cost. Fees differ by card type, country, and volume tier.
- Coverage. Some PSPs support local methods (bank debits, wallets) or currencies that others do not.
- Approval rate. The same card can be approved at one acquirer and declined at another.
- Negotiating position. A working second integration limits vendor lock-in.
Each extra PSP adds an API, a set of status codes, a webhook format, and a settlement report to maintain. Add one only when a reason from this list justifies it.
The adapter layer
Put every PSP behind one internal interface. The rest of the system (API, state machine, ledger) never sees a PSP's field names or status strings. This is sometimes called an anti-corruption layer. Each adapter has three jobs:
- Translate requests. Convert your internal amount, currency, and token into the PSP's format. Some PSPs expect minor units, and some expect decimal strings. Zero-decimal and three-decimal currencies need explicit handling.
- Normalize responses. Map the PSP's many codes onto a small set of internal outcomes.
- Normalize events. Convert PSP webhooks into your internal event type, after verifying their signatures.
The most important design decision is the outcome set. Four outcomes are enough to drive routing:
| Outcome | Meaning | Safe to try another PSP? |
|---|---|---|
| `APPROVED` | The PSP authorized the payment. | No. Move on to capture. |
| `DECLINED` | The issuer or the PSP refused. | Usually no. A hard decline such as "stolen card" will fail everywhere. |
| `NOT_SENT` | The request definitely never reached the PSP (DNS failure, connection refused, open circuit breaker). | Yes. |
| `UNKNOWN` | The request may have reached the PSP (timeout, connection reset after sending). | No, not until the first attempt is resolved. |
Routing rules
A router takes payment attributes and returns an ordered list of PSPs to try. Start with static rules in configuration:
- Currency and country, for example EUR card payments go to PSP A first.
- Payment method, for example a local bank debit only exists at PSP B.
- Merchant preference or contract, for example a merchant that brought its own acquiring agreement.
- Card attributes such as brand or BIN range, for example debit versus credit when fees differ.
Dynamic routing adds live signals: recent approval rate per PSP and card type, latency, and error rate. Keep it simple at first. A weighted split (90/10) lets you measure a new PSP on real traffic before you shift volume to it. Log which rule picked the PSP, because "why did this payment go to PSP B?" is a question support will ask.
Failover without double charging
Failover is where multi-PSP systems lose money. Suppose PSP A times out after receiving your request. If you now send the same payment to PSP B, both may approve it, and the customer is charged twice. PSPs do not share idempotency state, so your key at A means nothing at B.
Follow these rules:
- Fail over only on
NOT_SENT. A connection that was never opened, or a circuit breaker that rejected the call locally, is safe. - Resolve
UNKNOWNat the same PSP. Retry with the same idempotency key, or query the payment by your reference. Only after the PSP says it has no record, or you have voided any authorization it created, may you move on. - Use one idempotency key per PSP attempt. Derive it from the payment id and the PSP name so retries at the same PSP reuse the key and attempts at different PSPs do not collide.
- Record every attempt. Store the PSP, key, outcome, and PSP reference in an attempts table linked to the payment. Reconciliation and incident review need this history.
- Do not retry hard declines elsewhere. It wastes attempts, can raise issuer suspicion, and some networks penalize repeated retries of declined transactions.
from dataclasses import dataclass
from enum import Enum
from typing import Optional
class Outcome(Enum):
APPROVED = "approved"
DECLINED = "declined"
NOT_SENT = "not_sent"
UNKNOWN = "unknown"
@dataclass(frozen=True)
class Result:
outcome: Outcome
psp_ref: Optional[str] = None
class FakePsp:
"""Stand-in for a real adapter that returns a fixed outcome."""
def __init__(self, name, outcome):
self.name = name
self._outcome = outcome
def authorize(self, idempotency_key, amount_minor, currency, token):
ref = f"{self.name}-ref" if self._outcome is Outcome.APPROVED else None
return Result(self._outcome, ref)
ROUTES = {("EUR", "card"): ["psp_a", "psp_b"]}
DEFAULT_ROUTE = ["psp_b", "psp_a"]
def choose_order(currency, method):
return ROUTES.get((currency, method), DEFAULT_ROUTE)
def authorize_with_failover(payment_id, order, adapters, amount_minor, currency, token):
for name in order:
key = f"{payment_id}:{name}" # one key per payment and PSP
result = adapters[name].authorize(key, amount_minor, currency, token)
if result.outcome is Outcome.NOT_SENT:
continue # the only outcome that allows trying the next PSP
return name, result # approved, declined, and unknown all stop here
return None, Result(Outcome.NOT_SENT)
adapters = {
"psp_a": FakePsp("psp_a", Outcome.NOT_SENT),
"psp_b": FakePsp("psp_b", Outcome.APPROVED),
}
order = choose_order("EUR", "card")
print(authorize_with_failover("pay_123", order, adapters, 1999, "EUR", "tok_abc"))Running this prints ('psp_b', Result(outcome=<Outcome.APPROVED: 'approved'>, psp_ref='psp_b-ref')). PSP A reported NOT_SENT, so the router moved to PSP B.
Circuit breakers and health
A circuit breaker tracks recent failures per PSP. After too many failures it opens, and calls to that PSP fail immediately as NOT_SENT without a network call. After a cool-down it lets a few trial requests through. This protects your threads from slow timeouts and makes failover fast. Count only technical failures (timeouts, 5xx, connection errors). Customer declines say nothing about PSP health, so counting them would trip the breaker on a bad batch of cards.
Tokens and portability
Switching PSPs is hard when saved cards live in a PSP's vault, because tokens usually work only with the PSP that issued them. Your options:
- PSP-owned tokens. Simple, but each saved card is locked to one PSP.
- Your own vault. You store card data in a PCI-scoped vault and send it to any PSP. This gives the most flexibility and the largest compliance burden (see the security chapter).
- Network tokens. Card-network tokens are tied to the card, not to one PSP, and work across providers that support them.
Decide this before you add a second PSP. Retrofitting token portability means migrating live card data.
Webhooks and reconciliation across PSPs
Each PSP sends events in its own shape, on its own schedule, and sometimes out of order or duplicated. The adapter should verify the signature, normalize the event, and attach the PSP name and PSP reference. The rest of the system then treats events from all PSPs the same way. Every PSP also produces its own settlement report with different columns and cutoff times. Reconciliation needs one parser per PSP that outputs a common record format, keyed by PSP reference and your payment id.
Testing an integration
- Run each adapter against the PSP's sandbox, and also against a fake that can simulate timeouts, duplicate webhooks, and malformed responses.
- Write contract tests that every adapter must pass, such as "a repeated key returns the same result."
- Test failover with injected
NOT_SENTandUNKNOWNfaults, and assert that only one PSP ever holds an approval.
Exercise
Your router sends a payment to PSP A, and the call times out after the request was written to the socket. The retry budget at PSP A is used up. A teammate proposes sending the payment to PSP B right away so the customer is not kept waiting. What should the system do instead, and why?
Show answer
Treat the result as UNKNOWN and do not fail over yet. PSP A may have authorized the payment, and PSP B has no knowledge of PSP A's idempotency state, so both could approve it and the customer would be charged twice. First resolve the attempt at PSP A by querying the payment by your reference or retrying with the same idempotency key. Fail over only if PSP A confirms it has no record, or after any authorization it created has been voided. Return a pending status to the client in the meantime and let the webhook or status check finish the payment.