# Webhooks (https://docs.getbeel.com/en/api/webhooks)

Get an event for every SDI receipt and verify the Getbeel-Signature header.

Instead of polling, register an HTTPS endpoint: Getbeel sends it a signed JSON `POST` for every event you choose, about your invoices, reconciliations and taxes.

| Part        | Rule                                                                                                                                                                                |
| ----------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Request     | `POST`, JSON body, headers `Content-Type: application/json`, `User-Agent: getbeel-webhooks/1.0` and [`Getbeel-Signature`](#verifying-the-signature)                                 |
| Your answer | Any `2xx` within 10 seconds. Redirects are not followed: a `3xx` counts as a failure                                                                                                |
| Retries     | After a non-`2xx`, a timeout or a network error: again after 1 min, 5 min, 30 min, 2 h, 6 h, 12 h, 24 h and 24 h. Up to 9 attempts over about 3 days, then the delivery is `failed` |
| Duplicates  | Delivery is at least once: deduplicate on the event `id`                                                                                                                            |
| Order       | Not guaranteed: re-read the invoice when order matters                                                                                                                              |
| Modes       | A **test** endpoint gets the events of test keys (the sandbox); a **live** endpoint gets real ones                                                                                  |

## Add an endpoint [#add-an-endpoint]

In the app, open **Settings → API keys & MCP → Webhooks**, choose **Add endpoint**, then the URL, the mode and the events. The signing secret is shown once: store it on your server.

- The URL must be `https` on a public host. Private and internal hosts are refused, also when a public name resolves to one.
- **Send test event** posts a test event to the endpoint at once. Every delivery is listed under **Recent deliveries**, with the status, and **Redeliver** sends one again.
- An endpoint works while the member who added it can manage the team's settings. When they lose that permission, its deliveries stop.

## Events [#events]

| Event                   | When                                        | Invoice status  |
| ----------------------- | ------------------------------------------- | --------------- |
| `invoice.sent`          | Transmitted to SDI, waiting for the outcome | `sent`          |
| `invoice.delivered`     | Delivery receipt (RC)                       | `delivered`     |
| `invoice.not_delivered` | Delivery failure (MC)                       | `not_delivered` |
| `invoice.rejected`      | Rejection notice (NS), with the SDI codes   | `rejected`      |

With a test key the events come from the [sandbox](/en/api/sandbox), so you can test every case.

Bank and collection events carry real data, so only **live** endpoints receive them:

| Event                             | When                                                                                                              | `data.object`      |
| --------------------------------- | ----------------------------------------------------------------------------------------------------------------- | ------------------ |
| `bank_statement.parsed`           | A [bank statement](/en/api/bank-reconciliation) was read                                                          | `bank_statement`   |
| `reconciliation.completed`        | AI matching finished: the matches can be reviewed                                                                 | `reconciliation`   |
| `received_invoice.created`        | A supplier invoice arrived from SDI (`source: "sdi"`) or was collected (mailbox scan, forwarding or upload)       | `received_invoice` |
| `invoice.emailed`                 | An invoice or reminder email was sent to the customer                                                             | `invoice_email`    |
| `invoice.email_failed`            | The customer email could not be sent (`error` says why)                                                           | `invoice_email`    |
| `invoice.paid`                    | The payments recorded cover the amount due                                                                        | `invoice`          |
| `invoice.overdue`                 | The day after the due date, once, when the invoice is unpaid                                                      | `invoice`          |
| `filing.ready`                    | A [filing](/en/api/filings) was prepared (or recomputed)                                                          | `filing`           |
| `filing.filed`                    | Its receipt was uploaded (paid), or a return was marked filed with its protocol number                            | `filing`           |
| `filing.needs_review`             | A prepared filing waits for the commercialista's review                                                           | `filing`           |
| `filing.changes_requested`        | The commercialista sent it back with a comment                                                                    | `filing`           |
| `filing.approved`                 | Approved (visto bueno): it can be paid or filed                                                                   | `filing`           |
| `filing.skipped`                  | Marked not to be done, with the reason                                                                            | `filing`           |
| `filing.approval_due`             | With the commercialista's approval required, due within 5 working days and still not approved (once per due date) | `filing`           |
| `tax_deadline.upcoming`           | A [tax deadline](/en/api/taxes) is 7 days or 1 day away, not paid                                                 | `tax_deadline`     |
| `tax_deadline.insufficient_funds` | An F24 due within 5 working days is higher than the balance of every connected bank account                       | `f24_funds_alert`  |
| `bank_connection.expiring`        | A [connected bank](/en/api/bank-connections)'s consent ends within 7 days                                         | `bank_connection`  |
| `bank_connection.expired`         | The consent ended or was revoked: updates stop until you reconnect                                                | `bank_connection`  |

<Callout title="Coming soon">
  `invoice.accepted` and `invoice.refused` (public administration outcome),
  `invoice.terms_expired` (decorrenza termini).
</Callout>

## The payload [#the-payload]

Every event is an `event` object; for invoice events `data.object` is the full invoice, the same as `GET /invoices/{id}` (without the lines).

```json title="POST to your endpoint"
{
  "id": "evt_8a1f…",
  "object": "event",
  "type": "invoice.rejected",
  "created": 1761742800,
  "livemode": true,
  "data": {
    "object": {
      "object": "invoice",
      "id": "fe_3f1c…",
      "number": "121",
      "status": "rejected",
      "sdi": {
        "identificativo_sdi": "7731024559",
        "file_name": "IT13815270965_0004N.xml",
        "error_message": "00305 1.4.1.1.2 <IdCodice> non valido",
        "error_codes": ["00305"],
        "errors": [
          { "code": "00305", "description": "1.4.1.1.2 <IdCodice> non valido" }
        ],
        "available_since": null,
        "updated_at": "2026-10-30T15:02:11.000Z"
      },
      "…": "…"
    }
  }
}
```

Branch on `type`. An event can arrive more than once or late: deduplicate on `id` and, when you need the current state, read the invoice with `GET /invoices/{id}`. What each status means: [SDI lifecycle](/en/api/sdi-lifecycle).

## Verifying the signature [#verifying-the-signature]

Every request has a `Getbeel-Signature` header:

```text
Getbeel-Signature: t=1761742800,v1=5f2b9c…
```

- `t` is the Unix timestamp (seconds) of the delivery.
- `v1` is the hex HMAC-SHA256 of the string `t` + `.` + the raw request body, computed with your endpoint's secret.

To verify it: recompute the HMAC over the **raw** body (before parsing the JSON), compare it with `v1` in constant time, and reject old timestamps (we suggest 5 minutes) to prevent replays.

<Tabs items={['Node.js', 'Python']}>
<Tab value="Node.js">

```js
import { createHmac, timingSafeEqual } from 'node:crypto';
import express from 'express';

export function verifyGetbeelSignature(
  rawBody,
  header,
  secret,
  toleranceSeconds = 300,
) {
  let timestamp;
  const signatures = [];

  for (const part of (header ?? '').split(',')) {
    const [key, value] = part.trim().split('=');
    if (key === 't') timestamp = value;
    if (key === 'v1' && value) signatures.push(value);
  }

  if (!timestamp || signatures.length === 0) return false;
  if (Math.abs(Date.now() / 1000 - Number(timestamp)) > toleranceSeconds)
    return false;

  const expected = createHmac('sha256', secret)
    .update(`${timestamp}.${rawBody}`)
    .digest('hex');

  return signatures.some(
    (signature) =>
      signature.length === expected.length &&
      timingSafeEqual(Buffer.from(signature), Buffer.from(expected)),
  );
}

const app = express();

// Express: read the raw body, not the parsed JSON
app.post(
  '/webhooks/getbeel',
  express.raw({ type: 'application/json' }),
  (req, res) => {
    const ok = verifyGetbeelSignature(
      req.body.toString('utf8'),
      req.get('Getbeel-Signature'),
      process.env.GETBEEL_WEBHOOK_SECRET,
    );

    if (!ok) return res.sendStatus(400);

    const event = JSON.parse(req.body);
    // handle event.type …
    res.sendStatus(200);
  },
);
```

</Tab>
<Tab value="Python">

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

from flask import Flask, request

app = Flask(__name__)


def verify_getbeel_signature(raw_body: bytes, header: str, secret: str, tolerance: int = 300) -> bool:
    timestamp, signatures = None, []

    for part in (header or "").split(","):
        key, _, value = part.strip().partition("=")
        if key == "t":
            timestamp = value
        elif key == "v1" and value:
            signatures.append(value)

    if not timestamp or not timestamp.isdigit() or not signatures:
        return False
    if abs(time.time() - int(timestamp)) > tolerance:
        return False

    expected = hmac.new(
        secret.encode(), timestamp.encode() + b"." + raw_body, hashlib.sha256
    ).hexdigest()

    return any(hmac.compare_digest(expected, signature) for signature in signatures)


# Flask: request.get_data() returns the raw body
@app.post("/webhooks/getbeel")
def getbeel_webhook():
    if not verify_getbeel_signature(
        request.get_data(), request.headers.get("Getbeel-Signature"), os.environ["GETBEEL_WEBHOOK_SECRET"]
    ):
        return "", 400

    event = request.get_json()
    # handle event["type"] …
    return "", 200
```

</Tab>
</Tabs>

## If it fails [#if-it-fails]

What **Recent deliveries** shows, and what to do:

| Delivery error                                                     | Cause                                   | Fix                                                      |
| ------------------------------------------------------------------ | --------------------------------------- | -------------------------------------------------------- |
| `HTTP 4xx` or `5xx`                                                | Your endpoint answered an error         | Fix the handler; Getbeel retries on the schedule above   |
| `Timed out after 10 seconds`                                       | No answer in 10 seconds                 | Answer `2xx` first, then do the work in a queue          |
| `Could not connect to the endpoint`                                | DNS, TLS or network error               | Check that the URL is reachable from the internet        |
| `Endpoint URL not allowed`                                         | Not `https`, or a private host          | Use a public `https` URL (for tests, webhook.site works) |
| `The member who added this endpoint can no longer manage webhooks` | That member left or lost the permission | Add the endpoint again as a member who manages settings  |

Failures that cannot succeed (URL not allowed, endpoint disabled, the member's permission) are not retried.

## Good practice [#good-practice]

- Answer with a `2xx` right away and do heavy work later, in a queue.
- The same event can arrive more than once: make handling idempotent (for example, don't email the customer twice).
- Events can arrive out of order: if order matters, re-read the status with `GET /invoices/{id}`.
- Keep the webhook secret on your server, like the API key.

<Callout type="info">
  Webhooks have just shipped. Events, header and signature algorithm are as
  described here; the fields of `data` are described in the API reference and
  may gain new fields.
</Callout>
