Guides

WhatsApp webhook receiver in Express (Node.js)

A WhatsApp webhook receiver in Express (Node.js) on HelloHop needs the raw request body, a constant-time check of X-HelloHop-Signature, a saved event before the 200 and deduplication by chat and UTC day. HelloHop has no verify token and no GET handshake: it signs every delivery instead. This guide's receiver replies to inbound messages and records message.status receipts.

Facts (as of October 2026, API v1)

  • HelloHop signs each delivery in X-HelloHop-Signature: the lowercase hex HMAC-SHA256 of the raw body, keyed with the receiver secret, with no prefix.
  • Your endpoint has 10 seconds by default to answer any 2xx. A timeout, a network error, a 5xx, 408, 425 or 429 is retried with a growing wait for about a day and a half. Any other 4xx is a refusal and stops after three tries over about five minutes, and the webhook.test event gets one attempt.
  • A retry keeps the same body, id and timestamp. The delivery header is not signed, so build your keys from fields inside the verified body.
  • HelloHop has no GET handshake and no verify token. You set a secret of at least 24 characters on the receiver and every delivery is signed with it in X-HelloHop-Signature. POST /v1/sessions/{channel}/webhooks/test sends one signed webhook.test event to a URL you already set.
  • The unified POST /v1/sessions/{channel}/messages route accepts an Idempotency-Key of up to 255 characters. Repeating the same key and body within 24 hours returns the first result without another send, with the response header Idempotent-Replayed: true.
  • A 504 send_unconfirmed, a timeout, a 409 idempotency_uncertain or a 503 with ambiguous true means the message may have gone out. Treat it as possibly delivered and look at the chat before you send it again.

Steps

  1. Subscribe. PUT your HTTPS URL, the events message and message.status, and a secret of at least 24 characters to /v1/sessions/{channel}/webhooks. PUT replaces the whole receiver list.
  2. Verify the raw body. Mount express.raw on the route, compute the HMAC-SHA256 of the bytes and compare it with the signature header in constant time. Answer 401 on a mismatch.
  3. Save, then answer. Insert the inbound text under a key built from the chat and the day. If the insert fails, answer 500 so the event is delivered again. Answer 200 only after the write.
  4. Reply and track receipts. Claim the saved event, send one reply with an Idempotency-Key built from that key, and store each message.status receipt by the message id it names.

No verify token: what HelloHop does instead

Some webhook providers check your endpoint with a GET request that carries a verify token. HelloHop sends no such request. You set a secret of at least 24 characters on the receiver with PUT, and every delivery is a POST signed with that secret. Your handler proves a delivery is genuine by recomputing the signature, so there is nothing to answer on a GET. To try the endpoint, call POST /v1/sessions/{channel}/webhooks/test with a URL you already set: it delivers one signed webhook.test event there and sends nothing to WhatsApp.

Subscribe to messages and receipts

curl
API=https://api.hellohop.app/v1

curl -s -X PUT "$API/sessions/$CHANNEL_ID/webhooks" \
  -H "Authorization: Bearer $CHANNEL_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"receivers":[{"url":"https://example.com/webhooks/whatsapp","events":["message","message.status"],"secret":"REPLACE_WITH_24_PLUS_CHARACTERS"}]}'

List message.status yourself. The default set for a receiver is message, group.participants and session.status, and it does not include message.status.

The receiver (Node.js)

Implement the table helpers named in the comments at the top of the sample: one events row per chat per UTC day, with a unique key. The route verifies the raw body first, writes the event or the receipt, and only then answers 200. It replies to plain text in a direct chat only, once per chat per UTC day, so reactions, deletes, poll votes and another auto-responder cannot start a loop. The day comes from the UTC timestamp of the event, so it rolls over at 07:00 in Bangkok, and a redelivery that crosses midnight keeps its key. To use your own day, change the date slice in the key. A repeated delivery changes nothing: the insert ignores a known key and the claim goes to one worker. The sample checks WEBHOOK_SECRET at startup and refuses to start without 24 characters or more. The send helper waits at most 30 seconds in the claim. For a longer Retry-After it returns retryAt, and a retry outcome puts the row back to pending with that next_attempt. Neither the 60 second sweep nor a new text from the same chat claims the row before it is due, and then the same key and body are sent again. An abandoned claim becomes unknown and is not resent automatically. Events you do not handle, including webhook.test, get a plain 200. The reply text is an example.

Node.js: Express receiver
import crypto from 'node:crypto';
import express from 'express';

const API = 'https://api.hellohop.app/v1';
const { CHANNEL_ID, CHANNEL_TOKEN } = process.env;

// One send. Repeating the same key with the same body returns the first result.
async function sendWhatsApp(key, message) {
  try {
    const res = await fetch(`${API}/sessions/${CHANNEL_ID}/messages`, {
      method: 'POST',
      headers: {
        Authorization: `Bearer ${CHANNEL_TOKEN}`,
        'Content-Type': 'application/json',
        'Idempotency-Key': key,
      },
      body: JSON.stringify(message),
      signal: AbortSignal.timeout(15000),
    });
    const data = await res.json().catch(() => ({}));
    const result = { status: res.status, code: data.code, ambiguous: data.ambiguous, id: data.id };
    if (classify(result) === 'retry') {
      // 429 whatsapp_rate_limited carries no Retry-After, so it falls back to 1 second. This helper waits at most 30 seconds;
      // a longer Retry-After is not slept through: result.retryAt (Unix ms) says when the row is due, and your sweep or timer retries then.
      const h = res.headers.get('Retry-After');
      const ms = Math.max(0, (h ? (/^\d+$/.test(h) ? Number(h) * 1000 : Date.parse(h) - Date.now()) : 1000) || 1000);
      result.retryAt = Date.now() + ms;
      await new Promise((resolve) => setTimeout(resolve, Math.min(30000, ms)));
    }
    return result;
  } catch {
    return { status: 0 }; // timeout or lost connection: the message may have gone out
  }
}

// One answer per send: sent (server_ack), queued, retry, unknown or failed.
function classify({ status, code, ambiguous }) {
  if (status === 200) return 'sent'; // server_ack, not delivered
  if (status === 202) return 'queued'; // observe webhooks, do not resend
  // Refused before sending: repeat the same key and body later.
  const refused = ['upstream_unavailable', 'hopsmart_settings_unavailable', 'operator_unresolved'];
  if (status === 429 || (status === 503 && (ambiguous === false || refused.includes(code)))) return 'retry';
  // Possibly sent: look at the chat, never resend.
  if (status === 0 || status >= 500 || code === 'idempotency_uncertain') return 'unknown';
  return 'failed'; // an unlinked channel, idempotency_conflict, a bad request: fix it, do not retry
}
// Your events table: unique key, payload, state, claimed_at (Unix ms), message_id, next_attempt (Unix ms, default 0). Helpers:
//   saveEvent(key, payload)  insert a pending row once; a repeat changes nothing
//   claimSend(key)           atomic pending -> claimed, only when next_attempt <= now; sets claimed_at; true for one caller only
//   finish(key, expected, state, id, nextAttempt) UPDATE only WHERE state = expected; save the message id
//     retry returns to pending and saves nextAttempt (the helper's retryAt); all other outcomes stop automatic sends
//   skipPending(key)         UPDATE pending -> skipped only; never overwrites a claim or an outcome
//   saveBody(key, text) / savedBody(key)  keep the exact text, so a retry sends the same body
// Your timer calls recoverAbandonedClaims first, then re-runs pending rows. Never re-send unknown rows.
// db.run(sql, params) executes SQL in your database; claimed_at is Unix milliseconds.
async function recoverAbandonedClaims() {
  await db.run("UPDATE events SET state = 'unknown' WHERE state = 'claimed' AND (claimed_at IS NULL OR claimed_at < ?)",
    [Date.now() - 5 * 60 * 1000]);
}
const app = express();

const { WEBHOOK_SECRET } = process.env;
if (!WEBHOOK_SECRET || WEBHOOK_SECRET.length < 24) throw new Error('Set WEBHOOK_SECRET to the receiver secret (24 characters or more) before you start');
function validSignature(raw, header) {
  const expected = crypto.createHmac('sha256', WEBHOOK_SECRET).update(raw).digest('hex');
  return typeof header === 'string' && header.length === expected.length &&
    crypto.timingSafeEqual(Buffer.from(header), Buffer.from(expected));
}
// Also yours: markStatus(ids, status). It upserts one row per id into a receipts table (message_id, status) and only moves forward: delivered, then read or played.
// A receipt can arrive before the reply's message id is saved, so it never updates an events row. Join receipts to events on message_id when you read.
// db.all(sql, params) returns rows. Each events row holds the first inbound text of one chat on one UTC day: key = auto-<chat>-<UTC date>, payload = the raw body.

async function reply(key, event) {
  if (!(await claimSend(key))) return; // another worker has it, or the row is final
  const result = await sendWhatsApp(`reply-${key}`, { type: 'text', to: event.payload.chat_jid, text: 'Thanks, we got your message.' });
  // retry returns the row to pending, due at result.retryAt; the id lets message.status match
  await finish(key, 'claimed', classify(result), result.id, result.retryAt);
}

async function sweep() {
  await recoverAbandonedClaims();
  const rows = await db.all("SELECT key, payload FROM events WHERE state = 'pending' AND next_attempt <= ? LIMIT 100", [Date.now()]);
  for (const row of rows) await reply(row.key, JSON.parse(row.payload));
}
setInterval(() => sweep().catch(console.error), 60 * 1000);

app.post('/webhooks/whatsapp', express.raw({ type: 'application/json' }), async (req, res) => {
  if (!validSignature(req.body, req.get('X-HelloHop-Signature'))) return res.sendStatus(401);
  const raw = req.body.toString('utf8');
  const event = JSON.parse(raw);
  const m = event.payload;
  // Answer plain text in a direct chat only: a reaction, a delete or a poll vote gets no reply. One reply per chat per UTC day,
  // so a second auto-responder on the other side cannot start a loop. The date is the UTC day of the event timestamp,
  // so a redelivery keeps its key even across midnight. To use your own day, change the slice below.
  const inbound = event.type === 'message' && m.type === 'text' && !m.from_me && !m.is_group;
  const key = inbound ? `auto-${m.chat_jid}-${event.timestamp.slice(0, 10)}` : null;
  try {
    if (event.type === 'message.status') await markStatus(m.ids, m.status); // safe to repeat
    else if (inbound) await saveEvent(key, raw); // a repeated key changes nothing
  } catch {
    return res.sendStatus(500); // nothing is lost: the webhook is delivered again
  }
  res.sendStatus(200); // only after the write
  if (inbound) reply(key, event).catch(console.error);
});

app.listen(3000);

What the handler does with each send result

Send resultWhat your handler does
200 server_ackWhatsApp acknowledged the send. Mark it sent and save id; this is not a delivery receipt.
202 queuedPersisted in the queue, not delivered. A channel that queues its sends (for example while accepted sends drain) answers every text send this way, with id, status queued, position and expires_at. Mark it queued and save id. Observe the result through webhooks without resending.
429, or 503 with ambiguous false or code upstream_unavailable, hopsmart_settings_unavailable or operator_unresolvedRefused before sending. Honor Retry-After, keep the same key and body, and retry later. The Node helper waits at most 30 seconds before returning retry with a retryAt time, and the pages that keep a due time skip the row until then; the other Node timer pages retry on their next run. The Flask, Python reminder and PHP samples return the time to retry instead of waiting; the Sheets helper saves next_attempt_at and skips the row until then.
504 send_unconfirmed, 409 idempotency_uncertain, 503 with ambiguous true, a timeout or a lost responsePossibly delivered. Mark it unknown and look at the chat before any resend. Never force a resend of an uncertain key with a new key.
409 idempotency_conflictThe same key was used for a different message. Fix how you build the key. The first message is unchanged.
Any other 409Mark it failed. Fix the channel before scheduling another attempt.
Other 4xxThe request is wrong and a retry will not fix it. Log it and move on.

Subscribe to message and message.status webhooks and verify their signatures. The result of a queued send arrives as a message event: match the saved response id to payload.id. message.status reports delivered or read for each id in payload.ids. A send held by HopSmart™ expires 72 hours after acceptance, and the 202 carries expires_at. If no event arrives, read the job with GET /hopsmart/jobs/{id}. Save event ids to deduplicate. Do not resend queued work while waiting for a result.

What message.status tells you

payload.ids lists the messages one receipt covers, and payload.status is delivered, read, played or undecryptable. Receipts from your own other devices are not sent. Deliveries can repeat or arrive out of order, so the sample only moves a stored status forward. A receipt can also arrive before the id of your reply is saved, so it is stored by message id in its own table and joined later.

Questions

Is there a verify token or a GET handshake?
No. HelloHop signs every delivery with the secret you set on the receiver. Verify X-HelloHop-Signature on the raw body instead.
Why does the signature check need the raw body?
The signature covers the exact bytes HelloHop sent. Parsing and re-serializing the JSON can change the bytes, and then the hashes no longer match.
Why save the event before answering 200?
A 200 tells HelloHop to stop retrying. If the process dies after the 200 and before the save, the event is gone. Answer 500 on a failed save and the event is delivered again.
How do I avoid replying twice to one message?
The key is built from the chat and the day and is unique in your table, the claim goes to one worker, and the reply carries an Idempotency-Key built from that key.
What happens to an event I do not handle?
Answer 200 and ignore it. A non-2xx answer counts as a failed delivery, and while that event is retried, later events for that receiver URL and channel wait behind it.

Free sandbox, forever. Upgrade when you're ready.

Start free

HelloHop is an independent WhatsApp API for developers: send and receive messages, automate groups and communities, and get signed webhooks. Not affiliated with WhatsApp or Meta. You link your own number.

WhatsApp Webhook Receiver in Express (Node.js) | HelloHop