Secure Embedded Bank-Transfer Checkout Component Design
System DesignModel answerLast updated
Design a merchant-embeddable bank-payment checkout component: isolated iframe, safe parent-frame messaging, token exchange, asynchronous settlement, and webhook reliability at high scale.
Problem
Your company runs a payments platform and wants to offer a drop-in bank-transfer checkout component. A merchant adds a small JavaScript SDK to its checkout page. When a shopper picks "pay from my bank", the SDK opens a modal containing an iframe served from your own domain. Inside it, the shopper finds their bank, signs in, and approves a transfer over a rail such as ACH, RTP, or FedNow. The merchant must never see the shopper's bank credentials or account details.
Functional requirements
- Session creation: the merchant's server creates a single-use, short-lived session token tied to the amount, currency, and merchant identity.
- Widget lifecycle: the SDK creates an iframe pointing at your hosted domain, sets up a trusted two-way channel with it, and surfaces callbacks such as
onSuccess,onExit, andonError. - Consent and token exchange: the widget records the shopper's consent, finishes the bank's OAuth (or equivalent) handoff, and yields a short-lived code that the merchant's server exchanges for a payment token (single-use or reusable).
- Asynchronous settlement: final settlement can take seconds to minutes (RTP, FedNow) or several business days (ACH). Merchants learn about progress via webhooks.
Non-functional and security requirements
- Bank credentials, account numbers, and internal auth tokens must never reach the merchant's DOM or network logs.
- Defend against clickjacking, XSS, and origin spoofing in parent-to-iframe messaging.
- Be safe under retries: dropped connections, interrupted OAuth redirects, double clicks.
- 99.99% availability; iframe cold load under 500 ms.
Scale
- Peak 10,000 widget loads per second and 500 completed authorizations per second.
- More than 5,000 merchants and 100 million linked bank accounts.
What your answer should cover
- The end-to-end flow and APIs across merchant server, merchant page, iframe, your backend, and bank APIs.
- Browser security: the
postMessagehandshake, origin checks, CSP, iframe sandboxing, and OAuth redirect strategy. - The data model and state machines for sessions and payments, including failures, returns, and disputes.
- Reliability and observability: funnel tracking, PII-free telemetry, and webhook delivery guarantees.
Hints
Hint 1
Size the system first. Widget loads are static and belong on a CDN; the origin mostly sees session lookups. Authorizations (500/s) are modest for the database, and each payment produces several webhook events.
Hint 2
Ask which party you trust at each hop. The merchant page is untrusted, so the amount and payee must be fixed server-side at session creation, and the client-side success event should mean only 'the user consented', not 'money moved'.
Hint 3
Banks often forbid framing and third-party cookies break in-frame sessions, so run bank sign-in in a popup or top-level redirect rather than inside the iframe. Use PKCE and a signed state value, and let the server finish the code exchange.
Hint 4
Model sessions and payments as separate state machines. Payments need states for returns and disputes, and every transition should be an append-only event that also feeds the webhook outbox.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
1. Scope and sizing
I would confirm scope first: a web SDK, a hosted widget domain, and the backend with webhooks. Native mobile SDKs and risk underwriting are out of scope.
- Widget loads, 10k/s: serve the roughly 80 KB gzipped bundle and the iframe shell from a CDN. Only session lookups reach the origin, about 10k reads/s from a Redis-style session cache.
- Authorizations, 500/s: each involves a few bank API calls and one payment write. Under 1k DB writes/s per region is easy.
- Webhooks: about 3-5 events per payment gives roughly 2.5k deliveries/s at peak, plus retries.
- Storage: 100M linked accounts at about 1 KB is about 100 GB. A sharded relational store keyed by item ID works. Raw account numbers go to a separate tokenized vault.
- 99.99% is about 52 minutes of downtime per year. Use multi-region active-active for stateless tiers and CDN failover. Bank outages are outside our control, so degrade per institution, not globally.
2. Flow and APIs
- Merchant server calls
POST /link/token/createwith credentials, amount, currency, allowed origin, webhook URL, and an idempotency key. It receives alink_token. - Merchant page passes the token to the SDK, which creates the iframe at
https://link.example.com/?session=.... - Iframe loads session metadata (amount, merchant name) from our backend, never from the parent, then lets the user search for a bank and give consent.
- Bank sign-in happens in a popup (see section 3). Our backend finishes the OAuth code exchange and fetches account data.
- Iframe to SDK:
onSuccessdelivers apublic_tokenplus non-sensitive metadata (institution name, masked account). - Merchant server calls
POST /payment/authorizewith thepublic_token, its secret, and an idempotency key. It gets apayment_idwith statusPENDING, never account numbers. A reusable token is returned only when the merchant requested recurring payments.
Key decisions:
- Amount and payee are bound server-side at token creation, so a tampered page cannot change them.
public_tokenis single-use, lives about 30 minutes, and is useless without the merchant secret.onSuccesstherefore means consent, not payment.
3. Browser security
Handshake
- The SDK creates the iframe and keeps its
contentWindow. - The iframe fetches the session's registered
allowed_originand posts{type: "READY", nonce}to the parent with that exacttargetOrigin, never"*". - The SDK accepts only messages where
event.originequals our widget origin andevent.sourceequals the iframe's window. - The SDK answers by transferring a
MessagePortfrom aMessageChannel. Subsequent traffic uses that private port, invisible to other frames. - Messages are versioned, carry the nonce, are schema-validated, and unknown fields are dropped.
- Only non-sensitive data crosses the channel.
Headers on the hosted domain
frame-ancestorsset per session to the merchant's registered origin, which blocks framing by unregistered sites.- Strict
script-srcwith nonces, narrowconnect-src,object-src 'none', and Trusted Types. Ship no third-party scripts inside the iframe. - Cookies are
Secure; HttpOnly; SameSite=None; Partitioned, but session state is keyed by the opaque session ID so we survive cookie blocking.
Iframe attributes: sandbox="allow-scripts allow-same-origin allow-forms allow-popups allow-popups-to-escape-sandbox". allow-same-origin is safe because the frame is cross-origin to the merchant; it only grants our own origin's storage. Omit allow-top-navigation; the SDK does any top-level redirect itself.
Clickjacking by the parent: the merchant can overlay the iframe, but final consent happens on the bank's own top-level page, which the merchant cannot forge.
OAuth strategy: banks typically forbid framing, so never run OAuth inside the iframe.
- Primary: popup to the bank, with
stateas a signed value binding the session ID, and PKCE. The callback hits our domain, the server completes the exchange, and the iframe is notified viaBroadcastChannelwith a server poll as fallback. - Popup blocked or mobile webview: full-page redirect with a merchant-supplied
redirect_uri; the SDK resumes the same session on return.
4. Data model and state machines
link_session(session_id PK, merchant_id, amount_minor, currency, allowed_origin,
status, idempotency_key UNIQUE(merchant_id,key), expires_at, item_id, public_token_hash, version)
payment(payment_id PK, session_id UNIQUE, merchant_id, item_id, rail, amount_minor,
status, rail_reference, return_code, version)
payment_event(event_id PK, payment_id, seq, from_status, to_status, payload, ts)
webhook_delivery(event_id, endpoint_id, attempt, status, next_attempt_at)
Session: CREATED, OPENED, INSTITUTION_SELECTED, AUTH_PENDING, AUTHORIZED, EXCHANGED, with terminal EXPIRED, EXITED, FAILED.
Payment: PENDING, SUBMITTED, POSTED, SETTLED, with FAILED and RETURNED branches, and SETTLED can move to DISPUTED, then REVERSED or UPHELD.
Rail differences:
- RTP/FedNow settle in seconds and are irrevocable. Refunds are new credit transfers or return requests.
- ACH can be returned for days (insufficient funds within a couple of days; unauthorized-debit returns up to 60 days). Merchants must treat
POSTEDas provisional andSETTLEDas safe only after the return window they care about.
Use optimistic locking (version) and unique constraints for idempotency. Transitions are validated against an allowed-edge table and written as append-only events in the same transaction as the state change.
5. Reliability and observability
- Idempotency: keys on token creation and exchange, unique per merchant. A duplicate click returns the original result. The public token is consumed atomically.
- Webhooks: use a transactional outbox so an event exists if and only if the state change committed. Deliver at-least-once with signed payloads (HMAC with timestamp), exponential backoff with jitter over about 24-72 hours, per-endpoint circuit breakers, and a dead-letter queue. Include
event_idand a sequence number so consumers can dedupe and reorder. Also offer a "list events" API so merchants can reconcile. - Funnel telemetry: emit events per step (loaded, institution searched, selected, auth started, consent, exchanged) keyed by session ID. Scrub PII: no names, account numbers, or free-text search terms; log institution IDs and error codes only. Alert on per-institution conversion drops.
- Degradation: per-bank health checks and circuit breakers, with a "this bank is unavailable" screen and alternatives.
- Cold load under 500 ms: CDN-cached shell, preconnect to the API, prefetch the popular institutions list, and a small bundle.
Common mistakes
- Trusting an amount or payee sent from the parent page.
- Using
postMessage(..., "*")or checking onlyevent.originbut notevent.source. - Running bank OAuth inside the iframe.
- Treating
onSuccessor ACHPOSTEDas final payment. - Sending webhooks directly from the request path without an outbox.
- Logging bank names with user identifiers or search text in telemetry.