API BCE webhooks: seguir los cambios de empresas belgas
Webhooks de API BCE: recibe un evento firmado con HMAC en cuanto una empresa seguida cambia en la BCE. Creación, contenido, verificación y reintentos.
Webhooks push changes to you instead of you polling. Subscribe a webhook to one or more enterprises and CompanyBelgium POSTs a signed event to your URL whenever a watched record changes. You create and manage them through the Webhooks API.
How it works#
- Create a webhook with a target
urland the entity numbers to watch. - Store the
hmacSecretreturned at creation: it is shown only once. - We POST a JSON event to your URL on every change; respond with
2xxquickly to acknowledge it.
Event payload#
{
"event": "update",
"entityNumber": "1033022383",
"entityType": "enterprise",
"data": "...",
"timestamp": "..."
}Verify the signature#
Every delivery carries an X-CompanyBelgium-Signature header of the form sha256=<hex>: the HMAC-SHA256 of <timestamp>.<raw body>, keyed with your webhook secret, where the timestamp is the X-CompanyBelgium-Timestamp header (Unix milliseconds). Recompute it and compare in constant time before trusting the event; rejecting timestamps older than 5 minutes protects against replays.
import crypto from "node:crypto";
// Express handler: needs the RAW request body
export function handleWebhook(req, res) {
const header = req.header("X-CompanyBelgium-Signature"); // "sha256=<hex>"
const timestamp = req.header("X-CompanyBelgium-Timestamp"); // Unix milliseconds
const signature = (header || "").replace(/^sha256=/, "");
const expected = crypto
.createHmac("sha256", process.env.WEBHOOK_SECRET)
.update(`${timestamp}.${req.rawBody}`)
.digest("hex");
const ok = signature.length === expected.length &&
crypto.timingSafeEqual(Buffer.from(signature), Buffer.from(expected));
if (!ok) return res.status(401).end();
const event = JSON.parse(req.rawBody);
// ... process event, then ack quickly
res.status(200).end();
}Retries & delivery log#
A delivery that gets a 5xx, a network error or no answer within 10 seconds is retried up to 3 times. The most recent attempts are available from the delivery-log endpoint, and you can send a test event at any time.
Treat the HMAC secret like a password. If it leaks, rotate it from the Webhooks API: the old secret stops working immediately.
Create a webhook#
curl -X POST https://companybelgium.be/api/v2/webhook \
-H "X-API-Key: $API_BCE_KEY" -H "X-API-Secret: $API_BCE_SECRET" \
-H "Content-Type: application/json" \
-d '{
"name": "Prod listener",
"url": "https://example.be/hooks/bce",
"entityNumbers": ["1033.022.383"]
}'Cuándo usar los webhooks de API BCE#
Los webhooks sustituyen las consultas periódicas cuando sigues un conjunto conocido de empresas. Un caso típico es la monitorización de proveedores o de clientes con crédito abierto. En vez de consultar cada ficha cada día, recibes un evento solo cuando algo cambia. Así ahorras cuota y reaccionas antes. Ten en cuenta que los webhooks forman parte del plan API Pro.
Por ejemplo, un equipo financiero suscribe a sus clientes principales. Cuando llega un evento, su sistema vuelve a leer la ficha y comprueba el estado y la situación jurídica. Luego alerta al responsable si aparece una quiebra.
Diseñar un receptor fiable#
- Responde con un 2xx lo antes posible y procesa el evento en segundo plano.
- Verifica la firma
X-CompanyBelgium-Signaturecon una comparación en tiempo constante. - Rechaza los eventos cuyo
X-CompanyBelgium-Timestamptenga más de 5 minutos. - Haz tu tratamiento idempotente: un reintento puede entregar el mismo evento otra vez.
- Calcula el HMAC sobre el cuerpo bruto, antes de cualquier parseo JSON.
Errores frecuentes#
El fallo más común es un receptor lento. Si no respondes en 10 segundos, la entrega cuenta como fallida y se reintenta hasta 3 veces. Por eso no hagas llamadas pesadas antes de responder. Otro error es perder el secreto HMAC: solo se muestra una vez, al crear el webhook. Además, los webhooks aún no existen en modo de prueba. Por tanto, usa la entrega de prueba de la API de webhooks para validar tu endpoint.
Consejos para producción
En producción, separa la recepción del tratamiento. Primero, tu endpoint verifica la firma, guarda el evento en una cola y responde. Luego un proceso aparte lee la cola y actualiza tus datos. Así un pico de eventos no bloquea tu receptor. Además, registra el entityNumber y el timestamp de cada evento para detectar duplicados. Por último, revisa el registro de entregas tras cada despliegue, porque un cambio de ruta en tu servidor puede romper la recepción sin que lo notes.
Preguntas frecuentes sobre API BCE y los webhooks#
¿Qué contiene un evento?
El tipo de evento, el número de la entidad, su tipo (empresa o establecimiento), los datos y un timestamp. Si necesitas la ficha completa, consúltala después de recibir el evento.
¿Cómo veo si una entrega falló?
Consulta el registro de entregas del webhook. Muestra los intentos más recientes con el código de respuesta, los reintentos y el mensaje de error.
¿Qué hago si el secreto de mi webhook API BCE se filtra?
Renuévalo desde la API de webhooks. El secreto anterior deja de ser válido de inmediato, así que despliega el nuevo enseguida.