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

# Verify webhook signatures

> Check that a delivery came from API for GEO, in ten lines of code.

Deliveries follow [Standard Webhooks](https://www.standardwebhooks.com). Each one has three headers:

| Header | Value |
| - | - |
| `webhook-id` | The event id. The same on every retry: use it to drop a duplicate. |
| `webhook-timestamp` | Unix seconds. |
| `webhook-signature` | `v1,` and the base64 HMAC-SHA256 of `<id>.<timestamp>.<body>`. |

The HMAC key is your secret without `whsec_`, base64-decoded. During a secret rotation, two signatures come, separated by a space: accept either.

Which secret:

* A task's `webhookUrl`: the organization's **task webhook secret**, in the dashboard under **Webhooks**.
* An endpoint you added in the dashboard: that endpoint's secret, shown when you add it or rotate it.

> [!WARNING]
>
> Check the **raw** body, as it arrived, before you parse it. JSON that you parse and serialize again can differ by one byte, and the check then fails.

## Verify by hand

```javascript Node.js theme={null}
import { createHmac, timingSafeEqual } from "node:crypto";

function verifyWebhook(secret, headers, rawBody) {
  const id = headers["webhook-id"];
  const timestamp = headers["webhook-timestamp"];
  if (Math.abs(Date.now() / 1000 - Number(timestamp)) > 300) return false; // older than 5 minutes: a replay
  const key = Buffer.from(secret.replace(/^whsec_/, ""), "base64");
  const expected = Buffer.from(`v1,${createHmac("sha256", key).update(`${id}.${timestamp}.${rawBody}`).digest("base64")}`);
  return headers["webhook-signature"].split(" ").some((candidate) => {
    const given = Buffer.from(candidate);
    return given.length === expected.length && timingSafeEqual(given, expected);
  });
}
```

```python Python theme={null}
import base64, hashlib, hmac, time

def verify_webhook(secret: str, headers, raw_body: bytes) -> bool:
    msg_id = headers["webhook-id"]
    timestamp = headers["webhook-timestamp"]
    if abs(time.time() - int(timestamp)) > 300:
        return False  # older than 5 minutes: a replay
    key = base64.b64decode(secret.removeprefix("whsec_"))
    signed = f"{msg_id}.{timestamp}.".encode() + raw_body
    expected = "v1," + base64.b64encode(hmac.new(key, signed, hashlib.sha256).digest()).decode()
    return any(hmac.compare_digest(expected, given) for given in headers["webhook-signature"].split(" "))
```

## In a server

```javascript Express theme={null}
import express from "express";

const app = express();

// express.raw keeps the body as bytes, for the check.
app.post("/hooks/apiforgeo", express.raw({ type: "application/json" }), (req, res) => {
  if (!verifyWebhook(process.env.AFG_WEBHOOK_SECRET, req.headers, req.body.toString("utf8"))) {
    return res.sendStatus(401);
  }
  const event = JSON.parse(req.body);
  res.sendStatus(204); // answer within 10 seconds, then do the work
  if (event.type === "task.completed") saveResult(event.data);
});
```

```python Flask theme={null}
import os
from flask import Flask, request

app = Flask(__name__)

@app.post("/hooks/apiforgeo")
def apiforgeo_hook():
    if not verify_webhook(os.environ["AFG_WEBHOOK_SECRET"], request.headers, request.get_data()):
        return "", 401
    event = request.get_json()
    if event["type"] == "task.completed":
        queue_result(event["data"])  # keep it fast: answer within 10 seconds
    return "", 204
```

## With a library

A Standard Webhooks library does the same check in one call. It accepts the secret with its `whsec_` prefix.

```javascript Node.js theme={null}
// npm install standardwebhooks
import { Webhook } from "standardwebhooks";

const event = new Webhook(process.env.AFG_WEBHOOK_SECRET).verify(rawBody, headers); // throws if invalid
```

```python Python theme={null}
# pip install standardwebhooks
from standardwebhooks.webhooks import Webhook

event = Webhook(os.environ["AFG_WEBHOOK_SECRET"]).verify(raw_body, headers)  # raises if invalid
```

Libraries exist for Go, Ruby, PHP, Java, Rust, C# and more. See [standardwebhooks.com](https://www.standardwebhooks.com).


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