Design a payment API: intents, refunds and reliability

Difficulty: Advanced

Question

Design the core API of a payment platform (like Razorpay or Stripe): creating payments, capturing, refunds, webhooks and reliability guarantees.

Answer

Money APIs are unforgiving, so the guiding principles are correctness over speed, no duplicates, complete audit trails and explicit states. Let me sketch the model first. A merchant integrates server side to create an order or payment intent representing the intention to collect a specific amount, and a customer completes payment on the client using a hosted checkout or SDK, so sensitive card data never touches the merchant's servers (PCI DSS scope reduction through tokenization). The gateway then authorizes and captures the payment and notifies the merchant via webhooks.

Resources. Payment intent (or order): id, amount in minor units, currency, status, customer, metadata, capture method. Payment attempt: each try by the customer, which may fail and be retried under the same intent. Refund: linked to a payment. Customer and payment method (tokenized). Webhook events. Endpoints: POST /v1/payment_intents to create; GET /v1/payment_intents/{id}; POST /v1/payment_intents/{id}/confirm; POST /v1/payment_intents/{id}/capture for delayed capture (authorize now, capture later, up to a limit, e.g. 7 days); POST /v1/payment_intents/{id}/cancel; POST /v1/refunds with { payment_id, amount?, reason } for full or partial refunds; GET /v1/refunds?payment_id=...; and list endpoints with cursor pagination and created-time filters.

States: requires_payment_method, requires_action (3-D Secure or UPI approval), processing, authorized, captured (succeeded), failed, cancelled, and for refunds pending, succeeded, failed. Make the state machine explicit; illegal transitions return 409. The state after a timeout may be unknown, since banks can be slow, so a processing state and reconciliation are essential.

Idempotency is mandatory on every POST via the Idempotency-Key header, with keys stored per merchant, request fingerprints compared, and stored responses replayed, including for refunds so a retry can never refund twice. Additionally enforce business rules in the database: a refund amount plus already refunded amount must not exceed the captured amount, checked within a transaction with row-level locking or a conditional update.

Money handling: integer minor units (paise), ISO 4217 currency codes, no floats, and explicit rounding rules for tax splits. Keep an immutable double-entry ledger where every movement produces balanced debit and credit entries, so balances are derived and auditable.

Webhooks are the source of truth for asynchronous outcomes: payment.authorized, payment.captured, payment.failed, refund.processed. Sign them with HMAC, retry with backoff for days, include unique event ids, and advise merchants to deduplicate and to verify state via the API. Never let the frontend redirect be the only signal of success, since users close tabs. Provide a reconciliation API or daily settlement reports so merchants can match payments to bank credits.

Security: API keys with separate test and live modes, restricted keys with scopes (read-only for dashboards), HTTPS and HSTS only, request signing or mTLS for large partners, rate limits, IP allowlists, and audit logs for every state-changing call. Never log card numbers or CVV. Use tokens (card-on-file tokens) for repeat payments, and strong customer authentication where regulations such as RBI's require it.

Failure handling and reliability: calls to banks or networks are retried carefully with idempotent references; use the outbox pattern so ledger writes and outgoing events commit atomically; run reconciliation jobs comparing your records to the acquirer's; and make timeouts produce 'processing', never guess 'failed'. Return errors in problem+json with a stable code such as card_declined or insufficient_funds, plus decline reasons safe to show.

Versioning: date-pinned versions protect merchants from breaking changes, and test-mode sandboxes with magic card numbers let developers trigger each outcome.

Code examples

Create intent, then refund

POST /v1/payment_intents HTTP/1.1
Authorization: Bearer sk_test_...
Idempotency-Key: 11a7...
Content-Type: application/json

{ "amount": 150000, "currency": "INR", "capture_method": "automatic", "metadata": { "order_id": "ord_9001" } }

HTTP/1.1 201 Created
{ "id": "pi_1", "status": "requires_payment_method", "client_secret": "pi_1_secret_x" }

POST /v1/refunds HTTP/1.1
Idempotency-Key: 22b8...
{ "payment_id": "pay_7", "amount": 50000, "reason": "customer_request" }

HTTP/1.1 201 Created
{ "id": "rfnd_3", "status": "pending", "amount": 50000 }

Each money-moving POST carries an idempotency key; refunds are partial and asynchronous.

Guarding refund limits transactionally

await db.tx(async (t) => {
  const p = await t.one('SELECT amount, refunded FROM payments WHERE id=$1 FOR UPDATE', [paymentId]);
  if (p.refunded + amount > p.amount) {
    throw Object.assign(new Error('Refund exceeds captured amount'), { status: 422 });
  }
  await t.none('UPDATE payments SET refunded = refunded + $1 WHERE id=$2', [amount, paymentId]);
  await t.none('INSERT INTO refunds(id,payment_id,amount,status) VALUES($1,$2,$3,$4)', [refundId, paymentId, amount, 'pending']);
  await t.none('INSERT INTO outbox(topic,payload) VALUES($1,$2)', ['refund.created', { refundId }]);
});

Row lock prevents concurrent over-refunds, and the outbox insert commits atomically with the state change.

Key points

Common follow-up questions

Interview tips

Concepts covered

payment API, payment intent, refunds, reconciliation

More API Design questions