> For the complete documentation index, see [llms.txt](https://docs.dapta.ai/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.dapta.ai/dapta-docs-es/dcal/integrations/webhooks/verify-signature.md).

# Verifica la firma

Comprueba que una petición de webhook viene de verdad de dCal: calcula el HMAC-SHA256 del cuerpo sin procesar con tu secreto de firma y compáralo con la cabecera X-Slate-Signature en tiempo constante.

Cada entrega que envía dCal trae una cabecera `X-Slate-Signature`. Tu endpoint vuelve a calcular esa firma con el secreto de firma del webhook y rechaza cualquier petición que no coincida. Esta página explica cómo se arma la firma y te da código listo para copiar en Node.js y Python.

Aquí no hay capturas de pantalla: todo pasa en tu servidor.

***

## Cómo se arma la firma

| Elemento  | Valor                                                                     |
| --------- | ------------------------------------------------------------------------- |
| Algoritmo | HMAC-SHA256                                                               |
| Clave     | El secreto de firma completo del webhook, incluido el `whsec_` del inicio |
| Mensaje   | El cuerpo de la petición sin procesar, byte por byte, tal como llegó      |
| Cabecera  | `X-Slate-Signature`                                                       |
| Formato   | `sha256=` seguido del resultado en hexadecimal y minúsculas               |

Cabecera de ejemplo:

```
X-Slate-Signature: sha256=9f2b6c1d3e4a5b6c7d8e9f0a1b2c3d4e5f60718293a4b5c6d7e8f90a1b2c3d4e
```

Dos cosas importan al verificar:

* **Usa el cuerpo sin procesar.** Calcula el HMAC sobre los bytes que recibiste, antes de leer el JSON. Un framework que lee el JSON y lo vuelve a armar puede cambiar los espacios o el orden de las claves, y el resultado deja de coincidir. Lee el cuerpo sin procesar, verifícalo y después interprétalo.
* **Compara en tiempo constante.** Usa la comparación segura de tu lenguaje (`crypto.timingSafeEqual` en Node.js, `hmac.compare_digest` en Python) en lugar de `==`, para que nadie pueda adivinar la firma carácter por carácter.

***

## Node.js (Express)

{% code title="server.js" overflow="wrap" lineNumbers="true" %}

```js
const crypto = require("node:crypto");
const express = require("express");

const app = express();
const SECRET = process.env.DCAL_WEBHOOK_SECRET; // la clave whsec_ tal como te la mostró dCal

// Deja el cuerpo sin procesar: verifica ANTES de leer el JSON.
app.post("/webhooks/dcal", express.raw({ type: "application/json" }), (req, res) => {
  const received = req.get("X-Slate-Signature") || "";
  const expected =
    "sha256=" + crypto.createHmac("sha256", SECRET).update(req.body).digest("hex");

  const a = Buffer.from(received);
  const b = Buffer.from(expected);
  const valid = a.length === b.length && crypto.timingSafeEqual(a, b);
  if (!valid) return res.status(401).send("invalid signature");

  const message = JSON.parse(req.body.toString("utf8"));
  // message.event es "booking.created", "booking.rescheduled", "booking.cancelled" o "ping"
  console.log(message.event, message.data);

  res.status(200).send("ok"); // cualquier 2xx le dice a dCal que la entrega llegó
});

app.listen(3000);
```

{% endcode %}

***

## Python (Flask)

{% code title="app.py" overflow="wrap" lineNumbers="true" %}

```python
import hashlib
import hmac
import os

from flask import Flask, abort, request

app = Flask(__name__)
SECRET = os.environ["DCAL_WEBHOOK_SECRET"].encode()  # la clave whsec_ tal como te la mostró dCal


@app.post("/webhooks/dcal")
def dcal_webhook():
    raw = request.get_data()  # bytes sin procesar, antes de leer el JSON
    received = request.headers.get("X-Slate-Signature", "")
    expected = "sha256=" + hmac.new(SECRET, raw, hashlib.sha256).hexdigest()

    if not hmac.compare_digest(received, expected):
        abort(401)

    message = request.get_json(force=True)
    # message["event"] es "booking.created", "booking.rescheduled", "booking.cancelled" o "ping"
    print(message["event"], message["data"])

    return "ok", 200  # cualquier 2xx le dice a dCal que la entrega llegó
```

{% endcode %}

***

## Haz una prueba con Probar

No necesitas una reserva real para probar tu código. En **API y webhooks** > **Webhooks**, haz clic en **Probar** en la fila del webhook. El mensaje de prueba va firmado con el mismo secreto y el mismo método que una entrega real, así que un verificador que acepta la prueba también acepta los eventos reales. Si la fila muestra **Failed**, tu endpoint respondió con algo distinto de un estado 2xx: revisa si tu verificador la rechazó.

***

## Buenas prácticas

* **Guarda el secreto solo en tu servidor.** Ponlo en la configuración o en los secretos de tu aplicación, nunca en código que publiques ni en un navegador.
* **Omite las repeticiones.** La firma demuestra quién envió una petición, pero no trae marca de tiempo, así que no dice cuándo. Además, una entrega puede llegar más de una vez: todos los intentos de una misma entrega traen la misma cabecera `X-Slate-Delivery`, así que guarda los ID que ya procesaste e ignora una segunda copia.
* **Cambia el secreto sin perder eventos.** dCal no vuelve a mostrar un secreto y no puede rotarlo. Agrega un segundo webhook para la misma URL, deja que tu endpoint acepte los dos secretos por un tiempo, luego elimina el webhook anterior y quédate solo con el secreto nuevo.

> **⚠️ Nota:** Responder `401`, o cualquier estado que no sea 2xx, cuenta como entrega fallida y dCal la sigue reintentando hasta por 24 horas. Cuando cambies de secreto, actualiza primero tu servidor, para que no se rechacen entregas reales mientras haces el cambio.

## Relacionado

* [Webhooks](https://docs.dapta.ai/dapta-docs-es/dcal/integrations/webhooks.md): agrega un webhook y copia su secreto de firma.
* [Referencia del contenido](https://docs.dapta.ai/dapta-docs-es/dcal/integrations/webhooks/payload-reference.md): todos los campos y cabeceras.
* [Seguridad y privacidad](https://docs.dapta.ai/dapta-docs-es/dcal/security-and-privacy.md): cómo guarda dCal los secretos.


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.dapta.ai/dapta-docs-es/dcal/integrations/webhooks/verify-signature.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
