# Recibir webhooks

> Handlers de webhooks verificados para un route handler de Next.js, Express, un Cloudflare Worker y Python.

Todos los handlers hacen las mismas cuatro cosas: leer el cuerpo sin procesar, verificar la firma, ignorar las entregas que ya procesaron y responder `2xx` en menos de 15 segundos. El payload y las cabeceras se describen en [Webhooks](https://ikiform.com/es/docs/webhooks.md).

## Route handler de Next.js

`app/api/webhooks/ikiform/route.ts`:

```ts
import { verifyWebhook, WebhookVerificationError } from "@ikiform/sdk/webhooks";

export async function POST(request: Request) {
  const payload = await request.text();
  try {
    const event = await verifyWebhook({
      payload,
      headers: request.headers,
      secret: process.env.IKIFORM_WEBHOOK_SECRET!,
    });
    if (event.type === "submission.created") {
      await saveLead(event.id, event.data.fields);
    }
    return new Response(null, { status: 204 });
  } catch (error) {
    if (error instanceof WebhookVerificationError) {
      return new Response(error.reason, { status: 400 });
    }
    throw error;
  }
}
```

`request.text()` te da el cuerpo sin procesar. No llames antes a `request.json()`; el JSON vuelto a serializar ya no coincide con la firma.

## Express

`server.js`:

```js
import express from "express";
import { verifyWebhook, WebhookVerificationError } from "@ikiform/sdk/webhooks";

const app = express();

app.post("/webhooks/ikiform", express.text({ type: "application/json" }), async (req, res) => {
  try {
    const event = await verifyWebhook({
      payload: req.body,
      headers: req.headers,
      secret: process.env.IKIFORM_WEBHOOK_SECRET,
    });
    if (event.type === "submission.created") await saveLead(event.id, event.data.fields);
    res.status(204).end();
  } catch (error) {
    if (error instanceof WebhookVerificationError) return res.status(400).send(error.reason);
    res.status(500).end();
  }
});

app.listen(3000);
```

`express.text({ type: "application/json" })` conserva el cuerpo como la cadena exacta que envió Ikiform. Un `express.json()` global lo analizaría antes, así que monta la ruta del webhook antes que él o excluye esta ruta.

## Cloudflare Worker

`src/index.ts`:

```ts
import { verifyWebhook, WebhookVerificationError } from "@ikiform/sdk/webhooks";

interface Env {
  IKIFORM_WEBHOOK_SECRET: string;
  LEADS: KVNamespace;
}

export default {
  async fetch(request: Request, env: Env, ctx: ExecutionContext) {
    if (request.method !== "POST") return new Response(null, { status: 405 });
    const payload = await request.text();
    try {
      const event = await verifyWebhook({ payload, headers: request.headers, secret: env.IKIFORM_WEBHOOK_SECRET });
      if (event.type === "submission.created") {
        ctx.waitUntil(env.LEADS.put(event.id, JSON.stringify(event.data)));
      }
      return new Response(null, { status: 204 });
    } catch (error) {
      if (error instanceof WebhookVerificationError) return new Response(error.reason, { status: 400 });
      throw error;
    }
  },
};
```

El SDK solo usa Web Crypto, así que funciona en Workers, Deno y Bun sin polyfills.

## Python

`app.py`:

```python
import base64
import hashlib
import hmac
import os
import time

from flask import Flask, abort, request

app = Flask(__name__)
secret = base64.b64decode(os.environ["IKIFORM_WEBHOOK_SECRET"].removeprefix("whsec_"))


def verify(body: bytes, headers) -> bool:
    msg_id = headers.get("webhook-id")
    timestamp = headers.get("webhook-timestamp")
    signatures = headers.get("webhook-signature")
    if not msg_id or not timestamp or not signatures or not timestamp.isdigit():
        return False
    if abs(time.time() - int(timestamp)) > 300:
        return False
    content = f"{msg_id}.{timestamp}.".encode() + body
    expected = base64.b64encode(hmac.new(secret, content, hashlib.sha256).digest()).decode()
    for entry in signatures.split(" "):
        version, _, signature = entry.partition(",")
        if version == "v1" and hmac.compare_digest(signature, expected):
            return True
    return False


@app.post("/webhooks/ikiform")
def ikiform_webhook():
    body = request.get_data()
    if not verify(body, request.headers):
        abort(400)
    event = request.get_json()
    if event["type"] == "submission.created":
        save_lead(event["id"], event["data"]["fields"])
    return "", 204
```

## Gestiona los duplicados

Una entrega puede llegar más de una vez, por ejemplo cuando tu servidor la procesó pero la respuesta superó el tiempo de espera. La cabecera `webhook-id` y el `id` del payload son el id de la entrega y no cambian entre reintentos. Guárdalo con una restricción única y sáltate el trabajo que ya hiciste:

`leads.ts`:

```ts
async function saveLead(deliveryId: string, fields: Record<string, unknown>) {
  const inserted = await db.query(
    "insert into leads (delivery_id, fields) values ($1, $2) on conflict (delivery_id) do nothing returning id",
    [deliveryId, JSON.stringify(fields)],
  );
  if (inserted.rowCount === 0) return;
  await notifySales(fields);
}
```

## Pruebas en local

- Ikiform solo entrega a URL `https:` públicas en el puerto 443, así que `localhost` no funciona. Expón tu servidor local con un túnel que te dé una URL HTTPS pública y usa esa URL para un endpoint de prueba.
- Usa **Send test** en la página del endpoint. Envía un evento `endpoint.test` una sola vez, sin reintentos.
- Pega una entrega real en el [verificador de firmas](https://ikiform.com/es/docs/webhooks.md#verifier) para comprobar tu secreto y tus cabeceras en el navegador.
