Documentation · Webhooks

Webhooks

Des événements signés quand une liste se termine, quand les crédits baissent ou quand des résultats d'envoi arrivent. Markdown (en anglais)

Ajoutez un point d'accès dans le tableau de bord (Webhooks) ou avec POST https://api.verifyngn.com/v1/webhooks {"url": "https://...", "events": [...]}. Le secret de signature n'est affiché qu'une fois.

curl -s https://api.verifyngn.com/v1/webhooks \
  -H "Authorization: Bearer $VERIFY_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"url": "https://example.com/verify-hook", "events": ["list.completed", "credits.low"]}'
const API = "https://api.verifyngn.com/v1";
const headers = { Authorization: `Bearer ${process.env.VERIFY_API_KEY}`, "Content-Type": "application/json" };

const res = await fetch(`${API}/webhooks`, {
  method: "POST",
  headers,
  body: JSON.stringify({ url: "https://example.com/verify-hook", events: ["list.completed", "credits.low"] }),
});
const hook = await res.json();
console.log(hook.id, hook.secret); // keep the secret: it is shown only once
import os, requests

API = "https://api.verifyngn.com/v1"
headers = {"Authorization": f"Bearer {os.environ['VERIFY_API_KEY']}"}

res = requests.post(f"{API}/webhooks", headers=headers, timeout=30,
                    json={"url": "https://example.com/verify-hook", "events": ["list.completed", "credits.low"]})
res.raise_for_status()
hook = res.json()
print(hook["id"], hook["secret"])  # keep the secret: it is shown only once

Événements : list.completed, list.failed, credits.low, feedback.received. Chacun est un POST avec le JSON {"id", "type", "created_at", "data"} et les en-têtes Verify-Event-Id et Verify-Event-Type. data vaut {"list"} pour les événements de liste, {"balance", "threshold"} pour credits.low et {"email", "outcome", "at"} pour feedback.received.

Signatures

Chaque requête comporte Verify-Signature: t=<unix seconds>,v1=<hex>, où v1 est le HMAC-SHA256 de "<t>.<raw body>" avec votre secret. Vérifiez-la sur le corps brut, avant d'analyser le JSON, et refusez tout ce qui date de plus de 5 minutes (JavaScript et Python) :

import { createHmac, timingSafeEqual } from "node:crypto";

// rawBody: the request body exactly as received, before JSON parsing.
export function verifySignature(secret, rawBody, header, toleranceSeconds = 300) {
  const parts = Object.fromEntries(String(header ?? "").split(",").map((p) => p.trim().split("=")));
  const t = Number(parts.t);
  if (!t || !parts.v1 || Math.abs(Date.now() / 1000 - t) > toleranceSeconds) return false;
  const want = createHmac("sha256", secret).update(`${t}.${rawBody}`).digest("hex");
  return want.length === parts.v1.length && timingSafeEqual(Buffer.from(want), Buffer.from(parts.v1));
}

// Express: app.post("/verify-hook", express.raw({ type: "application/json" }), (req, res) => {
//   if (!verifySignature(process.env.VERIFY_WEBHOOK_SECRET, req.body.toString("utf8"), req.get("Verify-Signature"))) return res.sendStatus(400);
//   const event = JSON.parse(req.body); // { id, type, created_at, data }
//   res.sendStatus(200);
// });
import hashlib, hmac, time

# raw_body: the request body exactly as received (bytes), before JSON parsing.
def verify_signature(secret: str, raw_body: bytes, header: str, tolerance_seconds: int = 300) -> bool:
    parts = dict(p.strip().split("=", 1) for p in (header or "").split(",") if "=" in p)
    try:
        t = int(parts["t"])
    except (KeyError, ValueError):
        return False
    if "v1" not in parts or abs(time.time() - t) > tolerance_seconds:
        return False
    want = hmac.new(secret.encode(), f"{t}.".encode() + raw_body, hashlib.sha256).hexdigest()
    return hmac.compare_digest(want, parts["v1"])

# Flask:
# @app.post("/verify-hook")
# def hook():
#     if not verify_signature(os.environ["VERIFY_WEBHOOK_SECRET"], request.get_data(), request.headers.get("Verify-Signature")):
#         abort(400)
#     event = request.get_json()  # {"id", "type", "created_at", "data"}
#     return "", 200

Nouvelles tentatives

Répondez avec n'importe quel code 2xx en moins de 10 secondes. Sinon, nous réessayons après 1 minute, 5 minutes, 30 minutes, 2, 6, 12 et 24 heures, puis nous arrêtons.