Webhooks y Eventos

ENTREGA DE EVENTOS MODELO DIDIT

14 + 1 EventosHMAC-SHA256 V2Ventana anti-replay 300s

Webhooks Firmados y API de Gestión

Firmado HMAC-SHA256 sobre JSON canónico, ventana anti-replay de 300 segundos, rotación de secretos sin caída de 24 horas, protección SSRF y reintentos escalonados en los 14 eventos del ciclo de vida.

Los 7 endpoints de gestión de Webhooks requieren Bearer JWT (Authorization: Bearer <jwt>). Las entregas salientes van firmadas con HMAC-SHA256.

01 · ENCABEZADOS DE FIRMA Y ANTI-REPLAY

Encabezados enviados en cada POST saliente

EncabezadoConstrucción / FormatoRegla de Verificación
X-TimestampUnix epoch seconds (string)Ventana anti-replay: |nowEpochSec - Number(X-Timestamp)| <= 300 segundos (SIGNATURE_REPLAY_TOLERANCE_SEC = 300).
X-Signature-V2HMAC-SHA256(secret, canonicalJson(payload)) [hex]Firma principal estilo Didit calculada sobre JSON compacto con llaves ordenadas recursivamente y Unicode preservado sin escapes.
X-Signature-V2-PreviousHMAC-SHA256(previousSecret, canonicalJson(payload)) [hex]Enviado durante la ventana de gracia de 24 horas tras rotar secreto (previousSecretExpiresAt > now).
X-Signature-SimpleHMAC-SHA256(secret, "${timestamp}:${entityId}:${status}:${webhook_type}") [hex]entityId se resuelve como order_id ?? pack_order_id ?? data?.webhook_id ?? "" junto con el X-Timestamp del intento.
X-SignatureHMAC-SHA256(secret, rawBodyUtf8) [hex]HMAC exacto sobre los bytes UTF-8 crudos del cuerpo HTTP (JSON.stringify(effectivePayload)).

JSON Canónico y Precedencia de Verificación

  • 1. Rechaza de inmediato si falta el secreto (missing_secret) o si X-Timestamp no es entero válido (invalid_timestamp) o supera +/- 300 segundos (timestamp_expired).
  • 2. Exige al menos un encabezado de firma (X-Signature-V2, X-Signature-V2-Previous, X-Signature-Simple o X-Signature), si no retorna missing_signature.
  • 3. Si X-Signature-V2 está presente, verifícalo con comparación en tiempo constante (timingSafeEqual) y verifica también X-Signature / X-Signature-Simple si están presentes (matchedHeader: "x-signature-v2").
  • 4. Si V2 no está presente, valida X-Signature (matchedHeader: "x-signature") o X-Signature-Simple (matchedHeader: "x-signature-simple").
  • 5. Durante la rotación de secreto, si falla el secreto activo, valida X-Signature-V2-Previous (y previousSecret) para evitar pérdida de eventos en la transición.

Ejemplos de Verificación de Firma (Node.js, Python, cURL)

import crypto from "node:crypto";

function canonicalJson(value: unknown, seen = new WeakSet<object>()): string {
  if (value === null || value === undefined) return "null";
  if (typeof value !== "object") return JSON.stringify(value);
  if (typeof (value as { toJSON?: () => unknown }).toJSON === "function") {
    return canonicalJson((value as { toJSON: () => unknown }).toJSON(), seen);
  }
  if (seen.has(value)) throw new Error("Circular reference");
  seen.add(value);
  try {
    if (Array.isArray(value)) {
      const items = value.map((el) =>
        el === undefined || typeof el === "function" || typeof el === "symbol"
          ? "null"
          : canonicalJson(el, seen),
      );
      return `[${items.join(",")}]`;
    }
    const entries = Object.entries(value as Record<string, unknown>)
      .filter(([, v]) => v !== undefined && typeof v !== "function" && typeof v !== "symbol")
      .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))
      .map(([k, v]) => `${JSON.stringify(k)}:${canonicalJson(v, seen)}`);
    return `{${entries.join(",")}}`;
  } finally {
    seen.delete(value);
  }
}

function safeHexEqual(a: string, b: string): boolean {
  const ba = Buffer.from(a.toLowerCase(), "utf8");
  const bb = Buffer.from(b.toLowerCase(), "utf8");
  return ba.length === bb.length && crypto.timingSafeEqual(ba, bb);
}

export function verifyVerifikWebhook(
  rawBody: string,
  headers: Record<string, string | string[] | undefined>,
  secret: string,
  previousSecret?: string,
): { valid: boolean; matchedHeader?: string; reason?: string } {
  const norm = Object.fromEntries(
    Object.entries(headers).map(([k, v]) => [
      k.toLowerCase(),
      Array.isArray(v) ? v[0] : v,
    ]),
  );

  const rawTs = norm["x-timestamp"];
  const ts = Number(rawTs);
  const nowSec = Math.floor(Date.now() / 1000);
  if (rawTs === undefined || rawTs.trim() === "" || !Number.isFinite(ts)) {
    return { valid: false, reason: "invalid_timestamp" };
  }
  if (Math.abs(nowSec - ts) > 300) {
    return { valid: false, reason: "timestamp_expired" };
  }

  const sigV2 = norm["x-signature-v2"];
  const sigV2Prev = norm["x-signature-v2-previous"];
  if (!sigV2 && !sigV2Prev) {
    return { valid: false, reason: "missing_signature" };
  }

  const secrets = [secret, previousSecret].filter((s): s is string => Boolean(s));
  if (secrets.length === 0) {
    return { valid: false, reason: "missing_secret" };
  }

  let payload: unknown;
  try {
    payload = JSON.parse(rawBody);
  } catch {
    return { valid: false, reason: "invalid_json_body" };
  }

  const canonical = canonicalJson(payload);
  const signV2 = (key: string) =>
    crypto.createHmac("sha256", key).update(canonical, "utf8").digest("hex");

  if (sigV2) {
    for (const key of secrets) {
      if (safeHexEqual(sigV2, signV2(key))) {
        return { valid: true, matchedHeader: "x-signature-v2" };
      }
    }
  }

  if (sigV2Prev) {
    for (const key of secrets) {
      if (safeHexEqual(sigV2Prev, signV2(key))) {
        return { valid: true, matchedHeader: "x-signature-v2-previous" };
      }
    }
  }

  return { valid: false, reason: "signature_mismatch" };
}

02 · SOBRE DEL PAYLOAD

Estructura de evento alineada a Didit

{
  "event_id": "550e8400-e29b-41d4-a716-446655440000",
  "webhook_type": "order.completed",
  "status": "completed",
  "order_id": "674f8a9c2e1b4a0012c9d101",
  "pack_order_id": null,
  "product_code": "co_vehicle_full",
  "plate": "ABC123",
  "environment": "live",
  "is_sandbox": false,
  "external_ref_id": "crm-deal-42",
  "created_at": 1776333594,
  "timestamp": 1776333600,
  "data": {
    "orderId": "674f8a9c2e1b4a0012c9d101",
    "status": "completed",
    "productCode": "co_vehicle_full",
    "plate": "ABC123",
    "plateType": "car",
    "isSandbox": false,
    "sandboxScenario": null,
    "paymentMethod": "voucher",
    "creditsCharged": 0,
    "createdByChannel": "api",
    "externalRefId": "crm-deal-42",
    "pdfUrl": "https://cdn.verifik.co/reports-b2c/pdfs/abc123.pdf",
    "shareToken": "xYz987shareToken",
    "verificationHash": "A1B2C3D4E5F67890",
    "summary": { "healthScore": 100, "healthLabel": "Excelente" },
    "stepStates": []
  }
}

03 · CATÁLOGO DE EVENTOS

Los 14 Eventos de Ciclo de Vida + webhook.test + Comodín

webhook_typeEntidadEstado en sobreDisparadorCampos Adicionales en data
order.createdorder"pending_payment" | "completed" | "paid"Orden creada vía POST /orders (pending_payment en vivo, completed en sandbox) o POST /generate (paid en vivo).Campos base de _buildOrderPayloadData.
order.paidorder"paid"Pago confirmado por redención de voucher, aprobación Bold (webhook/reconciliación) o débito de créditos API en headless.Campos base de _buildOrderPayloadData (paymentMethod, creditsCharged).
order.runningorder"running"El ejecutor toma la orden pagada e inicia las consultas paralelas a RUNT, SIMIT, Fasecolda y fuentes regionales.Campos base de _buildOrderPayloadData.
order.completedorder"completed"Todos los pasos finalizaron con éxito (o Sandbox completado). En headless síncrono se emite tras generar PDF/enlace.order-executor: { stepStates }. headless: responsePayload completo (pdfUrl, shareUrl, shareToken, verificationHash, summary, stepStates, opcional composedReport).
order.partialorder"partial"El paso primario RUNT tuvo éxito, pero una o más fuentes secundarias fallaron temporalmente y quedaron en cola de reintento.order-executor: { stepStates, nextRetryAt }. headless: responsePayload completo.
order.updatedorder"completed" | "partial"Emitido al finalizar retryPartialOrder (por cron en segundo plano o por POST /orders/:id/retry).{ stepStates, nextRetryAt } combinado con los datos base de la orden.
order.failedorder"failed"Fallo al redimir voucher en headless, producto faltante o fallo en consulta primaria sobre órdenes pagadas con api_credits.{ errorCode } o { errorCode, errorMessage } además de refundReason cuando aplica.
order.refundedorder"refunded_as_voucher"Vehículo no hallado en RUNT (typo_plate_auto_refund) o fuente primaria caída (primary_source_unavailable_refund) en orden pagada con voucher/Bold.{ voucher: { credited, duplicate, productCode, balance, ledgerId } } + refundReason.
order.expiredorder"expired"El enlace de pago Bold pasó a EXPIRED vía webhook de Bold o POST /orders/:id/reconcile.Campos base de _buildOrderPayloadData.
order.pdf_exportedorder"completed" | "partial"Emitido cuando POST /orders/:id/pdf-url renderiza y almacena un nuevo PDF.{ pdfUrl, pdfByteLength, pdfGeneratedAt, lang }.
order.share_link_createdorder"completed" | "partial"Emitido cuando POST /orders/:id/share-link genera o rota un token público compartido.{ shareToken, shareUrl, isBranded, shareCreatedAt }.
order.share_link_revokedorder"completed" | "partial"Emitido cuando DELETE /orders/:id/share-link revoca el enlace compartido.{ shareRevokedAt }.
pack_order.paidpack_order"paid"Bold aprobó la compra de un paquete de vouchers (vía webhook Bold o POST /pack-orders/:id/reconcile).{ packOrderId, packCode, productCode, paidQuantity, totalCreditsGranted, priceCop, paymentMethod, voucherBalance, isResellerEligible: true }.
pack_order.expiredpack_order"expired"Bold reportó estado EXPIRED en un enlace de pago de paquete pendiente.Campos base de _buildPackOrderPayloadData.
webhook.testwebhook"test"Disparado manualmente con POST /webhooks/:id/test (un solo intento, is_sandbox: true, sin reintentos).{ webhook_id, message: "Verifik Reports test webhook ping" }.
order.createdorder
{"webhook_type":"order.created","status":"pending_payment","order_id":"674f...","data":{"orderId":"674f...","plate":"ABC123","productCode":"co_vehicle_full"}}
order.paidorder
{"webhook_type":"order.paid","status":"paid","order_id":"674f...","data":{"orderId":"674f...","paymentMethod":"PSE","creditsCharged":0}}
order.runningorder
{"webhook_type":"order.running","status":"running","order_id":"674f...","data":{"orderId":"674f...","status":"running","plate":"ABC123"}}
order.completedorder
{"webhook_type":"order.completed","status":"completed","order_id":"674f...","data":{"orderId":"674f...","pdfUrl":"https://cdn.verifik.co/...","verificationHash":"A1B2C3D4E5F67890"}}
order.partialorder
{"webhook_type":"order.partial","status":"partial","order_id":"674f...","data":{"orderId":"674f...","nextRetryAt":"2026-12-02T04:05:00.000Z","stepStates":[]}}
order.updatedorder
{"webhook_type":"order.updated","status":"completed","order_id":"674f...","data":{"orderId":"674f...","nextRetryAt":null,"stepStates":[]}}
order.failedorder
{"webhook_type":"order.failed","status":"failed","order_id":"674f...","data":{"orderId":"674f...","errorCode":"primary_source_unavailable"}}
order.refundedorder
{"webhook_type":"order.refunded","status":"refunded_as_voucher","order_id":"674f...","data":{"refundReason":"typo_plate_auto_refund","voucher":{"credited":true,"balance":1}}}
order.expiredorder
{"webhook_type":"order.expired","status":"expired","order_id":"674f...","data":{"orderId":"674f...","status":"expired"}}
order.pdf_exportedorder
{"webhook_type":"order.pdf_exported","status":"completed","order_id":"674f...","data":{"pdfUrl":"https://cdn.verifik.co/...","pdfByteLength":148230,"lang":"en"}}
order.share_link_createdorder
{"webhook_type":"order.share_link_created","status":"completed","order_id":"674f...","data":{"shareToken":"xYz987","shareUrl":"https://reports.verifik.co/r/xYz987","isBranded":true}}
order.share_link_revokedorder
{"webhook_type":"order.share_link_revoked","status":"completed","order_id":"674f...","data":{"shareRevokedAt":"2026-12-02T04:05:00.000Z"}}
pack_order.paidpack_order
{"webhook_type":"pack_order.paid","status":"paid","order_id":null,"pack_order_id":"674f...","data":{"packCode":"pack_full_10","voucherBalance":12,"isResellerEligible":true}}
pack_order.expiredpack_order
{"webhook_type":"pack_order.expired","status":"expired","order_id":null,"pack_order_id":"674f...","data":{"packCode":"pack_full_10","status":"expired"}}
webhook.testwebhook
{"webhook_type":"webhook.test","status":"test","order_id":null,"pack_order_id":null,"is_sandbox":true,"data":{"webhook_id":"674f...","message":"Verifik Reports test webhook ping"}}

04 · PROTECCIÓN SSRF, REINTENTOS Y ROTACIÓN

Endurecimiento de Entrega y Política de Reintentos

Protección SSRF y Límites de Transporte

  • Protocolos: https: obligatorio en producción (http: solo fuera de producción). Credenciales en URL (user:pass@) retornan 409:webhook_credentials_disallowed.
  • Hosts y CIDRs bloqueados: localhost, metadata.google.internal, *.local, *.internal, IPv4 privados/link-local/CGNAT (10.0.0.0/8, 100.64.0.0/10, 127.0.0.0/8, 169.254.0.0/16, 172.16.0.0/12, 192.168.0.0/16, etc.) e IPv6 (::1, fc00::/7, fe80::/10). El pinning DNS evita rebinding TOCTOU.
  • Transporte: DELIVERY_TIMEOUT_MS = 5000 (5 segundos) y maxRedirects: 0 (las respuestas 3xx nunca se siguen y se marcan fallidas).

Política de Reintentos, Persistencia y Deduplicación Ad-Hoc

  • Intentos y Backoff: MAX_DELIVERY_ATTEMPTS = 3 (1 inicial + 2 reintentos) con RETRY_BACKOFF_MS = [15_000, 60_000] (15s y 60s). event_id y created_at permanecen intactos entre reintentos mientras timestamp y X-Timestamp se actualizan.
  • Reintentables vs Terminales: Se reintenta ante HTTP 408, 429, >= 500 o timeouts de red. 3xx, otros 4xx (400, 401, 403, 404, 410) y errores SSRF fallan de inmediato. Recuperado por timers y cron runWebhookRetriesTick(); logs expiran en 30 días.
  • webhookUrl ad-hoc en POST /generate: Se normaliza y deduplica frente a webhooks registrados activos para evitar entregas duplicadas a la misma URL.

05 · API DE GESTIÓN DE WEBHOOKS

7 Endpoints para Registro, Rotación, Pruebas y Logs

MétodoEndpointAutenticaciónResumen
GET/v3/reports-b2c/webhooks

Listar Webhooks Registrados

Bearer JWTLista todos los endpoints webhook configurados en tu cuenta (el secreto se muestra enmascarado en secretPreview, ej. whsec_...a9f2).
POST/v3/reports-b2c/webhooks

Crear Endpoint Webhook

Bearer JWTRegistra un nuevo destino webhook validado contra SSRF (hasta 20 por cuenta) y retorna su secret (whsec_<48-hex>) una única vez.
PATCH/v3/reports-b2c/webhooks/:id

Actualizar Endpoint Webhook

Bearer JWTActualiza la URL destino (revalidada contra SSRF), lista de eventos suscritos, descripción o estado activo.
DELETE/v3/reports-b2c/webhooks/:id

Eliminar Endpoint Webhook

Bearer JWTElimina permanentemente un endpoint webhook registrado para detener futuros envíos de eventos.
POST/v3/reports-b2c/webhooks/:id/rotate-secret

Rotar Secreto de Firma

Bearer JWTGenera un nuevo secret (whsec_<48-hex>) manteniendo el anterior en previousSecret durante 24 horas (X-Signature-V2-Previous).
POST/v3/reports-b2c/webhooks/:id/test

Enviar Ping de Prueba Firmado

Bearer JWTEnvía de inmediato un ping firmado de un solo intento (maxAttempts: 1, is_sandbox: true) con webhook.test o cualquier evento del ciclo.
GET/v3/reports-b2c/webhooks/:id/deliveries

Listar Logs de Entrega Webhook

Bearer JWTLista intentos de entrega (retenidos 30 días vía TTL en Mongo) filtrables por status y webhookType.