Most payment integrations I've reviewed have the same bug somewhere: a field name typed from memory. customerId instead of customerID, reference_id in one place and referenceID in another, a status compared against a string that the API never sends. JavaScript is happy to send all of those, and the API answers with a 400 or, worse, quietly ignores the field.
If the API publishes an OpenAPI spec, you can make the compiler catch those for you. This post does that for Coldtill, a self-hosted crypto payment gateway, whose merchant API is described in a single OpenAPI 3.1 file at coldtill.com/openapi.yaml. We'll generate types with openapi-typescript, call the API through openapi-fetch, and then look at the things a spec can't tell your compiler, which is where the real care goes.
Everything below was type-checked with TypeScript 5.9 in strict mode, using openapi-typescript 7.13 and openapi-fetch 0.17, and run against a small mock server on Node 24.
Why not just use the SDK?
Coldtill has a TypeScript SDK, @coldtill/sdk, with no dependencies, which wraps the endpoints and verifies webhooks. If that covers you, use it.
Generating from the spec is worth it when you already have your own HTTP layer (retries, tracing, a shared fetch wrapper) and want types for it, when you need the payout endpoints typed as well, or when you'd like the same file to drive Postman, a mock server and your client. The docs suggest importing it into "Postman, Insomnia or a client generator", and that's all we're doing.
Generate the types
npm i openapi-fetch npm i -D openapi-typescript typescript curl -fsSLo openapi/coldtill.yaml https://coldtill.com/openapi.yaml npx openapi-typescript openapi/coldtill.yaml -o src/coldtill.d.ts I keep a copy of the spec in the repo rather than generating from the URL on every build. The generated types then change only when you choose to update the file, and the diff of coldtill.yaml in that pull request tells you what changed in the API you depend on.
The output is one .d.ts file with three things you'll use: paths (every endpoint, keyed by path and method), components (the schemas) and webhooks. The spec describes the two webhook kinds too, payment and payout, so you get types for what arrives at your endpoint as well as for what you send.
A client in a dozen lines
import createClient, { type Middleware } from 'openapi-fetch' import type { paths, components } from './coldtill.js' type Schemas = components['schemas'] export type PaymentState = Schemas['PaymentState'] export type PaymentEvent = Schemas['PaymentEvent'] const auth: Middleware = { onRequest({ request }) { request.headers.set('API-Key', process.env.COLDTILL_API_KEY!) return request }, } export const ct = createClient<paths>({ baseUrl: process.env.COLDTILL_URL }) ct.use(auth) COLDTILL_URL is your own server, for example https://pay.example.com. If Coldtill runs under a path of another site, the path is part of the base URL (https://example.com/coldtill), and the spec's servers entry says the same. The key goes in an API-Key header from a middleware, so it's set in one place and never in front-end code.
Now the paths are checked. This fails to compile:
await ct.POST('/api/v1/payment', { body: { customerId: '42', amountInUSD: 10 } }) // error TS2561: ... 'customerId' does not exist in type '{ customerID: string; amountInUSD: string | number; ... }'. // Did you mean to write 'customerID'? await ct.GET('/api/v1/payment/{reference_id}', { params: { path: { reference_id: id } } }) // error TS2345: Argument of type '"/api/v1/payment/{reference_id}"' is not assignable to parameter of type 'PathsWithMethod<paths, "get">'. The second one is a real path mistake: getting a payment is /api/v1/payment/reference/{reference_id}.
Creating a payment
export async function startCheckout(order: { id: string; customerId: string; total: string }) { const { data, error, response } = await ct.POST('/api/v1/payment', { body: { customerID: order.customerId, amountInUSD: order.total, invoiceID: order.id }, }) if (response.status === 409) return { retryLater: true as const } if (error) throw new Error(`create payment: ${response.status} ${error.error}`) if (!data.reference_id || !data.url) throw new Error('create payment: incomplete response') return { referenceId: data.reference_id, url: data.url } } A few things the types guided here. amountInUSD is number | string in the request, so I pass the order total as a decimal string and never let it touch floating point. error is typed as the spec's Error schema, { error: string; code?: string }, which is what every non-2xx response carries.
The 409 gets its own branch because it isn't really an error. A customer has at most one open payment, and creating a new one replaces the old. But if the old one has a deposit still confirming, Coldtill refuses with 409 so that deposit isn't stranded. The right response is "try again in a few minutes", not a stack trace.
Reading a payment, and the first gap
const FINAL: PaymentState[] = ['FILLED', 'OVER_FILLED', 'CANCELLED', 'REPLACED'] export async function paymentStatus(referenceId: string) { const { data, error, response } = await ct.GET('/api/v1/payment/reference/{reference_id}', { params: { path: { reference_id: referenceId } }, }) if (error) throw new Error(`get payment: ${response.status} ${error.error}`) const state = data.paymentState if (!state) throw new Error('get payment: no paymentState') return { state, final: FINAL.includes(state), paid: state === 'FILLED' || state === 'OVER_FILLED' } } PaymentState comes out as a proper union: OPEN, PARTIALLY_FILLED, FILLED, OVER_FILLED, CANCELLED, REPLACED. Typo a state and the compiler tells you.
But look at data.paymentState. It's optional. The response schemas don't mark fields as required, so the generator makes every property ?:, and const s: string = data.paymentState won't compile. That's honest. The spec doesn't promise the field, so the type doesn't either. I'd rather narrow once, at the edge, with a clear error, than sprinkle ! through the codebase.
The other thing the union can't encode is meaning. The spec's description says FILLED is within 1% of the amount owed, OVER_FILLED is more than 1% above, and those two plus CANCELLED and REPLACED are final. Ship on FILLED or OVER_FILLED. A PARTIALLY_FILLED payment is still open, and the checkout asks the customer for the rest. That rule lives in your paid flag, not in the types.
Decimal strings stay strings
Amounts in responses are a Decimal schema: a string matching ^-?[0-9]+(\.[0-9]+)?$. The generator types that as string, which is exactly right. It doesn't stop you from calling Number() on it, though, and that's where a sum of payments drifts by a cent. If you need arithmetic, use integer minor units or a decimal library, and keep the string as the thing you store.
Not every field is camelCase
Most of the API is camelCase. One response isn't. Assigning a deposit address returns Address, Family and Status with capital letters:
export async function addressFor(referenceId: string, network: string) { const { data, error, response } = await ct.POST('/api/v1/deposit-address/reference/{reference_id}', { params: { path: { reference_id: referenceId } }, body: { blockchain_code: network }, }) if (response.status === 409) throw new Error(`no deposit wallet set up for ${network}`) if (error) throw new Error(`deposit address: ${response.status} ${error.error}`) return data.Address } Hand-written, this is the line where someone writes data.address and gets undefined in production. Generated, data.address is a compile error. The request body uses blockchain_code in snake_case, too, and a 409 here means the project has no deposit wallet for that network yet.
Payouts: headers are typed too
Payouts need a full-access key and an Idempotency-Key header. The spec marks the header as required, so the generated type does too:
export async function refund(to: string, amount: string, orderId: string) { const { data, error, response } = await ct.POST('/api/v1/withdrawal/merchant', { params: { header: { 'Idempotency-Key': `refund-${orderId}` } }, body: { blockchainCode: 'BASE', currencyCode: 'USDC', amount, toAddress: to }, }) if (error) throw new Error(`payout: ${response.status} ${error.code ?? ''} ${error.error}`) return data.status } Leave out params.header and it doesn't compile. The key should be derived from the thing you're paying for, like the order ID here, so a retry after a timeout returns the original payout instead of sending twice. Reusing a key with different parameters gets a 409.
When I ran this against a mock answering the way a payments-only key does, the error came through typed and readable: payout: 403 api_key_scope this API key can only create and read payments. That's the scope check doing its job. Shop code should hold a payments-only key, and payouts should run from somewhere else with a full-access key. Through the API they can only go to addresses already in the project's address book, and anything over the project's limits waits as pending-approval for an admin.
Payout.status is a union as well: pending-approval, pending-otp-verification, pending, signing, initiated, sent, failed, rejected, cancelled and needs-review. A switch over it with a never check in the default branch will flag a new status the day you update the spec.
Webhooks: types after verification, never before
The generated PaymentEvent type gives you reference_id, invoice_id, status, the decimal amounts, timestamp_ms and the deposit details in payment_info. It's tempting to JSON.parse the body and cast it straight away. Don't cast until you've checked the signature on the raw bytes. X-Coldtill-Signature-V2 is sha256= plus a hex HMAC-SHA256 of <timestamp>.<raw body> with the endpoint secret, and the spec says to reject a timestamp more than five minutes off:
import { createHmac, timingSafeEqual } from 'node:crypto' export function parsePaymentWebhook( raw: Buffer, headers: Record<string, string | undefined>, secret: string, ): PaymentEvent { const ts = headers['x-coldtill-timestamp'] ?? '' const sig = headers['x-coldtill-signature-v2'] ?? '' if (Math.abs(Date.now() / 1000 - Number(ts)) > 300) throw new Error('stale or missing timestamp') const expected = 'sha256=' + createHmac('sha256', secret).update(`${ts}.`).update(raw).digest('hex') const a = Buffer.from(sig) const b = Buffer.from(expected) if (a.length !== b.length || !timingSafeEqual(a, b)) throw new Error('bad signature') return JSON.parse(raw.toString('utf8')) as PaymentEvent // only now } A type is a claim about shape. Only the signature tells you who sent it.
The spec also says to decide from the signed status in the body, not from the X-Coldtill-Event header, and the webhooks page adds that ordering isn't guaranteed. So the handler that marks an order paid has to be idempotent and has to check that reference_id matches the one you saved for that order. No generator will write that check for you.
What the spec gives you, and what it doesn't
Worth separating, because it's easy to feel safer than you are once everything is green:
| The types catch | Still on you |
|---|---|
| Wrong paths and methods | Treating 409 on create as "retry later" |
| Misspelled request fields | Shipping only on FILLED / OVER_FILLED |
| Missing required headers | Deriving idempotency keys from the order |
| Unknown payment and payout states | Decimal maths without floats |
Address vs address | Verifying webhook signatures before parsing |
Error bodies as { error, code? } | Matching reference_id to the order |
The left column is where typos live. The right column is where money goes missing.
Pointing it at a real server
The mock is fine for the compiler, but you'll want a real server before you trust any of this. A testnet install is the cheap way, and the Free edition doesn't need an account: the Free edition's Docker image and binaries are on GitHub, with checksums and the install script (the source code itself isn't published there). Install in testnet mode, create a payments-only key, pay a test invoice with Base Sepolia USDC, and watch your typed client walk the payment through to FILLED.
When you later update the spec file in your repo, run the generator, run tsc, and read the diff. If it compiles and the diff is small, you've learned what changed before your customers did. The merchant API reference is the same spec rendered, if you'd rather read it than grep it.

