# Webhooks

Webhooks let the API call you instead of you polling it. When an event happens, we send a `POST` request with a JSON body to the URL you registered, signed with a secret only you and we know.

## Events

| Event | Sent when | `data` |
|---|---|---|
| `bulk.completed` | A bulk job has finished | The [bulk job object](/docs/api-reference/bulk), the same one `GET /bulk/{id}` returns |
| `credits.low` | Your balance falls under 10% of your plan's monthly credits | `org_id`, `balance` and `threshold` |

## Set up an endpoint

1. Create a route in your application that accepts `POST` requests, such as `https://yourapp.example/webhooks/validation`.
2. In the dashboard, add a webhook with that URL and choose the events it should receive.
3. Copy the signing secret the dashboard shows for the webhook and store it with your other secrets.
4. Verify the signature of every request before you trust it, as shown below.

## Payload

Every event has the same envelope:

| Field | Type | Description |
|---|---|---|
| `id` | string | Identifier of the event, starting with `evt_`. The same event delivered twice keeps the same `id`. |
| `type` | string | `bulk.completed` or `credits.low`. |
| `created_at` | string | When the event happened, ISO 8601 in UTC. |
| `data` | object | The details of the event, depending on its type. |

### bulk.completed

```json
{
  "id": "evt_01M84D41Y02M9PX53VE2SJENF4",
  "type": "bulk.completed",
  "created_at": "2026-11-23T14:31:52.118Z",
  "data": {
    "id": "bulk_01M84BSX8MDFXRWMW580GKJWEY",
    "object": "bulk_job",
    "type": "email",
    "status": "completed",
    "rows_total": 48210,
    "rows_done": 48210,
    "credits_reserved": 48210,
    "credits_used": 47988,
    "created_at": "2026-11-23T14:02:11.482Z",
    "completed_at": "2026-11-23T14:31:51.904Z",
    "download_url": "https://api.qelka.com/v1/bulk/bulk_01M84BSX8MDFXRWMW580GKJWEY/download?expires=1795530712&signature=9c1e5a3f7b2d4e6a8c0f1b3d5e7a9c2e4f6a8b0d1c3e5f7a9b2d4c6e8f0a1b3c",
    "error": null
  }
}
```

Read `data.status` before you download: only a `completed` job has a `download_url`.

### credits.low

```json
{
  "id": "evt_01M84MR3G87QRSTPY7VJPCD3P7",
  "type": "credits.low",
  "created_at": "2026-11-23T16:45:09.530Z",
  "data": {
    "org_id": "org_01M84BDPNRQBDQEPZ7787ST5TH",
    "balance": 912,
    "threshold": 1000
  }
}
```

| Field | Type | Description |
|---|---|---|
| `data.org_id` | string | Your organization. |
| `data.balance` | integer | Your credit balance when the event fired. |
| `data.threshold` | integer | 10% of your plan's monthly credits: the line the balance just crossed. |

Values in the examples are illustrative.

## Verify the signature

Every request carries an `X-Signature` header:

```http
X-Signature: t=1795444312,v1=5d2c9f0e8b7a6d4c3b2a1f0e9d8c7b6a5f4e3d2c1b0a9f8e7d6c5b4a3f2e1d0c
```

- `t` is the Unix time, in seconds, when we signed the request.
- `v1` is the hex-encoded HMAC-SHA256 of the string `<t>.<raw body>`, keyed with your webhook's signing secret.

To verify a request:

1. Read the raw body exactly as received, before any JSON parsing. Parsing and serializing again changes the bytes and breaks the signature.
2. Split the header on commas and read `t` and `v1`.
3. Reject the request if `t` is more than 5 minutes away from your current time. This stops an attacker from replaying a request they captured.
4. Compute the HMAC-SHA256 of `t`, a dot, and the raw body, with your secret as the key.
5. Compare it with `v1` in constant time. If they differ, reject the request.

### With the JavaScript SDK

The SDK exports `verifyWebhook(rawBody, signatureHeader, secret)`. An Express route:

```javascript
import express from 'express'
import { verifyWebhook } from '@qelka/sdk'

const app = express()

app.post('/webhooks/validation', express.raw({ type: 'application/json' }), async (req, res) => {
  const rawBody = req.body.toString('utf8')
  const valid = await verifyWebhook(rawBody, req.get('X-Signature'), process.env.WEBHOOK_SECRET)
  if (!valid) return res.status(400).end()
  res.status(204).end()
  await processEvent(JSON.parse(rawBody))
})

async function processEvent(event) {
  if (event.type === 'bulk.completed' && event.data.status === 'completed') {
    const file = await fetch(event.data.download_url)
    console.log(`Job ${event.data.id} done, ${(await file.text()).length} characters of results`)
  }
  if (event.type === 'credits.low') {
    console.warn(`Credit balance ${event.data.balance} is under ${event.data.threshold}`)
  }
}

app.listen(3000)
```

`express.raw()` keeps the body as bytes. A global `express.json()` middleware that runs first would parse it and lose the original bytes, so mount the webhook route before it, or exclude the route from it.

### Without the SDK, in Node.js

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

export function verifySignature(rawBody, header, secret, toleranceSeconds = 300) {
  if (!header) return false
  const fields = header.split(',').map((part) => part.trim().split('='))
  const timestamp = Number(fields.find(([key]) => key === 't')?.[1])
  const signatures = fields.filter(([key]) => key === 'v1').map(([, value]) => value)
  if (!Number.isInteger(timestamp) || signatures.length === 0) return false
  if (Math.abs(Date.now() / 1000 - timestamp) > toleranceSeconds) return false
  const expected = createHmac('sha256', secret).update(`${timestamp}.${rawBody}`).digest('hex')
  return signatures.some(
    (signature) => signature.length === expected.length && timingSafeEqual(Buffer.from(signature), Buffer.from(expected)),
  )
}
```

### In Python

A Flask route:

```python
import hashlib
import hmac
import os
import time

from flask import Flask, abort, request

app = Flask(__name__)
SECRET = os.environ["WEBHOOK_SECRET"].encode()


def verify(raw_body: bytes, header: str | None, tolerance: int = 300) -> bool:
    if not header:
        return False
    fields = [part.strip().split("=", 1) for part in header.split(",") if "=" in part]
    timestamps = [value for key, value in fields if key == "t"]
    signatures = [value for key, value in fields if key == "v1"]
    if len(timestamps) != 1 or not timestamps[0].isdigit() or not signatures:
        return False
    if abs(time.time() - int(timestamps[0])) > tolerance:
        return False
    message = timestamps[0].encode() + b"." + raw_body
    expected = hmac.new(SECRET, message, hashlib.sha256).hexdigest()
    return any(hmac.compare_digest(expected, signature) for signature in signatures)


@app.post("/webhooks/validation")
def webhook():
    if not verify(request.get_data(), request.headers.get("X-Signature")):
        abort(400)
    event = request.get_json()
    if event["type"] == "credits.low":
        app.logger.warning("Credit balance %s is under %s", event["data"]["balance"], event["data"]["threshold"])
    return "", 204
```

## Respond fast, process later

Answer with any `2xx` status within 10 seconds. Anything else, including a timeout, counts as a failed delivery. Redirects are not followed either, so register the final URL of your endpoint. If processing takes longer, such as downloading a large result file, acknowledge first and do the work afterwards or in a background queue, as the Express example does.

Requests come with `Content-Type: application/json` and the `User-Agent` header `Qelka-Webhooks/1.0`, which you can use to recognize them in your logs. Do not use it to authenticate them: only the signature proves where a request comes from.

## Retries and duplicates

A failed delivery is retried up to 5 times, with increasing delays between attempts. Two consequences for your code:

- **The same event can arrive more than once,** for example when your server processed it but answered too late. Store the `id` of each event you handle and skip ids you have already seen.
- **Events can arrive out of order** after retries. Use `created_at` and the state in `data`, such as a bulk job's `status`, rather than the arrival order.

## Checklist

- Verify `X-Signature` on every request, against the raw body, with a 5-minute tolerance.
- Answer `2xx` within 10 seconds.
- Deduplicate on the event `id`.
- Keep the signing secret out of your code and logs, like an API key.
