PaybookDocsv1
Docs/Guías

Recibir webhooks y verificar la firma

Registra tu endpoint, comprueba que cada entrega viene de HUB+ y procesa los eventos sin duplicados.

Antes de empezar#

  • Un endpoint HTTPS público en tu sistema que acepte POST con cuerpo JSON.
  • Lee Eventos y webhooks para conocer los dos formatos de entrega y el catálogo de eventos.
  1. Crea la suscripción#

    Registra tu URL, el método y la lista de eventos.

    POST/v1/webhook
    curl -X POST "https://api.sandbox.hubplus.example/v1/webhook" \
      -H "Authorization: Bearer $HUB_ACCESS_TOKEN" \
      -H "X-Tenant-Id: $HUB_TENANT_ID" \
      -H "Content-Type: application/json" \
      -d '{
      "url": "https://integraciones.universidad.example/hubplus/webhook",
      "events": [
        "update_student"
      ],
      "method": "post"
    }'
    const res = await fetch("https://api.sandbox.hubplus.example/v1/webhook", {
      method: "POST",
      headers: {
        "Authorization": "Bearer " + process.env.HUB_ACCESS_TOKEN,
        "X-Tenant-Id": process.env.HUB_TENANT_ID,
        "Content-Type": "application/json",
      },
      body: JSON.stringify({
        "url": "https://integraciones.universidad.example/hubplus/webhook",
        "events": [
          "update_student"
        ],
        "method": "post"
      }),
    });
    
    if (!res.ok) throw new Error(`HUB+ respondió ${res.status}`);
    const data = await res.json();
    import os
    import requests
    
    res = requests.post(
        "https://api.sandbox.hubplus.example/v1/webhook",
        headers={
            "Authorization": f"Bearer {os.environ['HUB_ACCESS_TOKEN']}",
            "X-Tenant-Id": os.environ["HUB_TENANT_ID"],
        },
        json={
            "url": "https://integraciones.universidad.example/hubplus/webhook",
            "events": ["update_student"],
            "method": "post",
        },
        timeout=30,
    )
    res.raise_for_status()
    data = res.json()
    <?php
    $ch = curl_init("https://api.sandbox.hubplus.example/v1/webhook");
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_CUSTOMREQUEST => "POST",
        CURLOPT_HTTPHEADER => [
            "Authorization: Bearer " . getenv("HUB_ACCESS_TOKEN"),
            "X-Tenant-Id: " . getenv("HUB_TENANT_ID"),
            "Content-Type: application/json",
        ],
        CURLOPT_POSTFIELDS => json_encode([
            "url" => "https://integraciones.universidad.example/hubplus/webhook",
            "events" => ["update_student"],
            "method" => "post",
        ]),
    ]);
    $body = curl_exec($ch);
    $status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    
    if ($status >= 400) {
        throw new RuntimeException("HUB+ respondió $status");
    }
    $data = json_decode($body, true);
    HttpClient client = HttpClient.newHttpClient();
    
    HttpRequest request = HttpRequest.newBuilder()
        .uri(URI.create("https://api.sandbox.hubplus.example/v1/webhook"))
        .header("Authorization", "Bearer " + System.getenv("HUB_ACCESS_TOKEN"))
        .header("X-Tenant-Id", System.getenv("HUB_TENANT_ID"))
        .header("Content-Type", "application/json")
        .method("POST", HttpRequest.BodyPublishers.ofString("""
            {
              "url": "https://integraciones.universidad.example/hubplus/webhook",
              "events": [
                "update_student"
              ],
              "method": "post"
            }
            """))
        .build();
    
    HttpResponse<String> response =
        client.send(request, HttpResponse.BodyHandlers.ofString());
    Respuesta
    {
      "status": true,
      "data": {
        "webhook_id": "00000000-0000-4000-8000-000000000001"
      }
    }

    Guarda el webhook_id. Una suscripción pertenece al cliente de integración que la creó: solo ese cliente la lista y la elimina.

    OperaciónEndpoint
    Listar tus suscripcionesGET/v1/webhook
    Actualizar la URL o los eventosPOST/v1/webhook/00000000-0000-4000-8000-000000000001
    Rotar el secreto de firmaPOST/v1/webhook/00000000-0000-4000-8000-000000000001/rotate_secret
    EliminarDELETE/v1/webhook/00000000-0000-4000-8000-000000000001
  2. Guarda el secreto de firma#

    Cada suscripción tiene un secreto (whsec_…) con el que HUB+ firma las entregas. Guárdalo en tu gestor de secretos, junto a tu client_secret. Al rotarlo, el secreto anterior sigue siendo válido durante un periodo de gracia para que cambies sin perder eventos.

    Respuesta
    {
      "id": "00000000-0000-4000-8000-000000000001",
      "object": "webhook_endpoint",
      "secret": "whsec_EJEMPLO_NO_VALIDO",
      "previous_secret_expires_at": 1796169600
    }
  3. Verifica la firma#

    Cada entrega firmada lleva el encabezado HubPlus-Signature con una marca de tiempo y la firma HMAC-SHA256 del cuerpo:

    Encabezado de firma
    HubPlus-Signature: t=1796083200,v1=5257a869e7ecebeda32affa62cdca3fa51cad7e77a0e56ff536d0ce8e108d8bd

    Para verificar: concatena t, un punto y el cuerpo sin modificar; calcula el HMAC-SHA256 con tu secreto. Compara en tiempo constante con v1; y rechaza marcas de tiempo con más de 5 minutos de antigüedad.

    Receptor con verificación de firma
    import crypto from "node:crypto";
    import express from "express";
    
    const app = express();
    const SECRET = process.env.HUB_WEBHOOK_SECRET;
    
    function firmaValida(raw, header, tolerancia = 300) {
      const partes = Object.fromEntries(header.split(",").map((p) => p.split("=")));
      const esperado = crypto.createHmac("sha256", SECRET).update(`${partes.t}.${raw}`).digest("hex");
      const reciente = Math.abs(Date.now() / 1000 - Number(partes.t)) <= tolerancia;
      const a = Buffer.from(esperado);
      const b = Buffer.from(partes.v1 || "");
      return reciente &&. A.length === b.length &&. Crypto.timingSafeEqual(a, b);
    }
    
    // El cuerpo debe leerse crudo: la firma se calcula sobre los bytes recibidos.
    app.post("/hubplus/webhook", express.raw({ type: "application/json" }), (req, res) => {
      const header = req.get("HubPlus-Signature") || "";
      if (!firmaValida(req.body.toString("utf8"), header)) return res.sendStatus(400);
    
      const evento = JSON.parse(req.body);
      encolar(evento);          // procesa en segundo plano
      res.sendStatus(200);      // responde de inmediato
    });
    import hashlib, hmac, json, os, time
    from flask import Flask, request, abort
    
    app = Flask(__name__)
    SECRET = os.environ["HUB_WEBHOOK_SECRET"]
    
    def firma_valida(payload: bytes, header: str, tolerancia: int = 300) -> bool:
        partes = dict(p.split("=", 1) for p in header.split(",") if "=" in p)
        if "t" not in partes or "v1" not in partes:
            return False
        firmado = partes["t"].encode() + b"." + payload
        esperado = hmac.new(SECRET.encode(), firmado, hashlib.sha256).hexdigest()
        reciente = abs(time.time() - int(partes["t"])) <= tolerancia
        return reciente and hmac.compare_digest(esperado, partes["v1"])
    
    @app.post("/hubplus/webhook")
    def recibir():
        payload = request.get_data()   # bytes crudos, sin volver a serializar
        if not firma_valida(payload, request.headers.get("HubPlus-Signature", "")):
            abort(400)
        evento = json.loads(payload)
        encolar(evento)                # procesa en segundo plano
        return "", 200
    <?php
    $secret = getenv("HUB_WEBHOOK_SECRET");
    $payload = file_get_contents("php://input");   // cuerpo crudo
    $header = $_SERVER["HTTP_HUBPLUS_SIGNATURE"] ?? "";
    
    $partes = [];
    foreach (explode(",", $header) as $p) {
        [$k, $v] = array_pad(explode("=", $p, 2), 2, "");
        $partes[$k] = $v;
    }
    $esperado = hash_hmac("sha256", ($partes["t"] ?? "") . "." . $payload, $secret);
    $reciente = abs(time() - (int) ($partes["t"] ?? 0)) <= 300;
    
    if (!$reciente || !hash_equals($esperado, $partes["v1"] ?? "")) {
        http_response_code(400);
        exit;
    }
    
    $evento = json_decode($payload, true);
    encolar($evento);            // procesa en segundo plano
    http_response_code(200);
    import javax.crypto.Mac;
    import javax.crypto.spec.SecretKeySpec;
    import java.nio.charset.StandardCharsets;
    import java.security.MessageDigest;
    import java.time.Instant;
    import java.util.HexFormat;
    
    public final class FirmaHubPlus {
        public static boolean esValida(String payload, String header, String secret) throws Exception {
            String t = null, v1 = null;
            for (String parte : header.split(",")) {
                String[] kv = parte.split("=", 2);
                if (kv.length < 2) continue;
                if (kv[0].equals("t")) t = kv[1];
                if (kv[0].equals("v1")) v1 = kv[1];
            }
            if (t == null || v1 == null) return false;
    
            Mac mac = Mac.getInstance("HmacSHA256");
            mac.init(new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "HmacSHA256"));
            byte[] firma = mac.doFinal((t + "." + payload).getBytes(StandardCharsets.UTF_8));
            String esperado = HexFormat.of().formatHex(firma);
    
            boolean reciente = Math.abs(Instant.now().getEpochSecond() - Long.parseLong(t)) <= 300;
            return reciente && MessageDigest.isEqual(
                esperado.getBytes(StandardCharsets.UTF_8), v1.getBytes(StandardCharsets.UTF_8));
        }
    }
    Notificaciones ligeras

    Las notificaciones update_* no llevan firma. No confíes en su contenido: úsalas como aviso y consulta el recurso en la url indicada con tu token.

  4. Responde rápido y procesa después#

    Responde 2xx en cuanto verifiques la firma y encoles el evento. Tu endpoint tiene 10 segundos. Si haces el trabajo pesado antes de responder, un pico de eventos provocará reintentos innecesarios.

  5. Descarta duplicados#

    Un evento puede entregarse más de una vez. Guarda el id de cada evento procesado y omite los repetidos.

    Procesamiento idempotente
    def procesar(evento):
        if ya_procesado(evento["id"]):        # evt_… en una tabla con llave única
            return
        if evento["type"] == "payment.succeeded":
            pago = evento["data"]["object"]
            registrar_pago_en_sis(pago["id"], pago["allocations"])
        marcar_procesado(evento["id"])
  6. No dependas del orden#

    Los eventos pueden llegar fuera de orden. Si el orden importa, compara created o consulta el estado actual del recurso antes de actuar.

Recuperar eventos perdidos#

Si tu receptor estuvo caído, no pierdes información: los eventos quedan registrados y puedes listarlos y reenviarlos.

GET/v1/events
curl "https://api.sandbox.hubplus.example/v1/events?type=payment.succeeded&limit=100" \
  -H "Authorization: Bearer $HUB_ACCESS_TOKEN" \
  -H "X-Tenant-Id: $HUB_TENANT_ID"
const params = new URLSearchParams({
  "type": "payment.succeeded",
  "limit": "100"
});

const res = await fetch(`https://api.sandbox.hubplus.example/v1/events?${params}`, {
  headers: {
    "Authorization": "Bearer " + process.env.HUB_ACCESS_TOKEN,
    "X-Tenant-Id": process.env.HUB_TENANT_ID,
  },
});

if (!res.ok) throw new Error(`HUB+ respondió ${res.status}`);
const data = await res.json();
import os
import requests

res = requests.get(
    "https://api.sandbox.hubplus.example/v1/events",
    headers={
        "Authorization": f"Bearer {os.environ['HUB_ACCESS_TOKEN']}",
        "X-Tenant-Id": os.environ["HUB_TENANT_ID"],
    },
    params={
        "type": "payment.succeeded",
        "limit": "100",
    },
    timeout=30,
)
res.raise_for_status()
data = res.json()
<?php
$ch = curl_init("https://api.sandbox.hubplus.example/v1/events" . "?" . http_build_query([
    "type" => "payment.succeeded",
    "limit" => "100",
]));
curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_HTTPHEADER => [
        "Authorization: Bearer " . getenv("HUB_ACCESS_TOKEN"),
        "X-Tenant-Id: " . getenv("HUB_TENANT_ID"),
    ],
]);
$body = curl_exec($ch);
$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

if ($status >= 400) {
    throw new RuntimeException("HUB+ respondió $status");
}
$data = json_decode($body, true);
HttpClient client = HttpClient.newHttpClient();

HttpRequest request = HttpRequest.newBuilder()
    .uri(URI.create("https://api.sandbox.hubplus.example/v1/events?type=payment.succeeded&limit=100"))
    .header("Authorization", "Bearer " + System.getenv("HUB_ACCESS_TOKEN"))
    .header("X-Tenant-Id", System.getenv("HUB_TENANT_ID"))
    .GET()
    .build();

HttpResponse<String> response =
    client.send(request, HttpResponse.BodyHandlers.ofString());
POST/v1/events/91af12eb-c850-420d-8ad8-21870f763739/resend
curl -X POST "https://api.sandbox.hubplus.example/v1/events/91af12eb-c850-420d-8ad8-21870f763739/resend" \
  -H "Authorization: Bearer $HUB_ACCESS_TOKEN" \
  -H "X-Tenant-Id: $HUB_TENANT_ID" \
  -H "Idempotency-Key: $(uuidgen)" \
  -H "Content-Type: application/json" \
  -d '{
  "webhook_id": "00000000-0000-4000-8000-000000000001"
}'
const res = await fetch("https://api.sandbox.hubplus.example/v1/events/91af12eb-c850-420d-8ad8-21870f763739/resend", {
  method: "POST",
  headers: {
    "Authorization": "Bearer " + process.env.HUB_ACCESS_TOKEN,
    "X-Tenant-Id": process.env.HUB_TENANT_ID,
    "Idempotency-Key": crypto.randomUUID(),
    "Content-Type": "application/json",
  },
  body: JSON.stringify({
    "webhook_id": "00000000-0000-4000-8000-000000000001"
  }),
});

if (!res.ok) throw new Error(`HUB+ respondió ${res.status}`);
const data = await res.json();
import os
import uuid
import requests

res = requests.post(
    "https://api.sandbox.hubplus.example/v1/events/91af12eb-c850-420d-8ad8-21870f763739/resend",
    headers={
        "Authorization": f"Bearer {os.environ['HUB_ACCESS_TOKEN']}",
        "X-Tenant-Id": os.environ["HUB_TENANT_ID"],
        "Idempotency-Key": str(uuid.uuid4()),
    },
    json={
        "webhook_id": "00000000-0000-4000-8000-000000000001",
    },
    timeout=30,
)
res.raise_for_status()
data = res.json()
<?php
$ch = curl_init("https://api.sandbox.hubplus.example/v1/events/91af12eb-c850-420d-8ad8-21870f763739/resend");
curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_CUSTOMREQUEST => "POST",
    CURLOPT_HTTPHEADER => [
        "Authorization: Bearer " . getenv("HUB_ACCESS_TOKEN"),
        "X-Tenant-Id: " . getenv("HUB_TENANT_ID"),
        "Idempotency-Key: " . bin2hex(random_bytes(16)),
        "Content-Type: application/json",
    ],
    CURLOPT_POSTFIELDS => json_encode([
        "webhook_id" => "00000000-0000-4000-8000-000000000001",
    ]),
]);
$body = curl_exec($ch);
$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

if ($status >= 400) {
    throw new RuntimeException("HUB+ respondió $status");
}
$data = json_decode($body, true);
HttpClient client = HttpClient.newHttpClient();

HttpRequest request = HttpRequest.newBuilder()
    .uri(URI.create("https://api.sandbox.hubplus.example/v1/events/91af12eb-c850-420d-8ad8-21870f763739/resend"))
    .header("Authorization", "Bearer " + System.getenv("HUB_ACCESS_TOKEN"))
    .header("X-Tenant-Id", System.getenv("HUB_TENANT_ID"))
    .header("Idempotency-Key", UUID.randomUUID().toString())
    .header("Content-Type", "application/json")
    .method("POST", HttpRequest.BodyPublishers.ofString("""
        {
          "webhook_id": "00000000-0000-4000-8000-000000000001"
        }
        """))
    .build();

HttpResponse<String> response =
    client.send(request, HttpResponse.BodyHandlers.ofString());

Probar en sandbox#

  • Apunta la suscripción a un endpoint de pruebas con HTTPS.
  • Provoca el evento: por ejemplo, un pago de prueba para payment.succeeded.
  • Verifica en tu bitácora la firma, la respuesta 2xx y el descarte de un reenvío.

Lista de verificación#

  • El endpoint solo acepta HTTPS.
  • La firma se verifica sobre el cuerpo crudo, con comparación en tiempo constante y tolerancia de 5 minutos.
  • Responde 2xx antes de procesar.
  • Descarta duplicados por id y no depende del orden.
  • El secreto vive en tu gestor de secretos y se rota de forma periódica.
HUB+ by Paybook · Documentación para desarrolladores · API v1
Los hosts, llaves e identificadores de los ejemplos son ficticios.