Skip to content

Lesson 3 of 5 · 10 min

Receive signed actions on your server

Build a minimal Node.js server that receives a brain's actions, verifies the HMAC signature and never processes the same Zunous delivery twice.

With a custom action, the brain calls one of your webhooks to act in your systems: record a payment, create an order, look up a balance. In this lesson you write that webhook in Node.js, with no dependencies, with the two protections that must never be missing: verifying the signature and not processing the same delivery twice.

What you'll achieve

  • Understand what Zunous sends and how it's signed.
  • Write a server that verifies the HMAC signature and is idempotent by Zunous-Delivery.
  • Test it on your machine by signing a call yourself.

What arrives

An admin creates the action in the Console (Autonomous Mode → Custom actions → New action) with your URL and gives you the signing secret (whsec_…), which is shown only once. Each call is a POST with JSON:

json
{
  "accion": "registrar_pago",
  "organizacion": "acme",
  "brain": "cobranza",
  "ejecucion": "7b1e…",
  "aprobada_por": "ana@acme.com",
  "datos": { "factura": "FV-1023", "valor": 1200000 }
}

And these headers: Zunous-Event (for example accion.registrar_pago), Zunous-Delivery (the delivery ID), Zunous-Timestamp (seconds) and Zunous-Signature (v1= plus an HMAC-SHA256 in hexadecimal).

The signature is computed over the text <timestamp>.<raw body>, with the full secret as the key, including the whsec_ prefix. On Send test calls, the body also includes "prueba": true. The full format is in Webhook actions.

The server

javascript
import http from "node:http";
import crypto from "node:crypto";

const SECRETO = process.env.ZUNOUS_WHSEC; // whsec_…, never in the code
const entregas = new Map(); // Zunous-Delivery → promise of the result. In production, use your database.

function firmaValida(cuerpo, ts, firma) {
  if (!/^\d+$/.test(ts ?? "") || Math.abs(Date.now() / 1000 - Number(ts)) > 300) return false;
  const esperada = "v1=" + crypto.createHmac("sha256", SECRETO).update(`${ts}.${cuerpo}`).digest("hex");
  return typeof firma === "string" && firma.length === esperada.length &&
    crypto.timingSafeEqual(Buffer.from(firma), Buffer.from(esperada));
}

async function procesar(cuerpo) {
  const llamada = JSON.parse(cuerpo);
  if (llamada.prueba) return { codigo: 200, resultado: "Test received; nothing was recorded." };
  if (llamada.accion !== "registrar_pago") return { codigo: 400, resultado: `I don't know the action ${llamada.accion}.` };
  const { factura, valor } = llamada.datos ?? {};
  if (!factura || !(valor > 0)) return { codigo: 400, resultado: "The invoice or the amount is missing." };
  const recibo = await registrarPagoEnTuSistema(factura, valor, llamada.aprobada_por);
  return { codigo: 200, resultado: `Payment of ${valor} recorded on ${factura}. Receipt ${recibo}.` };
}

async function registrarPagoEnTuSistema(factura, valor, aprobadaPor) {
  // Your ERP or your database goes here.
  return "RC-" + Date.now();
}

http.createServer((req, res) => {
  const responder = (codigo, resultado) => {
    res.writeHead(codigo, { "Content-Type": "application/json" });
    res.end(JSON.stringify({ resultado }));
  };
  if (req.method !== "POST" || req.url !== "/zunous/acciones") return responder(404, "Route not found.");

  const partes = [];
  req.on("data", (p) => partes.push(p));
  req.on("end", async () => {
    const cuerpo = Buffer.concat(partes).toString("utf8"); // the raw body, never re-serialized
    if (!firmaValida(cuerpo, req.headers["zunous-timestamp"], req.headers["zunous-signature"])) {
      return responder(401, "Invalid signature.");
    }
    const entrega = req.headers["zunous-delivery"];
    if (!entregas.has(entrega)) entregas.set(entrega, procesar(cuerpo));
    try {
      const { codigo, resultado } = await entregas.get(entrega);
      responder(codigo, resultado);
    } catch (err) {
      entregas.delete(entrega); // it really failed: let the retry try again
      responder(500, "Internal error.");
    }
  });
}).listen(3000, () => console.log("Listening on port 3000"));

What each part does:

  • Signature and time: rejects the call if the signature doesn't match (compared in constant time) or if the timestamp is more than 5 minutes old.
  • Idempotency: stores the promise for each Zunous-Delivery. If a retry arrives, even while the first call is still in progress, it gets the same result and the payment isn't recorded twice. In production, store the ID in your database with a uniqueness constraint.
  • Test: with "prueba": true it responds without touching the real system.
  • Response: the resultado field (up to 2,000 characters) is what the brain reads and what is recorded in the log.

What to respond and how Zunous retries

Your responseWhat Zunous does
2xxDone. The brain reads your resultado
4xx or a 3xx redirectError, no retry. Zunous doesn't follow redirects
5xx, network down or more than 10 secondsOne retry after one second, with the same Zunous-Delivery and a new timestamp
It fails againThe brain receives the error in the same run

That's why you should respond quickly: if your system is slow, the retry arrives while the first call is still working, and that's where idempotency protects you.

The URL must be https, on port 443, at a public domain. Zunous rejects IP addresses, localhost and internal names, so publish the server behind your domain with a valid certificate. The full rules are in URL rules.

Test it on your machine

Before publishing it, sign a call yourself with openssl and send it to your local server:

bash
export ZUNOUS_WHSEC="whsec_…"
CUERPO='{"accion":"registrar_pago","organizacion":"acme","brain":"cobranza","ejecucion":null,"aprobada_por":null,"prueba":true,"datos":{"factura":"FV-1023","valor":1200000}}'
TS=$(date +%s)
FIRMA="v1=$(printf '%s.%s' "$TS" "$CUERPO" | openssl dgst -sha256 -hmac "$ZUNOUS_WHSEC" | sed 's/^.*= //')"
curl -s http://localhost:3000/zunous/acciones \
  -H "Content-Type: application/json" \
  -H "Zunous-Timestamp: $TS" -H "Zunous-Signature: $FIRMA" -H "Zunous-Delivery: test-1" \
  -d "$CUERPO"

It should respond {"resultado":"Test received; nothing was recorded."}. Once it's published, ask the admin to click Send test on the action's card.

Practice

Electro Hogar Tolima, a home appliance chain in Ibagué, wants the Collections Brain to record the payments it reconciles:

  1. Run the server with a test secret and send the signed call above.
  2. Remove "prueba": true, change the timestamp to one from 10 minutes ago and check that it responds 401.
  3. Send the same valid call twice with the same Zunous-Delivery and check that registrarPagoEnTuSistema runs only once.
  4. Replace the Map with a table in your database with the delivery ID as a unique key.
  5. Publish it at https://pagos.electrohogar.com.co/zunous/acciones and ask the admin to create the action and click Send test.

Check what you learned

1. Your verification always fails even though the secret is correct. What's the most common cause?

2. Why do you store the Zunous-Delivery?

3. What happens if your server responds with a 301 redirect?