easyway
Log inGet started

Crypto payment API errors: what to retry and what to fix

Most integration bugs with a payment API are not in the happy path but in what the code does when a call fails. Retry the wrong error and you hammer the API for nothing; give up on the right one and a customer never gets a checkout link. This post sorts every error the easyway API returns into "retry" and "fix", explains how the Idempotency-Key makes retries safe, and ends with a small Node.js helper we ran against each case.

Read the code, not the text

An error is an HTTP status plus a short JSON body. Most bodies put a general class in error (bad_request, unauthorized, forbidden, not_found, conflict) and the specific code in message. The others, such as validation_error and rate_limited, put the code straight in error:

HTTP/1.1 401 Unauthorized
{ "error": "unauthorized", "message": "invalid_api_key" }

HTTP/1.1 400 Bad Request
{ "error": "validation_error", "fields": ["amount"] }

HTTP/1.1 429 Too Many Requests
Retry-After: 37
{ "error": "rate_limited" }

So the code to match is message when error is one of the five classes, and error otherwise. One trap: request bodies are strict, so a misspelled field such as amout is rejected too, but it shows up as validation_error with an empty fields list, because the field is unknown rather than wrong. When fields is empty, compare your field names with the docs.

Every error, sorted

StatusCodeWhat to do
429rate_limitedRetry after the Retry-After seconds. The budget is 300 requests per minute per key.
409request_in_progressRetry in a moment with the same Idempotency-Key: the first request with that key is still running.
503rate_unavailableRetry shortly: there is no fresh exchange rate for that non-stablecoin right now.
5xx / networkinternal_errorRetry with back-off (1 s, 2 s, 4 s…) and the same Idempotency-Key.
400validation_error, invalid_idempotency_key, unknown_asset, amount_too_small…Fix the request. Sending it again unchanged gives the same answer.
401 / 403invalid_api_key, missing_scope, ip_not_allowedFix the key or its settings in Dashboard → Developers. Alert someone; don't loop.
409no_wallets_configured, wallet_not_configuredA setup state, not a glitch: add your receiving wallet for that network in Dashboard → Wallets, then retry.
402plan_invoice_limit_reachedThe plan's monthly invoice allowance is used up. Upgrade the plan; retrying won't help.
409invoice_not_pending, invoice_expiredThe invoice can't change any more. Read it back and create a new one if needed.
422idempotency_key_reusedA bug: the same key was sent with a different body. Use one key per distinct request.

Why a retry can't create a second invoice

The endpoints that create something, POST /v1/invoices, POST /v1/refunds and POST /v1/subscriptions, accept an Idempotency-Key header of 8–128 letters, digits and _ - : .. The first request with a key runs and, if it succeeds, its response is stored; a retry with the same key and the same body gets that stored response back, marked with an Idempotent-Replayed: true header, instead of a second invoice, refund or subscription. A request that fails frees the key, so the retry runs for real. Two consequences:

Build the key from something stable such as the order id (order-2048), not from a timestamp or a random value made on each try. And never retry a POST without a key after a timeout: the first attempt may have worked. Look it up first with GET /v1/invoices?order_id=2048. If a key keeps returning request_in_progress, do the same lookup before you try anything new.

The helper

// easyway.mjs: one call() that knows which errors to retry. Node 18+, no packages.
const API = process.env.EASYWAY_API ?? "https://api.easyway.cash";
const CLASSES = ["bad_request", "unauthorized", "forbidden", "not_found", "conflict"];
const RETRY = new Set(["rate_limited", "request_in_progress", "rate_unavailable"]);
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));

export class EasywayError extends Error {
  constructor(status, code, fields) {
    super(`easyway ${status}: ${code}${fields?.length ? ` (${fields.join(", ")})` : ""}`);
    Object.assign(this, { status, code, fields });
  }
}

export async function call(method, path, body, idempotencyKey, attempts = 5) {
  for (let i = 1; ; i++) {
    let res, json;
    try {
      res = await fetch(API + path, {
        method,
        headers: {
          Authorization: `Bearer ${process.env.EASYWAY_API_KEY}`,
          "Content-Type": "application/json",
          ...(idempotencyKey && { "Idempotency-Key": idempotencyKey }),
        },
        body: body && JSON.stringify(body),
        signal: AbortSignal.timeout(15_000),
      });
      json = await res.json().catch(() => ({}));
    } catch (err) { // timeout or network: the request may or may not have run
      if (i >= attempts || (method === "POST" && !idempotencyKey)) throw err;
      await sleep(2 ** (i - 1) * 1000);
      continue;
    }
    if (res.ok) return json;

    const code = (CLASSES.includes(json.error) ? json.message : json.error) ?? `http_${res.status}`;
    const retryable = res.status >= 500 || RETRY.has(code);
    if (!retryable || i >= attempts) throw new EasywayError(res.status, code, json.fields);
    // 429 says how long to wait; otherwise back off 1 s, 2 s, 4 s, 8 s.
    const after = Number(res.headers.get("retry-after"));
    await sleep(after > 0 ? Math.min(after, 60) * 1000 : 2 ** (i - 1) * 1000);
  }
}

It retries only the four retryable cases, at most five attempts in all, honours Retry-After on a 429 (capped at 60 s), and throws the rest at once as an EasywayError with the specific code and, for validation errors, the fields. A network error on a POST without a key is thrown, not repeated. We ran it on Node 22 against a mock that answered 429, then 409, 503 and 500 in a row: it waited about one second after the 429, then 1, 2 and 4 seconds, and got the 201 with the same key every time. A 400, 401 or 422 came back in a few milliseconds.

import { call, EasywayError } from "./easyway.mjs";

try {
  const inv = await call("POST", "/v1/invoices", { amount: "149.00", currency: "USD", order_id: "2048" }, "order-2048");
  console.log(inv.payment_url);
} catch (err) {
  if (!(err instanceof EasywayError)) throw err; // still failing after 5 tries: show "try again later"
  if (err.code === "invalid_api_key") alertOps("rotate or fix EASYWAY_API_KEY");
  else console.error(err.message); // e.g. "easyway 400: validation_error (amount)"
}

Log err.status, err.code and the order id, never the API key. For the rest of the setup (the hosted checkout redirect and the signed webhook) see the Node.js guide, or the Python, PHP, Go and Java versions, which read the error code the same way. You can trigger most of these errors safely with an sk_test_… key in the sandbox.

Create free accountRead the API docsAlready have an account? Sign in
Crypto payment API errors: retry or fix? | easyway