# Set up a webhook

How your tool learns what you do in the app: build a receiver, verify the signature, test.

So far, only your tool has been talking to Packlets. With a webhook, it works the other way too: when you tap a button, flip a toggle, or write in the chat, Packlets calls your tool.

By the end of this page you will have a small receiver that accepts events, checks that they are genuine, and reacts to them. [Buttons](https://packlets.app/en/docs/knoepfe.md), [elements in messages](https://packlets.app/en/docs/nachrichten-elemente.md), and [replies](https://packlets.app/en/docs/chat.md) all build on it.

**You need:** a packlet with a key, and a place where your tool is reachable at a public `https` address.

## 1. Build a receiver

A webhook receiver is a small web server with a single address that accepts `POST` requests. This one prints every event:

```python
# pip install flask
from flask import Flask, request

app = Flask(__name__)

@app.post("/packlets")
def packlets_webhook():
    event = request.get_json()
    print(event)
    return "", 204

app.run(port=8080)
```

```typescript
// Node.js 18 or newer, no extra packages
import { createServer } from "node:http";

createServer(async (req, res) => {
  let body = "";
  for await (const chunk of req) body += chunk;
  console.log(JSON.parse(body));
  res.writeHead(204).end();
}).listen(8080);
```

## 2. Make it publicly reachable

Packlets has to reach your receiver from the internet. The address must start with `https://`. Packlets rejects addresses like `localhost` or `192.168.…`.

- **On a server** with its own domain, this is already the case.
- **On your computer**, a tunnel helps for testing, for example `cloudflared tunnel --url http://localhost:8080` or `ngrok http 8080`. Both give you a public `https` address that points to your computer.

## 3. Enter the address in Packlets

You enter the webhook URL when you create the packlet, or later in its settings: tap the avatar or name at the top of the channel. In the example, that would be `https://your-address.example/packlets`.

To test, send yourself a message with an action button and tap it:

```bash
curl https://api.packlets.app/v1/push \
  -H "Authorization: Bearer $PACKLETS_KEY" \
  -H "Content-Type: application/json" \
  -d '{"text": "Is the webhook arriving?", "buttons": [{"id": "yes", "label": "Yes"}]}'
```

Your receiver now prints the event:

```json
{
  "type": "button",
  "packlet_id": "9d2f7c10-3a5b-4c8e-9f21-6b7d8e9f0a12",
  "message_id": "5b0c1a52-7c1e-4a43-9d0b-2f6f0c7d1e11",
  "button_id": "yes",
  "pressed_at": "2026-11-09T18:00:00.000Z"
}
```

Nothing arriving? The packlet's activity log shows every attempt with the status of your response. More under [Troubleshooting](https://packlets.app/en/docs/fehlersuche.md#the-webhook-doesn-t-arrive).

## 4. Verify the signature

Your address is public. Anyone who knows it could send you fake events. That is why Packlets signs every request in the `X-Packlets-Signature` header, and your tool checks the signature before it does anything.

Here is how it is calculated:

1. The secret is the SHA-256 hash of your key, as hex text.
2. With this secret, you compute the HMAC-SHA256 over the body, exactly as it arrived.
3. The result as hex text, prefixed with `sha256=`, must match the header.

```python
import hashlib, hmac, os
from flask import Flask, request

app = Flask(__name__)
SECRET = hashlib.sha256(os.environ["PACKLETS_KEY"].encode()).hexdigest().encode()

def is_from_packlets(raw_body: bytes, signature: str) -> bool:
    expected = "sha256=" + hmac.new(SECRET, raw_body, hashlib.sha256).hexdigest()
    return hmac.compare_digest(expected, signature or "")

@app.post("/packlets")
def packlets_webhook():
    if not is_from_packlets(request.get_data(), request.headers.get("X-Packlets-Signature", "")):
        return "", 401
    event = request.get_json()
    print(event)
    return "", 204

app.run(port=8080)
```

```typescript
import { createHash, createHmac, timingSafeEqual } from "node:crypto";
import { createServer } from "node:http";

const secret = createHash("sha256").update(process.env.PACKLETS_KEY ?? "").digest("hex");

function isFromPacklets(rawBody: string, signature = ""): boolean {
  const expected = Buffer.from("sha256=" + createHmac("sha256", secret).update(rawBody, "utf8").digest("hex"));
  const given = Buffer.from(signature);
  return expected.length === given.length && timingSafeEqual(expected, given);
}

createServer(async (req, res) => {
  let body = "";
  for await (const chunk of req) body += chunk;
  if (!isFromPacklets(body, req.headers["x-packlets-signature"] as string | undefined)) {
    res.writeHead(401).end();
    return;
  }
  console.log(JSON.parse(body));
  res.writeHead(204).end();
}).listen(8080);
```

> **Careful:** Compute over the body exactly as it arrived, not over JSON you regenerate from it. Even a different space changes the signature.

If you generate a new key in the app, the secret changes too. Your tool then needs the new key.

If your tool triggers something that must not happen twice, also check `timestamp` and `event_id` from the body: [Replay protection](https://packlets.app/en/docs/ereignisse.md#replay-protection).

## 5. React to events

There are three events. The `type` field tells you which one it is:

| `type` | When | Important fields |
|---|---|---|
| `button` | You tap an action [button](https://packlets.app/en/docs/knoepfe.md). | `message_id`, `button_id` |
| `ui` | You use an [element in a message](https://packlets.app/en/docs/nachrichten-elemente.md). | `message_id`, `element_id`, `value` |
| `message` | You write in the [chat](https://packlets.app/en/docs/chat.md). | `text` |

All fields are listed in the reference [Webhook events](https://packlets.app/en/docs/ereignisse.md). In the receiver, replace the output with your own logic:

```python
    event = request.get_json()
    if event["type"] == "button" and event["button_id"] == "restart":
        restart(event["message_id"])         # your function
    elif event["type"] == "ui" and event["element_id"] == "rollback":
        rollback()                           # your function
    elif event["type"] == "message":
        reply(event["text"])                 # your function
    return "", 204
```

```typescript
  const event = JSON.parse(body);
  res.writeHead(204).end(); // respond first, then work
  if (event.type === "button" && event.button_id === "restart") await restart(event.message_id); // your function
  else if (event.type === "ui" && event.element_id === "rollback") await rollback(); // your function
  else if (event.type === "message") await reply(event.text); // your function
```

It is best if your tool ignores events it does not know. That way it keeps working when Packlets adds new ones.

## Respond quickly

Packlets waits **10 seconds** at most for your response. Any `2xx` status counts as delivered, and the content of your response is not read.

If the work takes longer, for example an AI reply, acknowledge right away and work afterwards. Send the result with `POST /v1/push` once it is ready.

## Duplicate events

If your tool does not respond, responds too late, or responds with a server error, Packlets retries up to five times, spread over about ten minutes. So the same event can arrive more than once, even if your tool already processed it the first time.

If an action must only run once, remember what you have already seen:

| Event | Unique by |
|---|---|
| `button` | `message_id` and `button_id` |
| `message` | `message_id` |
| `ui` | `message_id`, `element_id`, and `changed_at` |

For toggles this usually doesn't matter: setting the same value twice does no harm. A restart or a payment, however, must only run once.

## What's next

- Write with your tool: [Build a chat bot](https://packlets.app/en/docs/chat.md).
- Toggles, inputs, and buttons in messages: [Elements in messages](https://packlets.app/en/docs/nachrichten-elemente.md).
- All fields, headers, and delivery rules: [Webhook events](https://packlets.app/en/docs/ereignisse.md).
