Webhooks

Avisos firmados (Clobepay-Signature) con reintentos, rotación de secreto y reenvío.

Clobepay te avisa por HTTPS cuando cambia el estado de un payin, una transferencia o una verificación de tu comercio. Cada aviso va firmado con el secreto de tu endpoint.

Entrega de un webhook
  • pending → in_flight: HTTPS a tu URL
  • pending → abandoned: Endpoint deshabilitado
  • in_flight → succeeded: 2xx
  • in_flight → pending: Error o timeout (reintento)
  • in_flight → failed: Sin más reintentos

Alta del endpoint

  • Desde el panel (Configuración de integración) o por API con POST /webhook-endpoints.
  • Solo https:// en el puerto 443, sin usuario ni contraseña en la URL y sin redirecciones.
  • No se permiten direcciones privadas o internas: la API responde 422 url_not_allowed.
  • Hasta 5 endpoints por comercio y entorno. Puedes suscribir eventos concretos o todos.
  • Al crearlo recibes el secreto (whsec_…) una sola vez. Guárdalo en tu servidor.
curl -X POST "$CLOBEPAY_API_BASE/webhook-endpoints" \  -H "Authorization: Bearer $CLOBEPAY_API_KEY" \  -H "Content-Type: application/json" \  -d '{"url":"https://api.comercioatlas.mx/webhooks/clobepay","eventTypes":["payin.settled","payin.expired","payout.completed"]}'

Respuesta

HTTP 201
{
  "id": "we_4Lq8Zt2Rk9Xw1Vb7Nc3Hd6",
  "url": "https://api.comercioatlas.mx/webhooks/clobepay",
  "eventTypes": [
    "payin.settled",
    "payout.completed"
  ],
  "status": "enabled",
  "secret": "whsec_AtCJBGiga3h…"
}

Cabeceras y firma

Cabeceras de cada entrega
Clobepay-Signature: t=1763445600,v1=5f2b…(hex sha256)[,v1=<firma con el secreto anterior | signature with the previous secret>]
Clobepay-Event-Id: evt_iS50IM4GXDwNpq1EZedhRJ
Clobepay-Event-Type: payin.settled
Clobepay-Delivery-Id: whd_7Qa…
Clobepay-Webhook-Version: 2026-11-17
User-Agent: Clobepay-Webhooks/1.0
Content-Type: application/json

v1 = hex(HMAC-SHA256(secreto, t + "." + cuerpo_crudo)). Para verificar:

  1. Lee el cuerpo crudo, antes de parsear el JSON.
  2. Toma t y todas las firmas v1 de Clobepay-Signature.
  3. Rechaza si |ahora − t| > 300 segundos.
  4. Calcula la firma con tu secreto y compárala en tiempo constante con cada v1; basta una coincidencia.
Node.js · verificar la firma
// Node 18+. Usa el cuerpo CRUDO (Buffer) / use the RAW body (Buffer).
import crypto from 'node:crypto';

export function verifyClobepaySignature(rawBody, header, secret, toleranceSec = 300) {
  const t = Number(/(?:^|,)t=(\d+)/.exec(header ?? '')?.[1]);
  const signatures = [...(header ?? '').matchAll(/v1=([0-9a-f]{64})/g)].map((m) => m[1]);
  if (!t || signatures.length === 0) return false;
  if (Math.abs(Date.now() / 1000 - t) > toleranceSec) return false;

  const expected = crypto
    .createHmac('sha256', secret)
    .update(`${t}.`)
    .update(rawBody)
    .digest();
  // Durante una rotación llegan dos v1: basta con que una coincida.
  // During a rotation two v1 values arrive: one match is enough.
  return signatures.some((sig) => crypto.timingSafeEqual(Buffer.from(sig, 'hex'), expected));
}

Python · verificar la firma
# Python 3. Usa el cuerpo CRUDO (bytes) / use the RAW body (bytes).
import hashlib, hmac, re, time

def verify_clobepay_signature(raw_body: bytes, header: str, secret: str, tolerance: int = 300) -> bool:
    m = re.search(r"(?:^|,)t=(\d+)", header or "")
    signatures = re.findall(r"v1=([0-9a-f]{64})", header or "")
    if not m or not signatures:
        return False
    t = int(m.group(1))
    if abs(time.time() - t) > tolerance:
        return False
    expected = hmac.new(secret.encode(), str(t).encode() + b"." + raw_body, hashlib.sha256).hexdigest()
    # Durante una rotación llegan dos v1 / during a rotation two v1 values arrive.
    return any(hmac.compare_digest(sig, expected) for sig in signatures)

Node.js (Express) · recibir el evento
// Express: responde 2xx rápido, deduplica por Clobepay-Event-Id y procesa después.
// Express: respond 2xx fast, deduplicate by Clobepay-Event-Id and process later.
import express from 'express';
import { verifyClobepaySignature } from './verify-clobepay.js';

const app = express();
app.post('/webhooks/clobepay', express.raw({ type: 'application/json' }), async (req, res) => {
  const ok = verifyClobepaySignature(
    req.body,
    req.get('Clobepay-Signature'),
    process.env.CLOBEPAY_WEBHOOK_SECRET,
  );
  if (!ok) return res.sendStatus(400);

  const isNew = await saveEventIdIfNew(req.get('Clobepay-Event-Id')); // índice único / unique index
  if (isNew) await enqueue(JSON.parse(req.body.toString('utf8')));
  res.sendStatus(200);
});

cURL · simular una entrega a tu endpoint
# Simula una entrega firmada contra TU endpoint (secreto del entorno de pruebas).
# Simulate a signed delivery to YOUR endpoint (test-environment secret).
WHSEC='whsec_solo_para_pruebas_locales'
T=$(date +%s)
BODY='{"id":"evt_test","type":"webhook_endpoint.test","data":{"object":{}}}'
SIG=$(printf '%s.%s' "$T" "$BODY" | openssl dgst -sha256 -hmac "$WHSEC" | awk '{print $NF}')
curl -X POST "https://api.comercioatlas.mx/webhooks/clobepay" \
  -H "Clobepay-Signature: t=$T,v1=$SIG" \
  -H "Clobepay-Event-Id: evt_test" \
  -H "Clobepay-Event-Type: webhook_endpoint.test" \
  -H "Content-Type: application/json" \
  -d "$BODY"

Sobre del evento

payin.settled
{
  "id": "evt_iS50IM4GXDwNpq1EZedhRJ",
  "type": "payin.settled",
  "apiVersion": "2026-11-17",
  "createdAt": "2026-11-18T06:00:00Z",
  "merchantId": "MID000847",
  "livemode": false,
  "data": {
    "object": {
      "object": "payin",
      "id": "pi_3Kx9mQ2vR8wL0tYbA4nC1e",
      "status": "settled",
      "source": "payment_link",
      "amount": "50.00",
      "asset": "USDT",
      "paymentLinkId": "7c2e1a4b-9d83-4f21-a6b0-2e8c91f04d17",
      "orderReference": "10042",
      "metadata": { "cart_id": "c_77" },
      "settledAt": "2026-11-18T06:00:00Z",
      "availableAt": "2026-11-18T06:00:00Z"
    },
    "previousAttributes": { "status": "pending" }
  }
}

Sin datos personales del pagador ni del firmante; montos como texto decimal. Solo recibes eventos de tu propio comercio.

Catálogo de eventos
RecursoEventos
Link de pagopayment_link.created, payment_link.expired
Payinpayin.created, payin.settled, payin.expired, payin.failed, payin.refunded
Cuenta de depósitodeposit_account.created
Transferenciapayout.created, payout.pending_approval, payout.approved, payout.rejected, payout.processing, payout.completed, payout.failed
KYC/KYBverification.submitted, verification.document_validated, verification.liveness_required, verification.liveness_completed, verification.changes_requested, verification.approved, verification.rejected
Pruebawebhook_endpoint.test

Entrega y reintentos

  • Éxito = cualquier respuesta 2xx en menos de 10 segundos. Responde rápido y procesa en segundo plano.
  • Entrega al menos una vez: deduplica por Clobepay-Event-Id, que no cambia entre reintentos (Clobepay-Delivery-Id sí cambia).
  • No dependas del orden de llegada: ante la duda, consulta el recurso.
Calendario de reintentos
IntentoEspera tras el anterior
1inmediato
21 min
35 min
430 min
52 h
66 h
712 h
824 h
  • Con variación aleatoria de ±20 %; en total unas 45 horas. Tras el 8.º fallo la entrega queda failed y puedes reenviarla.
  • Si respondes 410 Gone, la entrega queda failed de inmediato.
  • Si todas las entregas fallan durante 72 horas seguidas, el endpoint se desactiva solo y te avisamos en el panel.

Rotación del secreto

POST /webhook-endpoints/{id}/rotate-secret genera un secreto nuevo (se muestra una vez). Durante el periodo de gracia (expirePreviousInHours, de 0 a 72; 24 por defecto) cada entrega lleva dos firmas v1: una con el secreto nuevo y otra con el anterior. Despliega el secreto nuevo antes de que termine la gracia.

POST/webhook-endpoints/{endpointId}/rotate-secret
curl -X POST "$CLOBEPAY_API_BASE/webhook-endpoints/we_4Lq8Zt2Rk9Xw1Vb7Nc3Hd6/rotate-secret" \  -H "Authorization: Bearer $CLOBEPAY_API_KEY" \  -H "Content-Type: application/json" \  -d '{"expirePreviousInHours":24}'

Respuesta

HTTP 200
Nuevo secreto (solo en esta respuesta).

Bitácora, prueba y reenvío

  • POST /webhook-endpoints
  • GET /webhook-endpoints
  • PATCH /webhook-endpoints/{id}
  • DELETE /webhook-endpoints/{id}
  • POST /webhook-endpoints/{id}/rotate-secret
  • POST /webhook-endpoints/{id}/test
  • GET /webhook-endpoints/{id}/deliveries
  • GET /webhook-deliveries/{id}
  • POST /webhook-deliveries/{id}/resend
  • POST /webhook-endpoints/{id}/resend-failed

El reenvío masivo admite hasta 500 eventos por llamada. Las entregas se conservan 90 días.