Sub topic 5
Designing the payment API
This chapter covers the public API of a payment service: its resources, its endpoints, and how it reports results and errors. It assumes you know basic HTTP and REST, can read short SQL and Python snippets, and understand timeouts and retries. Idempotency, the state machine, and the ledger each get their own chapter. Here we only mark where the API must leave room for them.
What the API must do
A merchant's server calls the API to take money from a customer. Three facts about payments shape the design:
- A request can succeed even when the caller never sees the response, because networks time out.
- A payment finishes over time. Some results arrive minutes or days later.
- Errors have real cost. A wrongly reported failure can lead to a second charge, and a wrongly reported success can lead to goods shipped for free.
The API therefore exposes a payment as a resource with a status that changes over time. It does not expose a single "charge" call that returns a final answer.
Choose the resources
Model the nouns first. A small, stable set covers most designs.
| Resource | Purpose | Created by |
|---|---|---|
| Payment | One attempt to collect an amount from a customer | Merchant request |
| Capture | A request to collect funds that were authorized earlier | Merchant request |
| Refund | A return of captured funds, in full or in part | Merchant request |
| Payment method | A token that stands for a card or bank account | Client-side tokenization |
| Event | A record that something changed, delivered by webhook | The system |
Each resource has its own ID, so a refund is a separate object that points to its payment. Do not make refunds a field on the payment. A payment can have several partial refunds, and each one needs its own status, its own idempotency key, and its own ledger entries.
Endpoints
Use plural nouns, and use sub-resources for actions that create something.
| Method and path | Meaning |
|---|---|
| `POST /v1/payments` | Create a payment, optionally authorizing it at once |
| `GET /v1/payments/{id}` | Read the current state |
| `POST /v1/payments/{id}/captures` | Capture some or all of an authorized amount |
| `POST /v1/payments/{id}/voids` | Release an authorization |
| `POST /v1/payments/{id}/refunds` | Refund a captured payment |
| `GET /v1/payments?status=...&created_gte=...` | List payments with pagination |
Actions such as capture and void are POST requests to sub-resources. They are not PATCH requests that set status directly. A client that sets status could ask for a transition the state machine forbids, and the API would have to guess what the client meant. With a sub-resource, the intent is explicit, and the server decides whether the move is legal.
The create request
A create request carries only what the merchant knows:
{
"amount": 1999,
"currency": "USD",
"payment_method": "pm_tok_8f2a",
"capture": "manual",
"reference": "order-10442",
"metadata": {"cart_id": "c-77"}
}Points to notice:
amountis an integer in minor units, so 1999 means 19.99 USD. A string such as"19.99"is acceptable if the currency exponent is documented, but a JSON float is not.currencyis required and is an ISO 4217 code. There is no default currency.payment_methodis a token, never a raw card number. The security chapter explains why.referenceis the merchant's own order ID. It helps reconciliation but does not replace the idempotency key. Two real orders may legitimately share a reference after a retry at the business level.captureselects between authorize-then-capture and a single combined step.
The response returns the payment with a server-generated id, the status, and timestamps. The server never accepts an ID or status from the client.
The idempotency header
Every POST that moves money takes an Idempotency-Key header. The client generates a unique value, such as a UUID, once per intended operation and reuses it on every retry of that operation.
POST /v1/payments HTTP/1.1
Host: api.example-psp.test
Authorization: Bearer sk_live_...
Idempotency-Key: 5d0c7a0e-3f1b-4c3a-9d11-0b1d6a4c2e11
Content-Type: application/jsonThe API contract needs to state these rules, even though the next chapter covers the mechanism:
- Same key and same request body returns the original result, including the original status code.
- Same key and a different body returns an error, so a bug in the client is caught.
- Keys are scoped per merchant, so two merchants can never collide.
- Keys expire after a documented period, such as 24 hours or more.
Synchronous and asynchronous results
Card authorization usually completes in one or two seconds, but other methods do not. Bank transfers, wallet redirects, and 3-D Secure challenges need the customer or a third party to act. The API handles both with one shape: the response always carries a status, and some statuses mean "not finished".
import uuid
import requests
def create_payment(base_url, api_key, amount_minor, currency, token):
key = str(uuid.uuid4()) # store this with the order before sending
response = requests.post(
f"{base_url}/v1/payments",
headers={
"Authorization": f"Bearer {api_key}",
"Idempotency-Key": key,
},
json={
"amount": amount_minor,
"currency": currency,
"payment_method": token,
},
timeout=10,
)
response.raise_for_status()
payment = response.json()
if payment["status"] == "requires_action":
return payment["next_action"]["redirect_url"]
return payment["status"]When the status is requires_action, the response includes a next_action object, for example a redirect URL. When the customer returns, the final result still arrives through a webhook, and GET /v1/payments/{id} is available as a fallback. The caller should never assume that a response means "final".
Errors that clients can act on
The client needs to know three things from an error: did the operation happen, is it safe to retry, and what should be fixed. Use the HTTP status for the category and a machine-readable code for the detail.
| HTTP status | Code example | Retry with same key? |
|---|---|---|
| 400 | `invalid_amount` | No. Fix the request. |
| 401 / 403 | `invalid_api_key` | No. Fix credentials. |
| 402 | `card_declined` | No. A decline is a valid, final result. |
| 409 | `idempotency_key_reused` | No. The key was used with a different body. |
| 422 | `unsupported_currency` | No. |
| 429 | `rate_limited` | Yes, after the `Retry-After` delay. |
| 500 / 503 | `internal_error` | Yes, with the same key. |
A card decline is not a server failure. Return it as a normal payment with status failed and a decline reason, or as a 402 with the payment ID in the body. Either way, the payment record exists and can be read later.
{
"error": {
"type": "card_error",
"code": "insufficient_funds",
"message": "The card has insufficient funds.",
"payment_id": "pay_01HZX3",
"request_id": "req_8c1e"
}
}Do not forward the issuer's raw response codes to merchants without translating them. Some codes hint at fraud, and showing them to the customer helps attackers. Give the merchant a normalized code and a "may retry" flag, and keep the raw code in your internal logs.
Versioning, pagination, and authentication
- Versioning. Put the major version in the path (
/v1/). Add fields freely, since clients must ignore unknown fields. Never rename a field or change a meaning inside a version. - Pagination. Use cursor pagination for lists. Offset pagination skips or repeats rows when new payments arrive during paging, which breaks reconciliation jobs.
- Authentication. Use secret API keys on the server side and short-lived public keys in browsers and apps. Public keys can only create tokens. They cannot create or read payments.
- Rate limits. Limit per merchant and return
429withRetry-After. Count retries with the same key as the same operation, or the limit may punish a client for being careful.
The request flow
The API writes the payment row before it calls the outside party. If the process crashes after the call, a record still exists, and a later job can find the payment stuck in created and ask the PSP what happened.
Validation at the edge
Validate before any money logic runs, and reject early:
- Amount is a positive integer and fits within the currency's allowed range.
- Currency is supported for this merchant.
- Capture amount does not exceed the authorized amount minus earlier captures.
- Refund amount does not exceed the captured amount minus earlier refunds.
- Metadata has size limits, for example 50 keys of 500 characters each.
The capture and refund limits depend on current state, so check them again inside the database transaction that records the change. A check done earlier can be stale when two requests run at once.
Common mistakes
- Using
PUTorPATCHto change status, which lets clients request illegal transitions. - Returning
200with{"success": false}. HTTP clients and monitoring tools then count failures as successes. - Making the idempotency key optional. Clients skip optional safety features until the first double charge.
- Treating a timeout as a failure on the client. A timeout means "unknown", and the right response is to retry with the same key or to read the payment.
- Logging full request bodies. Tokens are less sensitive than card numbers, but metadata and customer data still need care.
Exercise
A merchant's server sends POST /v1/payments with Idempotency-Key "abc" and amount 1999. The request times out. The merchant's code then sends the same key with amount 2999 after a bug changed the cart total. What should the API return, and why?
Show answer
It should return a 409 error such as idempotencykeyreused, and it should not create or modify any payment. The key matches a stored request, but the request body hash differs. Returning the original result would hide the bug, and processing the new request would risk a second charge. The merchant must fix the bug and use a new key for the new amount.
Exercise
Why is POST /v1/payments/{id}/captures a better design than PATCH /v1/payments/{id} with {"status": "captured"}?
Show answer
The sub-resource states the intent, creates a capture object that has its own ID, amount, status, and idempotency key, and lets the server enforce the state machine. It also supports partial and multiple captures. A PATCH on status lets clients ask for arbitrary transitions and carries no place for a capture amount or its own history.