Payments API Design
Last Updated: 2026-12-01 Status: Complete
Payments API design is mostly about making money operations explicit, retry-safe and hard to misuse. After this page you can model payments, refunds, payouts and disputes as resources, return errors that clients can act on, version without breaking integrations, and write a validated NestJS endpoint that is safe against the two most common API authorization flaws.
Quick Reference
| Topic | Recommendation |
|---|---|
| Resources | Payments, refunds, payouts, disputes; state changes as action endpoints |
| Money | Integer minor units plus ISO 4217 currency |
| Errors | RFC 9457 problem details for failed calls; a decline is a business outcome |
| Retries | Idempotency-Key on every POST that moves money |
| Versioning | Additive changes; major versions or date-pinned versions; documented deprecation |
| Lists | Cursor pagination |
| Limits | 429 with Retry-After |
| Async | 202 plus a status resource plus a webhook |
| Security | Object-level authorization on every request; whitelisted DTOs |
How Should You Model Resources?
| Resource | Notes |
|---|---|
payment (or payment intent) | The aggregate across authorization, capture and settlement |
refund | Child of a payment; cumulative refunds must not exceed the captured amount |
payout | Money to a merchant's bank account; see Payouts |
dispute | Created by the network, read-only to most clients, with evidence sub-resources |
Do not let clients set status directly. Expose state transitions as explicit action endpoints:
POST /v1/payments create
POST /v1/payments/{id}/capture authorized -> captured
POST /v1/payments/{id}/cancel authorized -> voided
POST /v1/payments/{id}/refunds create a refund
GET /v1/payments/{id} read
Each action is validated against the transition table in State Machines, so an invalid transition returns 409 instead of corrupting state. Return the full resource, including a status that includes the explicit unknown state for unresolved timeouts, consistent with Idempotency Key Implementation.
Money: send amount as an integer in minor units and currency as an ISO 4217 code, for example 4999 and USD. Exponents differ (JPY has 0 decimals, KWD has 3), so read them from the published list instead of assuming two.
Expandable references: return related objects as ids by default ("merchant": "mer_...") and let clients request expansion (?expand=merchant) to save round trips. Keep expansion depth bounded.
How Should Errors and Declines Be Reported?
Separate two things: the API call failed versus the call succeeded and the business outcome was negative.
| Convention | Behavior | Notes |
|---|---|---|
| Outcome in the body | 201 with status: "declined" and a decline object | The declined payment is a resource with an id, audit trail and events. Recommended. |
| Error status | Stripe documents HTTP 402 for requests that were valid but failed, such as card errors | Familiar to clients of that API. The decline is expressed as an error, so clients need error handling for a normal business event. |
Either works if you are consistent. A decline is expected business, not a fault, and it should never share a code path with a 500. Pick one and apply it to every endpoint.
For genuine API errors (4xx and 5xx) use RFC 9457 problem details:
{
"type": "https://api.example.com/problems/validation-error",
"title": "Invalid request",
"status": 422,
"detail": "amount must be an integer of at least 1",
"instance": "/v1/payments",
"errors": [{ "field": "amount", "code": "min" }],
"retryable": false
}
Decline codes. Do not expose raw network codes as your API contract. Return a normalized category that maps to network codes and merchant advice codes, plus a retryable signal. The mapping, categories and customer messages are in Response Codes. Keep the raw code in internal records for analysis; show clients the category and a safe message. Retry timing belongs to Retry Strategy.
Retry signals: distinguish retry-the-same-request (503, 429, timeouts, with the same idempotency key), fix-the-request (400, 422) and do-not-retry-this-card (a hard decline category). An unknown timeout is none of these; it is a state to resolve.
How Should You Version, Paginate and Rate Limit?
Versioning. Two common approaches:
| Approach | How | Trade-off |
|---|---|---|
| URL major versions | /v1/, /v2/ | Simple and visible. Clients must migrate to adopt changes. |
| Date-pinned versions | Each account has a default dated version that a request header can override; Stripe documents this model | Fine-grained compatibility. You must maintain transformation logic for old versions. |
In both, make additive changes (new optional fields, new endpoints, new enum values announced in advance) without a version bump, document that clients must ignore unknown fields, and run deprecations with notice, a sunset date and usage tracking per client.
Pagination. Use cursor pagination (?limit=50&starting_after=pay_...) rather than offsets: offsets skip or repeat rows when records are inserted, and are slow on deep pages. Sort by a stable key such as creation time plus id. Support filters such as created[gte], status and merchant_id, and index for them.
Rate limiting. Return 429 with a Retry-After header (RFC 6585 and RFC 9110), and apply limits per tenant and per endpoint class. See Access Control for where limits sit in the security design.
How Do You Handle Long-Running and Bulk Operations?
Long-running operations. If the work cannot finish within a normal request, return 202 Accepted with a status resource and finish with a webhook:
Bulk operations. Accept a list, return a result per item, and never fail the whole batch for one bad row. Give each item its own idempotency key so a retried batch does not repeat the items that already succeeded:
{
"results": [
{ "index": 0, "idempotency_key": "payout_mer1_USD_20261201", "status": 201, "id": "po_[example]" },
{ "index": 1, "idempotency_key": "payout_mer2_EUR_20261201", "status": 422, "error": { "type": "https://api.example.com/problems/validation-error" } }
]
}
The keys above follow the scheduled-payout form payout_{merchantId}_{currency}_{payoutDate}, which extends the blog's payout_{merchantId}_{date}_{sequence} with currency so a merchant's USD and EUR payouts on the same day do not collide. Manual or instant payouts use the caller's own request key.
Webhooks versus polling. Offer both: webhooks for timeliness (Webhook Delivery), GET for reconciliation and recovery. Webhooks can be missed or reordered, so clients should treat the API as the source of truth.
What Security Essentials Does Every Endpoint Need?
- Object-level authorization (OWASP API1, BOLA). Every request that takes an id must check that the authenticated tenant owns the object. Scope queries by
tenant_idin the repository, not only in the controller; a missing check leaks other merchants' payments. - Mass assignment (API3, Broken Object Property Level Authorization). Never bind request bodies straight onto entities. Whitelist properties in DTOs so a client cannot set
status,merchantIdorfee. - Resource consumption (API4): bounded page sizes, bounded metadata, request size limits.
- Authentication, tenant isolation and RBAC are covered in Access Control.
// main.ts
app.useGlobalPipes(new ValidationPipe({
whitelist: true, // strip unknown properties
forbidNonWhitelisted: true, // reject them instead (blocks mass assignment)
transform: true,
}));
NestJS Example: CreatePaymentDto and Controller
import { IsInt, IsISO4217CurrencyCode, IsObject, IsOptional, IsString, Length, Max, Min, Validate,
ValidatorConstraint, ValidatorConstraintInterface } from 'class-validator';
@ValidatorConstraint({ name: 'boundedMetadata' })
class BoundedMetadata implements ValidatorConstraintInterface {
validate(v: Record<string, unknown>): boolean {
const entries = Object.entries(v ?? {});
return entries.length <= 20 &&
entries.every(([k, val]) => k.length <= 40 && typeof val === 'string' && val.length <= 500);
}
defaultMessage(): string { return 'metadata allows up to 20 string entries (keys 40, values 500 characters)'; }
}
export class CreatePaymentDto {
@IsInt() @Min(1) @Max(Number.MAX_SAFE_INTEGER)
amount!: number; // minor units; also check against the currency's exponent and your own limits
@IsISO4217CurrencyCode()
currency!: string;
@IsString() @Length(1, 100)
paymentMethod!: string; // token from your vault, never a PAN
@IsOptional() @IsObject() @Validate(BoundedMetadata)
metadata?: Record<string, string>;
}
@Controller('v1/payments')
@UseGuards(AuthGuard, TenantGuard) // authentication and tenant resolution
export class PaymentsController {
constructor(private readonly payments: PaymentsService) {}
@Post()
@UseInterceptors(IdempotencyInterceptor) // see Idempotency Key Implementation
create(@Tenant() tenantId: string, @Body() dto: CreatePaymentDto) {
return this.payments.create(tenantId, dto);
}
@Post(':id/capture')
@HttpCode(200) // an action on an existing payment, not a create (default would be 201)
@UseInterceptors(IdempotencyInterceptor)
capture(@Tenant() tenantId: string, @Param('id') id: string) {
return this.payments.capture(tenantId, id); // repository query is scoped by tenantId (BOLA)
}
@Get(':id')
get(@Tenant() tenantId: string, @Param('id') id: string) {
return this.payments.findOneForTenant(tenantId, id);
}
}
The amount check matters because @IsInt() alone accepts integers beyond 2^53, which JavaScript numbers cannot represent exactly; validate the ceiling, and convert to bigint internally. Interceptors run before pipes in NestJS, so the idempotency layer must delete its key when validation fails; see Idempotency Key Implementation. The tenant comes from the authenticated principal, never from the request body or a client-supplied header. Never log request bodies that might contain tokens or personal data. Confirm your data classification with security leadership; see Sensitive Data.
Related Topics
- Idempotency Key Implementation — the key layer these endpoints use.
- Webhook Delivery and Signature Verification — how async results reach clients.
- Event-Driven Payment Architecture — events behind long-running operations.
- State Machines — the transition tables the action endpoints enforce.
- Check your understanding: Reliability Quiz
References
- RFC 9457: Problem Details for HTTP APIs — IETF, 2023
- RFC 9110: HTTP Semantics — IETF
- RFC 6585: Additional HTTP Status Codes — IETF, 2012 (429 Too Many Requests)
- OWASP API Security Top 10:2023 — OWASP
- Stripe API: Errors — Stripe docs (HTTP 402 convention)
- Stripe API: Versioning — Stripe docs (account-pinned versions)
- ISO 4217 data standards — SIX, maintenance agency