---
title: Accept crypto in a Node.js app
description: A complete Node.js integration: sign merchant requests with HMAC-SHA256, create an order, redirect the player, and verify webhook signatures before delivering.
url: https://gaapay.com/integrations/node
updated: 2026-12-04
language: en
type: guide
---

# Accept crypto in a Node.js app

> Two functions cover the whole loop: `createOrder()` signs a POST with HMAC-SHA256, and `verifyWebhook()` checks timestamp + raw body before you parse it. Keep the secret in an environment variable; never expose it to the client.

Node 18+ has `fetch` and `node:crypto`, so there is no SDK to install and no dependency to audit. The signature is a hex HMAC over five newline-joined fields — the order is fixed, and the body must be the **exact bytes** you send.

## 1 · Create an order

```mjs
import { createHmac, randomUUID } from 'node:crypto';

export async function createOrder({ amount, ref, description }) {
  const path = '/api/v1/orders';
  const raw = JSON.stringify({
    amount: amount.toFixed(2),
    merchant_order_ref: ref,
    description,
  });
  const ts = Math.floor(Date.now() / 1000);
  const nonce = randomUUID();
  const payload = [ts, nonce, 'POST', path, raw].join('\n');
  const signature = createHmac('sha256', process.env.GAAPAY_SECRET)
    .update(payload).digest('hex');

  const res = await fetch(`https://api.gaapay.com${path}`, {
    method: 'POST',
    headers: {
      'content-type': 'application/json',
      'x-gaapay-app': process.env.GAAPAY_APP,
      'x-gaapay-timestamp': String(ts),
      'x-gaapay-nonce': nonce,
      'x-gaapay-signature': signature,
    },
    body: raw,
  });
  if (!res.ok) throw new Error(`GaaPay ${res.status}: ${await res.text()}`);
  return res.json(); // { id, checkout_url, ... }
}
```

`merchant_order_ref` is unique per app and doubles as the idempotency key. A retry after a timeout returns the same order instead of charging twice — do not generate a new ref on retry.

## 2 · Verify the webhook before parsing

```mjs
import { createHmac, timingSafeEqual } from 'node:crypto';

export function verifyWebhook(req) {
  const ts = req.headers["x-gaapay-timestamp"];
  const signature = req.headers["x-gaapay-signature"] || "";
  if (Math.abs(Date.now() / 1000 - Number(ts)) > 300) return false;
  const expected = "v1=" + createHmac("sha256", process.env.GAAPAY_WEBHOOK_SECRET)
    .update(`${ts}.${req.rawBody}`).digest("hex");
  const a = Buffer.from(expected);
  const b = Buffer.from(signature);
  return a.length === b.length && timingSafeEqual(a, b);
}

app.post("/webhooks/gaapay", express.raw({ type: "application/json" }), (req, res) => {
  if (!verifyWebhook(req)) return res.status(401).send("bad signature");
  const event = JSON.parse(req.rawBody);
  if (event.type === "payment.succeeded") fulfil(event.data.order_id);
  res.status(200).send("ok"); // 2xx only after the work is durable
});
```

> **Use the raw body:** — Express’s `json()` parser re-serializes and changes key order, which breaks the HMAC. Mount `express.raw()` on this route only, or use `verify` to capture the buffer.

## 3 · Before you ship

- Return 2xx only after the delivery is durable — a 200 followed by a crash loses the event.
- Deduplicate by `x-gaapay-event-id`; delivery is at-least-once.
- Use `merchant_order_ref` as your primary key for the order, not the GaaPay id.
- Log `request_id` from API errors; it is the only handle support needs.

## Node questions

### Do I need the SDK?

No. The API is three headers and an HMAC; a 20-line module is easier to audit than a dependency tree.

### How do I handle retries from GaaPay?

Your endpoint must be idempotent by `event_id`. If you already processed it, return 2xx again — do not do the work twice.

### Where do I keep the secret?

In the server environment (or a secret manager). A secret in a browser bundle, a mobile binary or a git history is already leaked.

[Get sandbox keys](/console) — **Run this against the sandbox**: The sandbox accepts the same signatures and returns deterministic test outcomes.

## Related

- https://gaapay.com/docs/auth
- https://gaapay.com/docs/verify
- https://gaapay.com/docs/api
- https://gaapay.com/integrations/python
