---
title: "Set up and verify webhooks"
description: "Get every received message and every delivery outcome as a signed POST to your endpoint, and check the signature."
url: "https://docs.yoagent.dev/webhooks/set-up-and-verify-webhooks"
---

# Set up and verify webhooks

A webhook sends each event — a message arrived, a sent message was delivered or bounced, a domain was verified — to a URL of yours as a `POST` with a JSON body, signed with the webhook’s secret ([Standard Webhooks](https://www.standardwebhooks.com/)). Your code reacts the moment it happens, without waiting on the API.

## Events

| Event                  | When                                                                                            | Scopes                            |
| ---------------------- | ----------------------------------------------------------------------------------------------- | --------------------------------- |
| `message.received`     | A message arrived in an inbox the webhook covers.                                               | `project`, `inboxes`, `catch_all` |
| `message.sent`         | A sent message was handed on to its first recipient.                                            | `project`, `inboxes`              |
| `message.delivered`    | A recipient's server accepted a sent message.                                                   | `project`, `inboxes`              |
| `message.bounced`      | A sent message bounced for a recipient (its address is suppressed).                             | `project`, `inboxes`              |
| `message.complained`   | A recipient marked a sent message as spam (the address is suppressed, sending may be paused).   | `project`, `inboxes`              |
| `message.rejected`     | A sent message was not sent to a recipient (the reason says why).                               | `project`, `inboxes`              |
| `message.unsubscribed` | A recipient unsubscribed from the organization's mail.                                          | `project`, `inboxes`              |
| `domain.verified`      | A custom domain's DNS records were found (mail to it is accepted), or its sending was verified. | `project`                         |

Each event’s body, field by field, with an example: [Webhook events](https://docs.yoagent.dev/reference/webhook-events). Every body has `event_id`, `event_type` and `occurred_at`; a message event carries the message, with its text, links and codes for `message.received`, and a recipient event its `recipient`.

## What a webhook watches

A webhook belongs to one project and has a **scope**:

- **`project`** — the mail of all the project’s inboxes, the catch-all’s included, and its domains.
- **`inboxes`** — only the inboxes in `inbox_ids` (up to 100). If they are all deleted, the webhook stays and receives nothing.
- **`catch_all`** — only mail that came through the project’s catch-all, while the catch-all is on. The catch-all is a feature of Pro: on Free, creating such a webhook answers `403 plan_required`.

`event_types` picks the events, among those its scope gets; without it, all of them.

## Create a webhook

The URL must be `https` and reach the public internet: an address that resolves to a private network is refused (`400 invalid_url`). To receive webhooks on your laptop, use a tunnel (ngrok, Cloudflare Tunnel and the like).

**curl**

```bash
curl -s https://api.yoagent.dev/v0/webhooks \
  -H "Authorization: Bearer $YOAGENT_KEY" \
  -H "Content-Type: application/json" \
  -d '{"url": "https://app.example.com/webhooks/yoagent", "scope": "inboxes", "inbox_ids": ["inb_01je56wqswfmn9pgbc1wq8tjgq"], "event_types": ["message.received"]}'
```

**MCP**

```text
create_webhook(url="https://app.example.com/webhooks/yoagent", scope="inboxes", inbox_ids=["inb_01je56wqswfmn9pgbc1wq8tjgq"], event_types=["message.received"])
```

Without `project_id`, the webhook goes to the project of its inboxes, or the first one the key may add webhooks to. A `client_id` makes the call safe to repeat: the same `client_id` returns the same webhook. In the dashboard: **Webhooks → New webhook**.

![The New webhook dialog in the dashboard: the project, the URL, which mail and which events](https://docs.yoagent.dev/_astro/webhook-new.bF_lqGUH_ZqhAhj.webp)

The answer has the webhook’s `secret`, `whsec_…`. It stays on the webhook’s page and in its API answers for whoever may create webhooks in the project. Later you can change its `event_types` and `inbox_ids`, or pause it (`PATCH /v0/webhooks/{webhook_id}`, `update_webhook`); its URL and scope stay. To move to a new URL or a new secret, create a second webhook, switch your endpoint to it, then delete the first.

Webhooks an organization may have: 3 on Free, 100 on Pro.

## Receive and verify

Each request carries three headers:

| Header              | What it is                                                                                                                 |
| ------------------- | -------------------------------------------------------------------------------------------------------------------------- |
| `webhook-id`        | The event’s id, `evt_…` — the same on every retry of the event                                                             |
| `webhook-timestamp` | When this attempt was sent, in Unix seconds                                                                                |
| `webhook-signature` | `v1,` and the base64 HMAC-SHA256 of `<webhook-id>.<webhook-timestamp>.<body>`, keyed with the secret’s base64 part decoded |

Check the signature on the **raw** body, as it arrived — not on JSON parsed and written again — and refuse an old timestamp, so a captured request cannot be replayed later. Then record the event — in your database or queue, once per `event_id` — and answer `2xx` within 10 seconds; do slow work after that. An answered event is never sent again. The answer’s body is not read, and redirects are not followed.

**JavaScript**

Node.js, no packages:

```js
import { createHmac, timingSafeEqual } from "node:crypto";
import { createServer } from "node:http";

const SECRET = process.env.YOAGENT_WEBHOOK_SECRET; // whsec_…

function verified(headers, body) {
  const id = headers["webhook-id"];
  const timestamp = headers["webhook-timestamp"];
  const signatures = headers["webhook-signature"];
  if (!id || !timestamp || !signatures) return false;
  if (Math.abs(Date.now() / 1000 - Number(timestamp)) > 300) return false;
  const key = Buffer.from(SECRET.replace(/^whsec_/, ""), "base64");
  const expected = createHmac("sha256", key)
    .update(`${id}.${timestamp}.${body}`)
    .digest();
  return signatures.split(" ").some((signature) => {
    const [version, value] = signature.split(",");
    const given = Buffer.from(value ?? "", "base64");
    return (
      version === "v1" &&
      given.length === expected.length &&
      timingSafeEqual(given, expected)
    );
  });
}

createServer(async (request, response) => {
  const chunks = [];
  for await (const chunk of request) chunks.push(chunk);
  const body = Buffer.concat(chunks).toString("utf8");
  if (!verified(request.headers, body)) {
    response.writeHead(401).end();
    return;
  }
  const event = JSON.parse(body);
  console.log(event.event_type, event.event_id); // record it here, once per event_id
  response.writeHead(204).end();
}).listen(3000);
```

**Python**

The check needs only the standard library; the server here is [Flask](https://flask.palletsprojects.com/):

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

from flask import Flask, abort, request

SECRET = os.environ["YOAGENT_WEBHOOK_SECRET"]  # whsec_…
app = Flask(__name__)


def verified(headers, body: bytes) -> bool:
    msg_id = headers.get("webhook-id")
    timestamp = headers.get("webhook-timestamp")
    signatures = headers.get("webhook-signature")
    if not (msg_id and timestamp and signatures):
        return False
    try:
        sent_at = int(timestamp)
    except ValueError:
        return False
    if abs(time.time() - sent_at) > 300:
        return False
    key = base64.b64decode(SECRET.removeprefix("whsec_"))
    signed = f"{msg_id}.{timestamp}.".encode() + body
    expected = base64.b64encode(hmac.new(key, signed, hashlib.sha256).digest()).decode()
    return any(
        hmac.compare_digest(signature.removeprefix("v1,"), expected)
        for signature in signatures.split()
        if signature.startswith("v1,")
    )


@app.post("/webhooks/yoagent")
def yoagent():
    if not verified(request.headers, request.get_data()):
        abort(401)
    event = request.get_json()
    print(event["event_type"], event["event_id"])  # record it here, once per event_id
    return "", 204
```

A [Standard Webhooks library](https://github.com/standard-webhooks/standard-webhooks) for your language does the same check: `Webhook(secret).verify(body, headers)`.

What happens when your endpoint is down or slow, and how to see every attempt: [Webhook delivery](https://docs.yoagent.dev/webhooks/webhook-delivery).
