> ## Documentation Index
> Fetch the complete documentation index at: https://docs.cresium.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Firma y reintentos

> Cómo verificar que un webhook viene de Cresium y qué pasa cuando tu servidor no responde.

## Los headers

Cada webhook trae estos headers:

| Header | Qué lleva |
| - | - |
| `x-api-key` | Tu API Key. |
| `x-company-id` | ID de la empresa a la que pertenece el evento. |
| `x-timestamp` | Momento del envío, en ISO 8601 UTC (por ejemplo `2026-04-21T15:42:03.000Z`). |
| `x-signature` | Firma HMAC-SHA256 en Base64, calculada con tu Secret. |

## Cómo verificar la firma

Es la misma fórmula que la de los requests a la API, con dos diferencias: el método es siempre `POST` y la URL es la **URL completa** que registraste, con su query string si la tiene.

```text theme={null}
{x-timestamp}|POST|{url completa registrada}|{body}
```

Por ejemplo, si registraste `https://tuapp.com/webhooks/cresium?token=xyz`:

```text theme={null}
2026-04-21T15:42:03.000Z|POST|https://tuapp.com/webhooks/cresium?token=xyz|{"type":"DEPOSIT","data":{"transaction":{...}}}
```

`body` es el body crudo que recibiste, sin parsear. Calculá la firma sobre ese texto, tal cual llegó.

```ts TypeScript theme={null}
import { createHmac, timingSafeEqual } from "node:crypto";

const WEBHOOK_URL = "https://tuapp.com/webhooks/cresium?token=xyz"; // la que registraste
const MAX_AGE_MS = 5 * 60 * 1000;

export function isValidCresiumWebhook(
  headers: Record<string, string | undefined>,
  rawBody: string,
): boolean {
  const timestamp = headers["x-timestamp"];
  const received = headers["x-signature"];
  if (!timestamp || !received) return false;

  // Descartá envíos viejos para evitar replays.
  if (Math.abs(Date.now() - Date.parse(timestamp)) > MAX_AGE_MS) return false;

  const expected = createHmac("sha256", process.env.CRESIUM_SECRET!)
    .update(`${timestamp}|POST|${WEBHOOK_URL}|${rawBody}`)
    .digest("base64");

  const a = Buffer.from(received);
  const b = Buffer.from(expected);
  return a.length === b.length && timingSafeEqual(a, b);
}
```

```python Python theme={null}
import base64
import hashlib
import hmac
import os
from datetime import datetime, timezone

WEBHOOK_URL = "https://tuapp.com/webhooks/cresium?token=xyz"  # la que registraste
MAX_AGE_SECONDS = 5 * 60


def is_valid_cresium_webhook(headers, raw_body: str) -> bool:
    timestamp = headers.get("x-timestamp")
    received = headers.get("x-signature")
    if not timestamp or not received:
        return False

    # Descartá envíos viejos para evitar replays.
    sent_at = datetime.fromisoformat(timestamp.replace("Z", "+00:00"))
    age = abs((datetime.now(timezone.utc) - sent_at).total_seconds())
    if age > MAX_AGE_SECONDS:
        return False

    data = f"{timestamp}|POST|{WEBHOOK_URL}|{raw_body}"
    expected = base64.b64encode(
        hmac.new(
            os.environ["CRESIUM_SECRET"].encode(), data.encode(), hashlib.sha256
        ).digest()
    ).decode()

    return hmac.compare_digest(received, expected)
```

Si la firma no coincide, descartá el webhook.

> [!NOTE]
>
> El timestamp es un string ISO 8601, no epoch en milisegundos. Firmá exactamente el valor que viene en `x-timestamp`.

## Reintentos

Cresium considera que un envío salió bien solo si tu servidor responde con un `2xx` en menos de 10 segundos. Si no, reintenta con espera creciente.

| Intento | Espera aproximada antes de enviarlo | `retry` en el body |
| - | - | - |
| Primer envío | inmediato | no viene |
| Reintento 1 | 1 a 2 segundos | `1` |
| Reintento 2 | 2 a 4 segundos | `2` |
| Reintento 3 | 4 a 8 segundos | `3` |
| Reintento 4 | 8 a 16 segundos | `4` |
| Reintento 5 | 16 a 32 segundos | `5` |

Si el reintento 5 también falla, el webhook **se descarta** y no se vuelve a enviar. En total son un envío y cinco reintentos, repartidos en alrededor de un minuto.

Qué implica para vos:

* Tu endpoint tiene que ser **idempotente**: si recibís dos veces el mismo evento, el segundo no debe duplicar el efecto. Usá `data.transaction.id` como clave.
* Cada reintento se firma de nuevo, con un `x-timestamp` nuevo.
* Si tenés varias URLs registradas para el mismo evento, el reintento solo va a la que falló.
* Si tu servidor estuvo caído más de un minuto, vas a perder esos eventos. Para ponerte al día, consultá `GET /v3/transaction/search`.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.