# Receive webhooks

> Let Quenza call your server when a client is created or accepts their invitation, and check, deduplicate and process each webhook safely.

Available on the Growth plan and higher.

Source: https://quenza.com/help/api/webhooks/

The API answers when you ask; a webhook tells you without asking. As soon as a client is created in your workspace, or accepts their invitation, Quenza sends a `POST` request to an address on your server. Your code can then add the client to your CRM, start a welcome email in your mailing tool or post a note in your team chat.

At Bright Path Coaching, a client who signs up through the landing page triggers [`client.created`](https://quenza.com/help/api/webhooks/client-created/). Sarah Bennett's CRM receives the name and email address seconds later, and when the client sets up their account, [`client.invitation_accepted`](https://quenza.com/help/api/webhooks/client-invitation-accepted/) marks them as onboarded.

A workspace Owner or Manager adds the address under **Developer Tools → Webhooks**; see [Webhooks](https://quenza.com/help/integrations/webhooks/) for the dialog, the history and how to retry a message by hand. Webhooks need a paid plan, and the API is not needed for them.

## Events

| Event | Sent when | Body |
| --- | --- | --- |
| [`client.created`](https://quenza.com/help/api/webhooks/client-created/) | A client or guest is added: by hand, by import, through the API or a landing page, and when a guest is converted to a client. | `client`, `invited_by` |
| [`client.invitation_accepted`](https://quenza.com/help/api/webhooks/client-invitation-accepted/) | A client accepts their invitation and sets up their account. | `client` |

There are no webhooks for activities, programs, tasks, chats or changes to existing clients. To find out about those, ask the API on a schedule, as in the [weekly task digest](https://quenza.com/help/api/guides/weekly-task-digest/).

## The request

Quenza sends one `POST` per event and webhook address, with a JSON body and these headers:

| Header | Value |
| --- | --- |
| `Content-Type` | `application/json` |
| `X-Quenza-Event` | The event, such as `client.created`. The body does not contain it. |
| `Authorization` | `Basic …`, only when the webhook has a **Username** and **Password**. |
| Your own headers | Every header you added under **Custom Headers**, such as `X-Webhook-Secret`. |

The address must start with `https://` and be reachable from the internet. Addresses on a private network or `localhost` are refused; to try a webhook on your own computer, use a tunnel such as ngrok or Cloudflare Tunnel.

## Delivery and retries

- **Answer with a 2xx status**, such as `200` or `204`, within 30 seconds. Anything else, or no answer in time, counts as a failure.
- **Failed messages are sent again**: the first retry follows within about a minute, then the waits grow to every 4 hours. After 30 attempts, about three days after the event, the message gets the status **Failed**. A webhook that is disabled gets no retries.
- **Messages can arrive twice**: a message that timed out is sent again, also when your server did process it, and a guest who is converted to a client triggers `client.created` a second time. Use the client `id` to process each client only once.
- **Order is not guaranteed**: after a retry, `client.invitation_accepted` can arrive before the `client.created` of the same client.
- **Each message keeps its settings**: the address, headers and login are those the webhook had when the event happened, also for retries.

So answer first and do the slow work afterwards, or put it in a queue. A server that sends emails before it answers risks a timeout, a retry and a second email.

## Check that the request comes from Quenza

> **Caution:** Quenza does not sign webhook requests. Anyone who knows your address could send a request to it, so always protect it with a secret.

Set a **Username** and **Password** on the webhook (HTTP Basic Authentication), or add a custom header with a long random value, such as `X-Webhook-Secret`. Generate the value with `openssl rand -hex 32`, store it on your server as an environment variable and refuse every request without it. Compare it in constant time, so its length and content cannot be guessed from the response times.

## A complete receiver

This receiver checks the `X-Webhook-Secret` header, answers right away, skips messages it has already seen and then handles the event. It keeps the seen messages in a file to stay short; use your database in production.

**JavaScript**

```js
// Node.js 18 or later, no packages: node receiver.mjs
const secret = Buffer.from(process.env.QUENZA_WEBHOOK_SECRET);
const seenFile = 'seen-webhooks.txt';
const seen = new Set(existsSync(seenFile) ? readFileSync(seenFile, 'utf8').split('\n') : []);

const fromQuenza = (value = '') => {
  const given = Buffer.from(value);
  return given.length === secret.length && timingSafeEqual(given, secret);
};

createServer(async (req, res) => {
  if (req.method !== 'POST' || !fromQuenza(req.headers['x-webhook-secret'])) {
    res.writeHead(401).end();
    return;
  }
  let body = '';
  for await (const chunk of req) body += chunk;
  res.writeHead(204).end(); // answer first, then do the work

  const event = req.headers['x-quenza-event'];
  const { client, invited_by } = JSON.parse(body);
  const key = `${event}:${client.id}`;
  if (seen.has(key)) return; // already handled
  seen.add(key);
  appendFileSync(seenFile, `${key}\n`);

  if (event === 'client.created') {
    console.log(`New client ${client.first_name} ${client.last_name} <${client.email}>, added by ${invited_by.first_name}`);
  } else if (event === 'client.invitation_accepted') {
    console.log(`${client.email} set up their account at ${client.invitation_accepted_at}`);
  }
}).listen(3000);
```

**Python**

```python
# pip install flask, then: flask --app receiver run --port 3000
import hmac
import json
import os
import threading

from flask import Flask, request

app = Flask(__name__)
SECRET = os.environ["QUENZA_WEBHOOK_SECRET"]
SEEN_FILE = "seen-webhooks.txt"
seen = set(open(SEEN_FILE).read().split()) if os.path.exists(SEEN_FILE) else set()
lock = threading.Lock()


def handle(event, body):
    client = body["client"]
    key = f"{event}:{client['id']}"
    with lock:
        if key in seen:  # already handled
            return
        seen.add(key)
        with open(SEEN_FILE, "a") as f:
            f.write(key + "\n")
    if event == "client.created":
        who = body["invited_by"]["first_name"]
        print(f"New client {client['first_name']} {client['last_name']} <{client['email']}>, added by {who}")
    elif event == "client.invitation_accepted":
        print(f"{client['email']} set up their account at {client['invitation_accepted_at']}")


@app.post("/")
def webhook():
    if not hmac.compare_digest(request.headers.get("X-Webhook-Secret", ""), SECRET):
        return "", 401
    event = request.headers.get("X-Quenza-Event")
    body = json.loads(request.get_data())
    # Answer first, then do the work in the background.
    threading.Thread(target=handle, args=(event, body)).start()
    return "", 204
```

**PHP**

```php
<?php
// receiver.php, for example: php -S 0.0.0.0:3000 receiver.php

$secret = getenv('QUENZA_WEBHOOK_SECRET');
if ($_SERVER['REQUEST_METHOD'] !== 'POST'
    || !hash_equals($secret, $_SERVER['HTTP_X_WEBHOOK_SECRET'] ?? '')) {
    http_response_code(401);
    exit;
}

$event = $_SERVER['HTTP_X_QUENZA_EVENT'] ?? '';
$body = json_decode(file_get_contents('php://input'), true);
$client = $body['client'];

// Answer first, then do the work (PHP-FPM; elsewhere, use a queue).
http_response_code(204);
if (function_exists('fastcgi_finish_request')) {
    fastcgi_finish_request();
}

$seenFile = 'seen-webhooks.txt';
$key = "{$event}:{$client['id']}";
$seen = file_exists($seenFile) ? file($seenFile, FILE_IGNORE_NEW_LINES) : [];
if (in_array($key, $seen, true)) {
    exit; // already handled
}
file_put_contents($seenFile, $key . "\n", FILE_APPEND | LOCK_EX);

if ($event === 'client.created') {
    error_log("New client {$client['first_name']} {$client['last_name']} <{$client['email']}>, added by {$body['invited_by']['first_name']}");
} elseif ($event === 'client.invitation_accepted') {
    error_log("{$client['email']} set up their account at {$client['invitation_accepted_at']}");
}
```


In Quenza, add the webhook with your server's address and, under **Custom Headers**, the header name `X-Webhook-Secret` with the same value as `QUENZA_WEBHOOK_SECRET`.

## Try it

Before you connect the real address, send the request Quenza would send yourself:

```bash
curl -X POST http://localhost:3000/ \
  -H "Content-Type: application/json" \
  -H "X-Quenza-Event: client.created" \
  -H "X-Webhook-Secret: $QUENZA_WEBHOOK_SECRET" \
  -d '{"client":{"id":"8GJ4D9KQ","email":"emma.clarke@example.com","first_name":"Emma","last_name":"Clarke","is_guest":false,"status":"pending","created_at":"2026-11-15T09:30:00+00:00"},"invited_by":{"id":"H2V7N4QX","email":"sarah.bennett@example.com","first_name":"Sarah","last_name":"Bennett"}}'
```

Then add a test client in Quenza with an email address at example.com, and check the webhook's **History** tab: the message should show **Successful**. Delete the test client afterwards.

## Get more details

The webhook body only has the client's basics. To read everything else, such as their phone number, time zone or birthdate, [get the client](https://quenza.com/help/api/clients/get-a-client/) with the `id` from the webhook; it is the same ID the API uses. That needs an [API token](https://quenza.com/help/api/authentication/) and the Collective plan or higher.
