Blog

Accept crypto payments in Node.js and Express

CoinStackUpdated 11 min read
Integrations

Accepting crypto payments in Node.js and Express takes two routes. The first loads an order, creates a CoinStack checkout with fetch and answers with a 303 redirect to the checkout page. The second receives the webhook with express.raw(), verifies the CoinStack-Signature header against the raw body, records the event_id so a retried delivery is skipped, and marks the order paid when the checkout is completed. The whole app below is about 170 lines in one file.

What you need before you start

The app uses Express 5 and node:sqlite, the SQLite module built into Node.js. That module needs Node.js 22.13 or later, the release where the Node.js docs say it stopped needing the --experimental-sqlite flag. We ran this code on Node.js 26.0 with Express 5.3 in December 2026, posting signed sample events to the webhook route. SQLite keeps the example to one file you can run; the patterns carry over to PostgreSQL or MySQL unchanged.

From CoinStack you need two values from the dashboard's Developers page: an API key with Read and write access (it starts with sk_) and, after you add a webhook, its signing secret (it starts with whsec_). Both are shown once. If you have not made an API call yet, the crypto payments API quickstart explains each field of a checkout; this tutorial assumes you know what a checkout is and focuses on the Express code.

Set up the project

mkdir crypto-shop && cd crypto-shop
npm init -y
npm pkg set type=module
npm install express@5

Create .env next to it. BASE_URL is the public address of your app, used for the return links on the checkout page:

COINSTACK_API_KEY=sk_your_key
COINSTACK_WEBHOOK_SECRET=whsec_your_secret
BASE_URL=https://shop.example.com

The code below goes into server.js, top to bottom in the order shown. Start it with node --env-file=.env server.js, which loads the variables without a dotenv package.

Store orders, checkouts and handled events

import crypto from "node:crypto";
import { DatabaseSync } from "node:sqlite";
import express from "express";

const API = "https://coinstack.net/api/v1";
const apiKey = process.env.COINSTACK_API_KEY;
const secret = process.env.COINSTACK_WEBHOOK_SECRET;
const baseUrl = process.env.BASE_URL;

const db = new DatabaseSync("shop.db");

db.exec(`
  CREATE TABLE IF NOT EXISTS orders (
    id INTEGER PRIMARY KEY,
    amount TEXT NOT NULL,
    currency TEXT NOT NULL,
    status TEXT NOT NULL DEFAULT 'unpaid',
    paid_at TEXT
  );
  CREATE TABLE IF NOT EXISTS checkouts (
    checkout_id TEXT PRIMARY KEY,
    order_id INTEGER NOT NULL REFERENCES orders (id),
    url TEXT NOT NULL,
    created_at TEXT NOT NULL
  );
  CREATE TABLE IF NOT EXISTS webhook_events (
    event_id TEXT PRIMARY KEY,
    kind TEXT NOT NULL,
    received_at TEXT NOT NULL
  );
`);

Checkouts get their own table instead of a column on orders because one order can end up with several. A customer opens the checkout, lets it expire overnight, and comes back the next day for a fresh one. If they then pay the old address as well, that payment must still find its order. Amounts are stored as text because the API sends and expects strings, which avoids floating-point surprises on values like "19.99".

Node.js 26.11 renamed the class to Database and keeps DatabaseSync as an alias, according to the deprecation notes. The older name is used here because it works on every version from 22.13.

Call the API from one helper

async function coinstack(method, path, body) {
  const response = await fetch(`${API}${path}`, {
    method,
    headers: {
      Authorization: `Bearer ${apiKey}`,
      "Content-Type": "application/json",
    },
    body: body ? JSON.stringify(body) : undefined,
    signal: AbortSignal.timeout(30_000),
  });
  const result = await response.json();

  if (!result.success) {
    throw new Error(`CoinStack ${response.status}: ${result.response}`);
  }

  return result.response;
}

const app = express();

Every CoinStack response is {"success": true, "response": {...}} or {"success": false, "response": "message"}, so one helper can unwrap all of them and throw on failure. The 30-second limit matches the timeout the docs' Python and PHP examples use. Without a signal, a hung connection would hold the customer's request open far longer.

Create the checkout and redirect the customer

app.post("/orders/:id/pay", async (request, response) => {
  const order = db
    .prepare("SELECT * FROM orders WHERE id = ?")
    .get(Number(request.params.id));

  if (!order) return response.sendStatus(404);
  if (order.status === "paid") return response.redirect(303, `/orders/${order.id}`);

  // Reuse the newest checkout if it is still open for at least 10 minutes.
  const last = db
    .prepare("SELECT * FROM checkouts WHERE order_id = ? ORDER BY created_at DESC LIMIT 1")
    .get(order.id);

  if (last) {
    const { checkout } = await coinstack("GET", `/checkouts/${last.checkout_id}`);
    const open = ["pending", "confirming", "partial"].includes(checkout.status);
    const minutesLeft = (Date.parse(checkout.expires_at) - Date.now()) / 60_000;

    if (open && minutesLeft > 10) return response.redirect(303, checkout.url);
  }

  const { checkout } = await coinstack("POST", "/checkouts", {
    amount: order.amount,
    currency: order.currency,
    reference: `order-${order.id}`,
    description: `Order #${order.id}`,
    success_url: `${baseUrl}/orders/${order.id}`,
    cancel_url: `${baseUrl}/cart`,
    metadata: { order_id: String(order.id) },
  });

  db.prepare("INSERT INTO checkouts (checkout_id, order_id, url, created_at) VALUES (?, ?, ?, ?)")
    .run(checkout.checkout_id, order.id, checkout.url, new Date().toISOString());

  response.redirect(303, checkout.url);
});

The amount comes from your database, never from the request, so a customer cannot edit the form and pay $1 for a $100 order. The reuse block handles the customer who clicks Pay twice or presses Back: instead of a second checkout with a second address, they land on the one they already opened. It only reuses a checkout with more than 10 minutes left, so nobody starts paying a page that is about to close.

Express 5 passes a rejected promise from an async handler to its error handler, so a failed API call becomes a 500 instead of a hung request. On Express 4 you would wrap the body in try/catch and call next(error). The 303 status tells the browser to follow the redirect with a GET, which is what you want after a form POST.

Receive the webhook on the raw body

The signature is computed over the exact bytes CoinStack sent. If anything parses the JSON first, those bytes are gone, and in Express this happens without any error:

  • app.use(express.json()) near the top of the file parses every JSON request before your route runs. In Express 5.3, the route's express.raw() then receives the parsed object, not a Buffer.
  • The fix is to give the webhook route its own express.raw({ type: "application/json" }) and to register it before any global JSON parser, or to exclude its path from that parser.

This app has no global parser, so the route below works as written. The handler also checks that request.body really is a Buffer. In Express 5, a request whose Content-Type does not match leaves request.body undefined, and the check turns that into a clean 400 instead of a crash.

Verify the CoinStack-Signature header

function verify(header, body) {
  const parts = Object.fromEntries(
    String(header).split(",").map((part) => part.split("=")),
  );
  const expected = Buffer.from(
    crypto.createHmac("sha256", secret).update(`${parts.t}.${body}`).digest("hex"),
  );
  const given = Buffer.from(String(parts.v1));

  return (
    given.length === expected.length &&
    crypto.timingSafeEqual(given, expected) &&
    Math.abs(Date.now() / 1000 - Number(parts.t)) <= 300
  );
}

This function is copied from the webhooks guide. The header looks like t=1796228678,v1=0e64.... The function joins t, a full stop and the body, computes an HMAC-SHA256 with your signing secret, and compares the hex result with v1. The length check comes first because crypto.timingSafeEqual throws when the two buffers differ in length. The constant-time comparison stops an attacker from guessing a valid signature one character at a time from response timings, and the 300-second window means a captured request cannot be replayed later. Use the whole secret, whsec_ prefix included.

Handle each event exactly once

function applyCheckout(checkout) {
  const known = db
    .prepare("SELECT order_id FROM checkouts WHERE checkout_id = ?")
    .get(checkout.checkout_id);

  if (!known) return; // Not a checkout this app created, such as the dashboard test event.

  if (checkout.status === "completed" || checkout.status === "resolved") {
    db.prepare("UPDATE orders SET status = 'paid', paid_at = ? WHERE id = ? AND status <> 'paid'")
      .run(new Date().toISOString(), known.order_id);
  }
}

app.post(
  "/webhooks/coinstack",
  express.raw({ type: "application/json" }),
  (request, response) => {
    const body = Buffer.isBuffer(request.body) ? request.body.toString("utf8") : "";

    if (!verify(request.get("CoinStack-Signature"), body)) {
      return response.status(400).send("Invalid signature");
    }

    const event = JSON.parse(body);

    db.exec("BEGIN IMMEDIATE");

    try {
      const inserted = db
        .prepare("INSERT INTO webhook_events (event_id, kind, received_at) VALUES (?, ?, ?) ON CONFLICT DO NOTHING")
        .run(event.event_id, event.kind, new Date().toISOString());

      if (inserted.changes === 1 && event.kind.startsWith("checkout.")) {
        applyCheckout(event.data.checkout);
      }

      db.exec("COMMIT");
    } catch (error) {
      db.exec("ROLLBACK");
      throw error;
    }

    response.sendStatus(200);
  },
);

CoinStack can deliver the same event more than once, and event_id stays the same across retries and resends. The INSERT ... ON CONFLICT DO NOTHING reports one changed row the first time an ID is seen and zero after that, so a duplicate is acknowledged with a 200 and nothing else happens.

The event row and the order update share one transaction. If applyCheckout throws, the rollback removes the event row too, Express answers 500, and the delivery counts as failed. CoinStack then retries after 1 minute, 5 minutes, 30 minutes, 2 hours, 5 hours, 8 hours and 8 hours, and the retry finds no stored ID and runs the work again. Recording the ID outside the transaction would mark the event handled even though the order never changed.

Answer within 10 seconds. This handler does two small SQLite writes, so it is fast. If yours sends emails or provisions servers, save the event, respond, and do the slow part in a background job. Reliable payment webhooks covers queues and replays in more depth.

Mark the order paid in any delivery order

Events can arrive out of order: a retried checkout.confirming can land after checkout.completed. applyCheckout is safe against that because it only ever moves an order forward. It ignores every status except completed and resolved, and its UPDATE touches only orders that are not paid yet. A late confirming or an expired event changes nothing. The known lookup rejects checkouts this app did not create, including the sample event that Send test in the dashboard sends.

Three situations need a decision from you rather than more code:

EventFlagWhat it means for this shop
checkout.completedlatePaid in full after expires_at. If your shop cancels unpaid orders at expiry, fulfill anyway or refund
checkout.completedoverpaidMore than 2% over. All of it is in your wallet; refund the difference if you choose to
checkout.expiredunderpaidPart of the amount arrived, then the checkout closed. Resolve it or refund

resolved is what you get when you accept an underpayment with Mark as resolved in the dashboard, which is why the handler treats it as paid. Underpaid crypto payments explains when that is the right call.

Show the order and start the server

app.get("/orders/:id", (request, response) => {
  const order = db
    .prepare("SELECT id, status FROM orders WHERE id = ?")
    .get(Number(request.params.id));

  if (!order) return response.sendStatus(404);

  response.send(
    order.status === "paid"
      ? `Order #${order.id} is paid. Thank you.`
      : `Order #${order.id} is waiting for your payment to confirm. Refresh in a minute.`,
  );
});

app.listen(3000, () => console.log("Listening on http://localhost:3000"));

This is the page success_url points to. The customer can arrive here a moment before the webhook does, so the page says "waiting" rather than "failed". The webhook, not this page, is what marks the order paid.

Run it end to end

  1. Start the app and add a test order. With the sqlite3 command-line tool: sqlite3 shop.db "INSERT INTO orders (amount, currency) VALUES ('1.00', 'USD');".
  2. Expose port 3000 over HTTPS with a tunnel, because CoinStack only delivers to https:// URLs with a domain name.
  3. In Developers, add a webhook for https://your-tunnel-domain/webhooks/coinstack. Put its secret in .env, set BASE_URL to the tunnel address so the return links work, and restart the app.
  4. Select Send test on the webhook. The app should answer 200, and no order should change.
  5. Send curl -i -X POST http://localhost:3000/orders/1/pay and open the Location URL it returns. Pay the $1 checkout from a wallet, then load /orders/1.

Keep test orders at the $1 minimum: a real $1 payment exercises the checkout page, settlement to your wallet and the webhook for about a dollar. Test with a stablecoin such as USDC on Base. How to test a crypto checkout lists what else to try before launch, such as an underpayment and a payment after expiry.

What to change before production

Check that the signed-in customer owns the order in the pay route; this example lets anyone pay any order ID, which is harmless here but wrong in a real shop. Move the tables into your main database: in PostgreSQL the same idempotency is a primary key on event_id and the same ON CONFLICT DO NOTHING. Add a scheduled job that calls GET /checkouts/{checkout_id} for orders still unpaid after an hour, so a webhook lost to an outage on your side is caught; reconciling crypto payments describes that check. Keep the API key and webhook secret out of your repository, and rotate the secret from the dashboard if it leaks.

Frequently asked questions

Why does my signature check fail on every request?

Usually because the body was parsed before the check. A global express.json() registered above the webhook route turns the body into an object, so the HMAC is computed over the wrong bytes. Other causes: a signing secret copied without its whsec_ prefix, a secret from a different webhook, or a proxy in front of the app that rewrites the body. Use Send test to try each fix.

Can I use Express 4 instead of Express 5?

Yes. express.raw() and the webhook handler work the same on Express 4.17 and later. The difference is error handling in async routes: Express 4 does not catch a rejected promise, so wrap the pay route in try/catch and pass errors to next. Without that, a failed API call leaves the customer's request hanging.

Should I trust the checkout inside the event or fetch it again?

For marking an order paid, the event's own data.checkout is enough once the signature is verified, because this handler acts only on completed and resolved and never moves an order backward. If you build logic that depends on the latest state, such as showing a partial amount, call GET /checkouts/{checkout_id} when the event arrives and use its current status.

Does this work with TypeScript, Fastify or NestJS?

The CoinStack side is identical: a fetch call to create the checkout and an HMAC check on the raw body. What changes is how each framework gives you that body. Fastify and NestJS parse JSON by default, so you configure a raw-body option for the webhook route. For an App Router project, the Next.js tutorial shows the equivalent route handler.

More posts