# Webhooks and signature verification

> Receive every status change by POST, answer 200 and verify it comes from zulu with its HMAC-SHA256 signature.

[Sandbox · coming soon]

zulu tells you by `POST` when something changes, so you do not have to poll. Webhooks are set up in the [dashboard](https://developers.zulu.com.co/en/dashboard), as in production: one URL per type and up to 5 static headers zulu sends on every delivery.

## Types

| Type             | Sent when                                          | Payload                                            |
| ---------------- | -------------------------------------------------- | -------------------------------------------------- |
| `TRANSACTIONS`   | A withdrawal or a conversion changes status        | `{transactionId, status}`                          |
| `DEPOSITS`       | Money lands in your COP balance (PSE, Bre-B or QR) | `{depositId, method, amount, currency, reference}` |
| `RECHARGE_LINKS` | A PSE payment link changes status                  | `{slug, status}`                                   |

```json title="TRANSACTIONS"
{
  "status": "COMPLETED",
  "transactionId": "SBX-OR-NPTRFI261124K7Q2M9-X4"
}
```

```json title="DEPOSITS"
{
  "amount": 250000,
  "currency": "COP",
  "depositId": "SBX-MOV-CREDIT-5d1b2f0e-6c3a-4e8b-9f7d-1a2b3c4d5e6f",
  "method": "BRE_B",
  "reference": "@acmepagos"
}
```

```json title="RECHARGE_LINKS"
{
  "slug": "7QmVt3KpXz",
  "status": "PAID"
}
```

The payload is short on purpose: fetch the resource (`GET /v1/transactions/{transactionId}`, `GET /v1/deposits/{depositId}`, `GET /v1/recharge-links/{slug}`) for the complete, current detail.

## Deliveries and retries

- A delivery succeeds only if you answer **exactly HTTP 200**. A 201, a 204, a redirect or a timeout counts as a failure.
- On failure zulu retries after 30 seconds, 2 minutes, 10 minutes, 1 hour and 6 hours. After the last attempt the delivery is `DEAD`.
- An endpoint is disabled after 50 consecutive failures, and we e-mail you.
- Arrival order is not guaranteed: rely on `status` and on fetching the resource, not on the order.

Answer 200 as soon as you receive and verify the webhook, and process it afterwards (on a queue): a slow task never turns into a retry.

## Verify the signature

Every delivery carries three headers:

| Header                     | What it is                                                                           |
| -------------------------- | ------------------------------------------------------------------------------------ |
| `X-Zulu-Webhook-Id`        | Event id (UUID). It is the same on every retry: use it to avoid processing it twice. |
| `X-Zulu-Webhook-Timestamp` | Unix seconds of the attempt.                                                         |
| `X-Zulu-Webhook-Signature` | `v1=` followed by the HMAC-SHA256 in hex.                                            |

The signature is `HMAC-SHA256(secret, "zulu-webhook/v1\n" + id + "\n" + timestamp + "\n" + sha256(raw body))` in hex, with the endpoint's secret (dashboard) as UTF-8 bytes. To accept a webhook:

1. Compute the SHA-256 of the **raw body**, exactly as it arrived. Never re-serialize the JSON.
2. Reject the timestamp when it is more than 300 seconds away from your clock.
3. Compare your signature with the received one in constant time.
4. Drop the ids you already processed.

**Verify a webhook**

```js label="Node.js"
import { createHash, createHmac, timingSafeEqual } from 'node:crypto';

// rawBody: the request body exactly as received (string or Buffer), before any JSON.parse.
export function verifyZuluWebhook({ secret, id, timestamp, signature, rawBody, now = Math.floor(Date.now() / 1000) }) {
  if (!/^\d+$/.test(timestamp) || Math.abs(now - Number(timestamp)) > 300) return false;

  const bodySha256 = createHash('sha256').update(rawBody).digest('hex');
  const content = `zulu-webhook/v1\n${id}\n${timestamp}\n${bodySha256}`;
  const expected = Buffer.from(`v1=${createHmac('sha256', secret).update(content).digest('hex')}`);
  const received = Buffer.from(signature ?? '');

  return expected.length === received.length && timingSafeEqual(expected, received);
}
```

```python label="Python"
import hashlib
import hmac
import time


def verify_zulu_webhook(secret: str, webhook_id: str, timestamp: str, signature: str, raw_body: bytes, now=None) -> bool:
    """raw_body: the request body exactly as received, before any json.loads."""
    now = int(time.time()) if now is None else now
    if not timestamp.isdigit() or abs(now - int(timestamp)) > 300:
        return False

    body_sha256 = hashlib.sha256(raw_body).hexdigest()
    content = f"zulu-webhook/v1\n{webhook_id}\n{timestamp}\n{body_sha256}".encode()
    expected = "v1=" + hmac.new(secret.encode(), content, hashlib.sha256).hexdigest()

    return hmac.compare_digest(expected, signature or "")
```

### Test vector

Your implementation must accept this signature (with `now` within 300 seconds of the timestamp) and reject it if you change a single byte of the body:

| Field                      | Value                                                                   |
| -------------------------- | ----------------------------------------------------------------------- |
| secret                     | `whsec_sandbox_test_3c9a1f8e2b7d4a6c`                                   |
| `X-Zulu-Webhook-Id`        | `0b6f3c2e-9a41-4d7b-8e15-6c2f9a0d3b47`                                  |
| `X-Zulu-Webhook-Timestamp` | `1795532645`                                                            |
| body                       | `{"status":"COMPLETED","transactionId":"SBX-OR-NPTRFI261124K7Q2M9-X4"}` |
| sha256(body)               | `6c9bcdb3ad36980f0ea8dd58cf9f68c9610937dc078eaee53cdc3908ba8ba7a8`      |
| `X-Zulu-Webhook-Signature` | `v1=cea8ec57f628a03edbdf6974f98d098cb6e1f0ab84384f07ddc90ce06243fa9f`   |

> **The signature is a preview**
>
> Production does not sign its webhooks today. The signature arrives with this same shape; meanwhile, protect your production endpoint with the static headers you set in the dashboard.
