easyway
Sign inCreate free account

A typed crypto payment API client in TypeScript

easyway publishes its merchant API as an OpenAPI 3.1 file at /openapi.json. From that file a TypeScript project can get exact types for every request and response, so a misspelled coin id, an amount sent as a number or a webhook event you forgot to handle fails the build instead of a payment. This post generates the types, wraps fetch in a small client and shows what the compiler catches. No SDK to install: the only extra package is a development tool.

1. Generate the types

openapi-typescript reads the spec and writes one .d.ts file: types only, nothing that ships in your bundle. Node 18 or later is enough, since the client uses the built-in fetch.

npm install --save-dev openapi-typescript typescript @types/node tsx
npx openapi-typescript https://easyway.cash/openapi.json -o easyway-api.d.ts

The generated file has a components["schemas"] entry for each object in the spec. These are the ones you will use:

SchemaWhat it types
InvoiceCreateThe body of POST /v1/invoices: amount, currency, order_id, allowed_assets, lifetime…
InvoiceEvery invoice response: status, pay_amount, pay_address, pay_memo, payment_url, expires_at…
AssetIdA union of every coin id the API accepts, such as "USDT_TRC20" or "BTC"
DecimalAmounts, which are strings, never numbers
ErrorThe error body: error, message, and fields for a validation_error
WebhookEventA webhook delivery: id, type, mode, created and data.invoice or data.payout
PayoutCreateThe body of POST /v1/payouts (see the payouts post)

A strict tsconfig.json that fits a script or a Node backend:

{
  "compilerOptions": { "target": "ES2022", "module": "ESNext", "moduleResolution": "Bundler", "strict": true, "noEmit": true, "types": ["node"] }
}

2. A small client

Two endpoints are enough for a shop: create an invoice and read it back. The wrapper adds the API key, the Idempotency-Key header (8 to 128 letters, digits or _-:.), a timeout, and turns an error response into an exception that carries the typed body:

import type { components } from "./easyway-api";

type InvoiceCreate = components["schemas"]["InvoiceCreate"];
type Invoice = components["schemas"]["Invoice"];
type ApiError = components["schemas"]["Error"];

const API = "https://api.easyway.cash";

export class EasywayError extends Error {
  constructor(public status: number, public body: ApiError) {
    // A general class (bad_request, unauthorized, …) carries the specific code in `message`.
    super(`easyway ${status}: ${body.message ?? body.error}`);
  }
}

async function call<T>(method: "GET" | "POST", path: string, body?: unknown, idempotencyKey?: string): Promise<T> {
  const res = await fetch(API + path, {
    method,
    headers: {
      Authorization: `Bearer ${process.env.EASYWAY_API_KEY}`,
      ...(body ? { "Content-Type": "application/json" } : {}),
      ...(idempotencyKey ? { "Idempotency-Key": idempotencyKey } : {}),
    },
    body: body ? JSON.stringify(body) : undefined,
    signal: AbortSignal.timeout(15_000),
  });
  const json = await res.json();
  if (!res.ok) throw new EasywayError(res.status, json as ApiError);
  return json as T;
}

export const createInvoice = (input: InvoiceCreate, idempotencyKey: string) =>
  call<Invoice>("POST", "/v1/invoices", input, idempotencyKey);

export const getInvoice = (id: string) => call<Invoice>("GET", `/v1/invoices/${encodeURIComponent(id)}`);

The error code to show is message when error is a general class such as unauthorized, which is how the spec describes it; the error codes post lists which ones are worth a retry.

3. Create an invoice

import { createInvoice, EasywayError } from "./easyway";

try {
  const invoice = await createInvoice(
    {
      amount: "49.00",
      currency: "USD",
      order_id: "7310",
      allowed_assets: ["USDT_TRC20", "USDT_BEP20", "USDC_SOL"],
      lifetime: 30,
    },
    "shop-order-7310",
  );
  console.log("redirect the customer to", invoice.payment_url);
} catch (err) {
  if (err instanceof EasywayError) console.error(err.message, err.body.fields ?? "");
  else throw err;
}

Run with a made-up key (EASYWAY_API_KEY=sk_test_x npx tsx order.ts), the script prints easyway 401: invalid_api_key, which shows the request reached the API and the error path works. With a real test key it prints the checkout URL. Redirect the customer there and wait for the webhook.

What the compiler catches

MistakeWhat tsc says
allowed_assets: ["USDC_SOLANA"]Type "USDC_SOLANA" is not assignable… Did you mean "USDC_SOL"?
amount: 49Type 'number' is not assignable to type 'string'
A webhook event type left out of a switchType "webhook.test" is not assignable to type 'never'

The coin id check matters most. Without types, a wrong id comes back as a 400 at run time, often only when a customer tries to pay. Amounts are strings because a JSON number cannot hold every coin amount exactly (the amounts post explains why). On the response side every field of an Invoice is always present, and a field without a value is null: pay_address is typed string | null because it is only set once the customer picks a coin, so the compiler makes you handle that case.

4. Type the webhook events

Verify the signature on the raw body first, as the webhook signature guide shows; only then parse it as a WebhookEvent. A switch with a never check makes the build fail if a regenerated spec adds an event type you don't handle yet:

import type { components } from "./easyway-api";

type WebhookEvent = components["schemas"]["WebhookEvent"];

// Call this only after the signature check passed (see the webhook signature guide).
export function handleEvent(event: WebhookEvent): void {
  switch (event.type) {
    case "invoice.paid":
      console.log("deliver order", event.data.invoice?.order_id);
      break;
    case "invoice.underpaid":
    case "invoice.expired":
    case "invoice.cancelled":
      console.log("do not deliver", event.data.invoice?.order_id);
      break;
    case "invoice.confirming":
    case "payout.sent":
    case "payout.failed":
    case "webhook.test":
      break;
    default: {
      const unhandled: never = event.type; // a new event type in a regenerated spec fails the build here
      console.warn("unknown event", unhandled);
    }
  }
}

Deliver only on invoice.paid, and store the event id to skip repeats: a delivery can arrive more than once (see webhook retries).

Keep the types current

AssetId is the coin list the spec was built from, and easyway adds coins over time. Run the generate command again when you want to offer a new coin, or in CI, and commit the result; a removed or renamed field then shows up as a compile error in your own code. The same spec imports into Postman or Insomnia, and the plain Node.js post covers the same flow without TypeScript.

Create free accountRead the API docsAlready have an account? Sign in
Typed crypto payment API client in TypeScript | easyway