Conceptos

Recibir webhooks

Comprueba que cada entrega viene de Flavio, responde rápido y gestiona las repeticiones.

Ver en Markdown

Flavio envía cada evento de una cuenta a la URL de sus webhooks (Crear un webhook) como un POST con el evento en JSON, el sobre que describe Eventos:

http
POST /flavio HTTP/1.1
Host: hooks.example-builder.com
Content-Type: application/json
User-Agent: Flavio-Webhooks/1.0
X-Flavio-Signature: t=1764500000,v1=5f2c8e0b9d4a7c1e3f6b8a0d2c4e6f8a1b3d5f7a9c0e2b4d6f8a0c2e4b6d8f0a

{"id":"2b8f41d0c9e44a1b8c6d3e0f1a2b3c4d5e6f7081","type":"plan.ready","created_at":"2026-11-04T11:04:52Z","account":"{uuid}","source":"flavio","l1":"Plan ready","l2":"Flavio wrote version 3 of the plan after the goals changed.","details":{"plan_version":3}}

Comprueba la firma

  1. Toma t y v1 de la cabecera X-Flavio-Signature.
  2. Calcula el HMAC-SHA256, en hexadecimal, de t, un punto y el cuerpo tal como llegó, con el secret del webhook. Si antes interpretas el JSON y lo vuelves a escribir, el cuerpo cambia.
  3. Compáralo con v1 en tiempo constante, y rechaza un t de hace más de cinco minutos.
js
// Node.js (Express): read the body raw, as it arrived.
import crypto from "node:crypto";

app.post("/flavio", express.raw({ type: "application/json" }), (req, res) => {
  const header = req.get("X-Flavio-Signature") ?? "";
  const { t, v1 } = Object.fromEntries(header.split(",").map((part) => part.split("=")));
  const expected = crypto
    .createHmac("sha256", process.env.FLAVIO_WEBHOOK_SECRET)
    .update(`${t}.${req.body}`)
    .digest("hex");
  const fresh = Math.abs(Date.now() / 1000 - Number(t)) < 300;
  const valid =
    v1?.length === expected.length &&
    crypto.timingSafeEqual(Buffer.from(v1), Buffer.from(expected));
  if (!fresh || !valid) return res.sendStatus(400);

  res.sendStatus(204);
  queue.add(JSON.parse(req.body)); // The work, afterwards.
});
python
# Python (Flask)
import hashlib, hmac, json, os, time
from flask import request

@app.post("/flavio")
def flavio():
    parts = dict(p.split("=", 1) for p in request.headers.get("X-Flavio-Signature", "").split(","))
    body = request.get_data()  # The body raw, as it arrived.
    expected = hmac.new(os.environ["FLAVIO_WEBHOOK_SECRET"].encode(),
                        parts.get("t", "").encode() + b"." + body, hashlib.sha256).hexdigest()
    fresh = abs(time.time() - int(parts.get("t", "0"))) < 300
    if not fresh or not hmac.compare_digest(parts.get("v1", ""), expected):
        return "", 400
    queue.put(json.loads(body))  # The work, afterwards.
    return "", 204
php
<?php
// PHP
$body = file_get_contents("php://input"); // The body raw, as it arrived.
parse_str(str_replace(",", "&", $_SERVER["HTTP_X_FLAVIO_SIGNATURE"] ?? ""), $parts);
$expected = hash_hmac("sha256", ($parts["t"] ?? "") . "." . $body, getenv("FLAVIO_WEBHOOK_SECRET"));
$fresh = abs(time() - (int) ($parts["t"] ?? 0)) < 300;
if (!$fresh || !hash_equals($expected, $parts["v1"] ?? "")) {
    http_response_code(400);
    exit;
}
http_response_code(204);
enqueue(json_decode($body, true)); // The work, afterwards.

Responde rápido, trabaja después

Responde con un 2xx en menos de 10 segundos, antes de hacer nada lento: guarda el evento y trabájalo después. Cualquier otra respuesta, o ninguna, se reintenta con esperas cada vez más largas durante 24 horas; después, el evento no se vuelve a enviar. Todo está también en el historial de la cuenta.

Repeticiones y orden

El mismo evento puede llegar dos veces: guarda el id de los que ya has gestionado y sáltate la repetición. Los eventos pueden llegar desordenados: ordénalos por created_at. Un evento lleva identificadores, no los objetos: para saber cómo está algo ahora, léelo.

Pruébalo

Probar un webhook envía un evento webhook.test en menos de un minuto. Cómo fue se ve en last_status y last_error del webhook.