A crypto payment API in Node.js with no dependencies
The Node examples in the easyway docs use Express. Since Node 18 you don't need it, or any other package: fetch creates the invoice, node:http receives the webhook and node:crypto checks its signature. This post shows two files that do the whole job with no npm install, and the Node-specific traps on the way. We ran both on Node 22.
What the two files do
| File | Job | Built-in modules |
|---|---|---|
easyway.mjs | POST /v1/invoices and return the invoice, whose payment_url you redirect the customer to; GET one invoice back. | fetch, AbortSignal |
webhook.mjs | Receive the signed invoice.paid delivery, check it, and mark the order paid. | node:http, node:crypto |
Between the two, the customer pays on the hosted checkout: they pick a coin and network, see the amount and a QR code, and the page follows the payment by itself. Create the API key in Dashboard → Developers with the invoices:write and invoices:read scopes; it needs nothing else. An sk_test_… key only touches sandbox data. Before going live, set your receiving wallet for each network you accept (Dashboard → Wallets): payments go straight to it, and without one a live invoice is refused with 409 no_wallets_configured or wallet_not_configured.
1. Create the invoice with fetch
// easyway.mjs: no npm install. Node 18+ (built-in fetch).
const API = process.env.EASYWAY_API ?? "https://api.easyway.cash";
const CLASSES = ["bad_request", "unauthorized", "forbidden", "not_found", "conflict"];
export class EasywayError extends Error {
constructor(status, code) {
super(`easyway ${status}: ${code}`);
this.status = status;
this.code = code;
}
}
async function call(method, path, body, idempotencyKey) {
const 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), // fetch has no timeout of its own
});
const json = await res.json().catch(() => ({}));
if (!res.ok) { // fetch does not throw on 4xx/5xx
throw new EasywayError(res.status, (CLASSES.includes(json.error) ? json.message : json.error) ?? "unknown_error");
}
return json;
}
// Money as integer cents in your code, a decimal string on the wire: 14900 → "149.00".
const usd = (cents) => `${Math.trunc(cents / 100)}.${String(cents % 100).padStart(2, "0")}`;
export function createInvoice(orderId, totalCents) {
return call("POST", "/v1/invoices", {
amount: usd(totalCents),
currency: "USD",
order_id: orderId,
description: `Order #${orderId}`,
success_url: `https://shop.example.com/thanks?order=${encodeURIComponent(orderId)}`,
cancel_url: "https://shop.example.com/cart",
}, `order-${orderId}`); // a retry returns the same invoice
}
export const getInvoice = (id) => call("GET", `/v1/invoices/${encodeURIComponent(id)}`);| Detail | Why |
|---|---|
| Cents → decimal string | The API takes amounts as strings such as "149.00". JavaScript numbers are floats (0.1 + 0.2 is 0.30000000000000004), so keep money as integer cents and format it at the edge. usd(905) gives "9.05". |
| Idempotency-Key | Built from the order id, so a retry after a timeout returns the same invoice instead of a second one. 8–128 characters: letters, digits, _ - : . |
AbortSignal.timeout | fetch waits as long as the connection stays open. The signal aborts it after 15 seconds with a TimeoutError. |
res.ok | fetch only rejects on network errors; a 401 or 422 resolves normally. Check res.ok and read the JSON body yourself. |
CLASSES | Most errors put a general class in error and the specific code in message, e.g. {"error": "unauthorized", "message": "invalid_api_key"}. The helper keeps the specific one in err.code; the errors section of the docs has the rule, and which errors to retry adds back-off. |
import { createInvoice } from "./easyway.mjs";
const invoice = await createInvoice("2048", 14900); // order id and total in cents from your database
// save invoice.id with the order, then redirect the customer (303) to:
console.log(invoice.payment_url);A rejected call with a TimeoutError or TypeError: fetch failed can simply be repeated with the same order id; the Idempotency-Key makes that safe. An answer with a code, such as 402 plan_invoice_limit_reached, is not something to retry blindly. Once the customer has picked a coin, the invoice's pay_amount is what they must send; on networks where invoices share one address it can be a hair above your price (e.g. 149.001 USDT), so show it as returned. To bill in a coin instead of USD, set currency to an asset id such as "USDT_TRC20" (see pricing in USD or in the coin); to show only some coins, add allowed_assets (see limiting the checkout).
2. Verify the webhook with node:crypto
Each delivery carries X-Webhook-Signature: t=…,v1=…, where v1 is the lower-case hex HMAC-SHA256 of t + "." + raw body under the endpoint's signing secret.
// webhook.mjs: Dashboard → Developers → Webhooks points here. No Express needed.
import { createServer } from "node:http";
import { createHmac, timingSafeEqual } from "node:crypto";
import { getInvoice } from "./easyway.mjs";
const SECRET = process.env.EASYWAY_WEBHOOK_SECRET;
function verify(header, raw) {
const parts = Object.fromEntries(header.split(",").map((p) => p.split("=", 2)));
const t = parts.t ?? "", v1 = parts.v1 ?? "";
if (!/^\d{1,12}$/.test(t) || Math.abs(Date.now() / 1000 - Number(t)) > 300) return false;
const expected = Buffer.from(createHmac("sha256", SECRET).update(`${t}.`).update(raw).digest("hex"));
const given = Buffer.from(v1);
return given.length === expected.length && timingSafeEqual(given, expected); // unequal lengths would throw
}
async function readRaw(req, limit = 1_000_000) {
const chunks = [];
let size = 0;
for await (const c of req) {
size += c.length;
if (size > limit) throw new Error("body too large");
chunks.push(c);
}
return Buffer.concat(chunks); // the RAW bytes are what was signed
}
createServer(async (req, res) => {
try {
const raw = await readRaw(req);
if (req.method !== "POST" || !verify(String(req.headers["x-webhook-signature"] ?? ""), raw)) {
res.writeHead(400).end();
return;
}
const event = JSON.parse(raw.toString("utf8"));
// Store event.id and skip repeats: deliveries are retried until you answer 2xx.
if (event.type === "invoice.paid") {
const inv = await getInvoice(event.data.invoice.id); // optional: re-read it with your own key
if (inv.status === "paid") console.log("order", inv.order_id, "paid:", inv.received_amount, inv.pay_asset);
// await markOrderPaid(inv.order_id, inv.id, inv.received_amount, inv.pay_asset);
}
res.writeHead(200).end();
} catch (err) {
console.error(err);
res.writeHead(500).end(); // easyway retries later
}
}).listen(8000, "127.0.0.1");We sent deliveries signed that way to this server. The genuine one got 200, the invoice was read back and the order printed. A changed body, a timestamp 400 seconds old, another secret, a missing or malformed header, a short v1, a non-ASCII v1 and a non-ASCII digit in t all got 400.
| Pitfall | Fix |
|---|---|
timingSafeEqual | It throws a RangeError when the two buffers differ in length, so a short v1 would turn into a 500. Compare the lengths first. |
Buffer.from(v1, "hex") | Silently drops everything from the first non-hex character. Compare the hex strings as UTF-8 bytes, as above, instead of decoding them. |
express.json() | Parses the body before your handler sees it; re-serialised JSON is not byte-identical. In Express, use express.raw({ type: "application/json" }) on this route, as the webhook signature guide does. |
| Duplicates | Deliveries are retried until you answer 2xx; store the event id and skip repeats. |
| Slow handler | Answer within 10 seconds. Send e-mails and licence keys from a queue, not before the response. |
Reading the invoice back with getInvoice is optional, since the signature already proves who sent the event. It costs one request and means the order is marked paid from what your own API key sees, which is a cheap extra check when the handler also ships goods. Behind a reverse proxy with HTTPS, node:http is enough for production; in Fastify or Next.js route handlers, keep verify() and pass it the raw body (await request.text() in a Next.js route).
Test it end to end
Set EASYWAY_API_KEY to a test key and EASYWAY_WEBHOOK_SECRET to the endpoint's secret, start node webhook.mjs behind a tunnel, and add the tunnel URL in Dashboard → Developers → Webhooks. Then create an invoice, open its payment_url and press Simulate payment: the real payment-processing code runs and a real invoice.paid delivery reaches your server. The sandbox guide covers underpaid and expired cases too.
Errors worth a branch
| Status | Code | What to do |
|---|---|---|
| 400 | validation_error | A field is missing or malformed; fields says which. |
| 401 | invalid_api_key | Wrong, revoked or test-vs-live key. |
| 402 | plan_invoice_limit_reached | Your plan's monthly live-invoice allowance is used up. Do not retry: upgrade the plan or wait for the next month. |
| 409 | no_wallets_configured | Live mode with no receiving wallet set (wallet_not_configured: none for that coin's network). Add it under Wallets; retrying will not help. |
| 409 | request_in_progress | The same Idempotency-Key is still running: retry shortly. |
| 422 | idempotency_key_reused | Same key, different body: a new order needs a new key. |
| 429 | rate_limited | Over 300 requests per minute on the key: back off and retry. |
Branch on err.code, never on other text. There is no fee per payment: the money arrives in your own wallet in full, and the service is priced by plan, from a free plan up (see pricing). The same integration in other languages: Python, PHP, Go and Java; every endpoint is in the API docs, and the crypto payment API overview sums up what it covers.