# Receive replies

A safe, idempotent webhook receiver.

This guide builds a webhook receiver that verifies the signature, answers fast and never processes the same event twice.

## The receiver

```js
import express from 'express';
import crypto from 'node:crypto';

const app = express();
const seen = new Set();

app.post('/webhooks/whatsapp', express.raw({ type: '*/*' }), (req, res) => {
  const header = req.get('X-Wa-Signature') || '';
  const parts = Object.fromEntries(header.split(',').map((p) => p.split('=')));
  const expected = crypto.createHmac('sha256', process.env.WHSEC).update(parts.t + '.' + req.body).digest('hex');
  const a = Buffer.from(expected);
  const b = Buffer.from(parts.v1 || '');
  const fresh = Math.abs(Date.now() / 1000 - Number(parts.t)) <= 300;

  if (!fresh || a.length !== b.length || !crypto.timingSafeEqual(a, b)) {
    return res.sendStatus(401);
  }

  const delivery = req.get('X-Wa-Delivery');
  if (seen.has(delivery)) {
    return res.sendStatus(200);
  }
  seen.add(delivery);

  queue.push(JSON.parse(req.body.toString('utf8')));
  res.sendStatus(200);
});

app.listen(3000);
```

Three points to remember:

1. The body is read **raw** (`express.raw`): the signature covers the exact bytes received.
2. The answer goes out before any processing: the event is put in a queue (`queue`).
3. `X-Wa-Delivery` is the idempotency key. In production, keep it in a database or Redis with an expiry, not in memory.

## Read an event

```json
{
  "event_type": "messages",
  "connection_id": "con_...",
  "payload": {
    "entry": [{ "changes": [{ "value": {
      "messages": [{ "from": "237600000000", "type": "text", "text": { "body": "Where is my parcel?" } }]
    } }] }]
  }
}
```

A message status arrives in `value.statuses` (`sent`, `delivered`, `read`, `failed`); a customer reply arrives in `value.messages`.

## Test

Register the address with `POST /webhook-endpoints`, send a message to your own number and reply to it: you should see a status arrive, then your reply.
