Skip to content
couryo

Developer guideEvents

Webhooks

Get your email events by webhook, signed with Standard Webhooks and retried for up to 3 days. Verification examples in Node, PHP and Python.

View as Markdown

Webhooks tell your system when something happens to an email: delivered, deferred, bounced, complained, opened, clicked. Every call is signed with the open Standard Webhooks specification.

Create a webhook#

cURL
curl https://api.couryo.com/v1/webhooks \
  -H "Authorization: Bearer $COURYO_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{ "url": "https://example.com/webhooks/couryo", "events": ["delivered", "bounced", "complained"] }'
Response
{
  "id": "whk_5n1c8v2z7r3k6m9p",
  "url": "https://example.com/webhooks/couryo",
  "events": ["delivered", "bounced", "complained"],
  "enabled": true,
  "secret": "whsec_MfKQ9r8GKYqrTwjUPD8ILPZIo2LaLaSw",
  "created_at": "2026-10-07T18:30:00Z"
}

The secret is shown only in this response. Store it with your other credentials.

  • The URL must start with https:// and be public: internal network addresses are refused (invalid_field). On every delivery the address is checked again and the connection goes to the checked IP, so DNS that changes later cannot divert the call into our network. Redirects are not followed.
  • Creating, changing and deleting webhooks needs the admin scope; listing and reading, read.
  • PATCH /v1/webhooks/{id} changes url, events or enabled (to pause without deleting). DELETE /v1/webhooks/{id} deletes it.

What you receive#

A JSON POST with three headers:

Headers
webhook-id: evt_7d3k9s0a2m5n8b1c
webhook-timestamp: 1791484264
webhook-signature: v1,K5oZfzN95Z9UVu1EsfQmfVNQhnkZ2pj9o9NDN/H/pI4=
Body
{
  "type": "bounced",
  "timestamp": "2026-10-07T18:31:04Z",
  "data": {
    "email_id": "msg_9w2k7c1x0d4e5f6g",
    "event_id": "evt_7d3k9s0a2m5n8b1c",
    "recipient": "maria@company.com",
    "provider": "other",
    "mx": "mx.company.com",
    "smtp_code": "550 5.1.1",
    "smtp_response": "550 5.1.1 <maria@company.com>: Recipient address rejected: User unknown",
    "explanation": "The mailbox does not exist. The address was added to the suppression list.",
    "tags": { "type": "order" },
    "metadata": { "order_id": "1042" }
  }
}

webhook-id is the event ID and stays the same on retries: use it to ignore duplicates.

On clicked, data.url carries the original link; on opened, data.machine is true when the open was automatic (privacy protection). These go on the first open and the first click of each link only; repeats show as count in the timeline. See Open and click tracking.

Verify the signature#

Always verify before trusting the payload. The signature is an HMAC-SHA256 of webhook-id.webhook-timestamp.body, keyed with the Base64-decoded secret (without the whsec_ prefix). Also reject messages older than 5 minutes, to prevent replays.

Use the raw body, exactly as received. If your framework already parsed it into JSON, the signature will not match.

Node.js (Express)
import crypto from "node:crypto";
import express from "express";

function verifyWebhook(rawBody, headers, secret) {
  const id = headers["webhook-id"];
  const timestamp = headers["webhook-timestamp"];
  const signatures = headers["webhook-signature"];
  if (!id || !timestamp || !signatures) throw new Error("missing headers");
  if (Math.abs(Date.now() / 1000 - Number(timestamp)) > 300) throw new Error("timestamp too old");

  const key = Buffer.from(secret.replace(/^whsec_/, ""), "base64");
  const expected = crypto.createHmac("sha256", key).update(`${id}.${timestamp}.${rawBody}`).digest("base64");

  const valid = signatures.split(" ").some((entry) => {
    const [version, signature] = entry.split(",");
    return (
      version === "v1" &&
      signature?.length === expected.length &&
      crypto.timingSafeEqual(Buffer.from(signature), Buffer.from(expected))
    );
  });
  if (!valid) throw new Error("invalid signature");
  return JSON.parse(rawBody);
}

const app = express();
app.post("/webhooks/couryo", express.raw({ type: "application/json" }), (req, res) => {
  let event;
  try {
    event = verifyWebhook(req.body.toString("utf8"), req.headers, process.env.COURYO_WEBHOOK_SECRET);
  } catch {
    return res.sendStatus(400);
  }
  res.sendStatus(200); // answer fast; process later (queue, job)
  console.log(event.type, event.data.email_id);
});
PHP
function verify_webhook(string $body, array $headers, string $secret): array
{
    $id = $headers['webhook-id'] ?? '';
    $timestamp = $headers['webhook-timestamp'] ?? '';
    $signatures = $headers['webhook-signature'] ?? '';
    if ($id === '' || $timestamp === '' || $signatures === '') {
        throw new RuntimeException('missing headers');
    }
    if (abs(time() - (int) $timestamp) > 300) {
        throw new RuntimeException('timestamp too old');
    }

    $key = base64_decode(preg_replace('/^whsec_/', '', $secret));
    $expected = base64_encode(hash_hmac('sha256', "{$id}.{$timestamp}.{$body}", $key, true));

    foreach (explode(' ', $signatures) as $entry) {
        [$version, $signature] = array_pad(explode(',', $entry, 2), 2, '');
        if ($version === 'v1' && hash_equals($expected, $signature)) {
            return json_decode($body, true);
        }
    }
    throw new RuntimeException('invalid signature');
}

$body = file_get_contents('php://input');
$headers = array_change_key_case(getallheaders(), CASE_LOWER);
try {
    $event = verify_webhook($body, $headers, getenv('COURYO_WEBHOOK_SECRET'));
} catch (RuntimeException $e) {
    http_response_code(400);
    exit;
}
http_response_code(200);
Python
import base64
import hashlib
import hmac
import json
import time


def verify_webhook(body: bytes, headers, secret: str) -> dict:
    msg_id = headers.get("webhook-id")
    timestamp = headers.get("webhook-timestamp")
    signatures = headers.get("webhook-signature")
    if not (msg_id and timestamp and signatures):
        raise ValueError("missing headers")
    if abs(time.time() - int(timestamp)) > 300:
        raise ValueError("timestamp too old")

    key = base64.b64decode(secret.removeprefix("whsec_"))
    signed = f"{msg_id}.{timestamp}.".encode() + body
    expected = base64.b64encode(hmac.new(key, signed, hashlib.sha256).digest()).decode()

    for entry in signatures.split(" "):
        version, _, signature = entry.partition(",")
        if version == "v1" and hmac.compare_digest(signature, expected):
            return json.loads(body)
    raise ValueError("invalid signature")

The official Standard Webhooks libraries (for Node, PHP, Python, Go, Ruby and more) also work with Couryo's secret.

Retries#

  • Reply with any 2xx status to acknowledge. Reply fast and process later, in a queue.
  • Without a 2xx (or with no answer within 15 seconds), Couryo retries after 30 s, 2 min, 10 min, 30 min, 1 h, 2 h, 4 h, 8 h, 12 h, 16 h and 24 h: 12 attempts over about 3 days.
  • The dashboard shows each webhook's last 100 attempts, with your server's status and response, and has a button to resend right away.
  • Missed events? List everything at GET /v1/events.

Available events#

accepted, queued, sent, delivered, deferred, bounced, complained, opened, clicked, suppressed and failed. What each one means is in Events and timeline.

email.received: an email arrived on a receiving domain (Pro plans and above). The body carries the received email in data; see Receiving email.

Unsubscribes, topics and suppression#

So your system learns when someone leaves through Couryo, without polling the API:

Event When
contact.unsubscribed the person left every marketing email of the project. data.source says how: link (footer link, confirmed on the page), one_click (the mailbox provider's unsubscribe button, RFC 8058), preferences_page ("Leave all" on the preferences page) or reply (a reply asking to leave, read by the inbound triage)
contact.topic_changed the person (or you) changed the topics. Only sent when something really changed. source: preferences_page, api, dashboard or mcp
suppression.created an address entered the suppression list, with reason, stream and source (bounce, complaint, link, one_click, preferences_page, reply, api, dashboard)
suppression.deleted an address left the list (one entry per reason and stream), with source (api, dashboard, mcp or support)
contact.unsubscribed
{
  "type": "contact.unsubscribed",
  "timestamp": "2026-10-12T14:03:11Z",
  "data": {
    "event_id": "evt_2k8d0s1a9m3n7b5c",
    "email": "ana@example.com",
    "contact_id": "con_8f2k1s9d0a7m3n5b",
    "stream": "marketing",
    "source": "one_click",
    "email_id": "msg_9w2k7c1x0d4e5f6g",
    "campaign_id": "cmp_1a2b3c4d5e6f7g8h"
  }
}
contact.topic_changed
{
  "type": "contact.topic_changed",
  "timestamp": "2026-10-12T14:05:40Z",
  "data": {
    "event_id": "evt_5n7b1c2k8d0s9a3m",
    "email": "ana@example.com",
    "contact_id": "con_8f2k1s9d0a7m3n5b",
    "source": "preferences_page",
    "changes": [{ "key": "offers", "subscribed": false }],
    "topics": { "newsletter": true, "offers": false }
  }
}
suppression.created
{
  "type": "suppression.created",
  "timestamp": "2026-10-12T14:03:11Z",
  "data": {
    "event_id": "evt_0a9m3n5b8f2k1s7d",
    "email": "ana@example.com",
    "reason": "unsubscribe",
    "stream": "marketing",
    "source": "one_click",
    "email_id": "msg_9w2k7c1x0d4e5f6g"
  }
}
  • contact_id is null when the address is not a contact of the project. email_id and campaign_id come when the link used carried the email.
  • An unsubscribe fires both events: contact.unsubscribed and suppression.created (with reason: unsubscribe). Subscribe to what makes sense for you.
  • Same signature, retries and history as the other events. These events are not in GET /v1/events; to sync by cron, use GET /v1/suppressions?since=.

Project marketing pace#

When more than 2% of a project's sends in the last 7 days bounce as missing addresses (with at least 100 sends and 5 bounces), that project's marketing moves to a reduced pace: half of the week's average marketing day, at least 50 a day. Transactional email does not change. The pace comes back on its own when the 7-day rate falls under 1.5%. It is a warning before the project pause, which only comes above 3%.

Event When
project.marketing_throttled the project's marketing moved to the reduced pace, with bounce_rate_7d, sent_7d, hard_bounces_7d and daily_marketing_cap
project.marketing_restored the pace is back to normal (daily_marketing_cap: null)

While the pace is reduced, a marketing send above the day's cap gets daily_limit_reached with param: "project"; campaigns and sequences wait for the next day on their own.

Through MCP#

Through the MCP server: list_webhooks (scope read), create_webhook (scope admin; the secret appears only in the response) and test_webhook (scope admin; sends a signed test event and shows your server's response).