# Webhooks

A webhook sends an HTTPS `POST` to a URL you choose each time something happens in your organization, so your own systems can react without polling. Owners and admins manage webhooks in **Settings → Webhooks** or with the [API](#manage-webhooks-with-the-api). An organization can have up to 5 webhooks.

## Add a webhook

1. Go to **Settings → Webhooks** and select **Add webhook**.
2. Under **Send to**, keep **Custom JSON** for your own endpoint (for a chat channel, see [Slack, Discord or Microsoft Teams](#send-events-to-slack-discord-or-microsoft-teams)). Enter the endpoint URL. It must start with `https://`. Addresses that point to private, local or internal networks are refused, and we check again each time we send.
3. Choose the events you want.
4. Copy the signing secret. It is shown **once**. We store it encrypted, but we cannot show it again. If you lose it, rotate it.

Select **Send test event** to deliver a `webhook.test` event right away.

## Events

| Event | Sent when |
|---|---|
| `server.requested` | A server request is received. |
| `server.approved` | A request is approved. |
| `server.rejected` | A request is declined. |
| `server.provisioning` | The host is being prepared for the server. |
| `server.running` | A server is running. |
| `server.stopped` | A server is stopped. |
| `server.interrupted` | A server was stopped and suspended by the platform. |
| `server.failed` | A server could not be created or hit an error. |
| `server.destroyed` | A server is deleted. |
| `server.resumed` | A paused server runs again (after an interruptible pause, or after a balance suspension is lifted). |
| `server.offline` | The host behind a server has been unreachable for two checks in a row (about two minutes). Sent once per outage. |
| `server.back_online` | A server that was reported offline runs again. |
| `server.disk_low` | A running server's disk passed 90% (`level: "low"`) or 98% (`level: "full"`). Sent once per level, and again only after usage fell below 85%. |
| `server.gpu_idle` | A server's GPU stayed under 2% utilisation for 24 hours. Off unless you subscribe to it: there is no email or in-app notice for it. |
| `server.rental_ending` | The host's rental period for a server ends in 7 days, 72 hours and 24 hours (`rental.stage` 1, 2, 3). The server is stopped at that date and its data is deleted about 48 hours later. We also email the organization owner and add an in-app notice. |
| `server.rental_ended` | The rental period ended and the server was stopped. Data on its disk is deleted about 48 hours after `rental.availableUntil`. |
| `plan.available` | A plan a member is watching (**Notify me when available** in the deploy wizard, `POST /api/v1/plan-watches`, `apidly watch add`) can be launched again. Sent once per watch, together with the email. |
| `endpoint.created` | A serverless endpoint is created. |
| `endpoint.paused` | An endpoint is paused, by you or automatically (`endpoint.pausedReason` is `manual`, `runway` or `failures`). |
| `endpoint.resumed` | A paused endpoint is resumed. |
| `endpoint.scaled` | The number of workers an endpoint wants changed (`scale.from`, `scale.to`, `scale.reason`). Can fire often on a busy endpoint. |
| `payment.failed` | A card payment failed: an auto top-up (`kind: "auto_topup"`) or a subscription renewal (`kind: "subscription"`). |
| `balance.low` | The balance is running low. |
| `balance.exhausted` | The balance reached zero. |
| `balance.topped_up` | Credit was added (including auto top-up). |
| `invoice.created` | A receipt or monthly statement is created. `data.invoice.amount` is the total as `{ micros, usd }`, like all money in webhooks; `amountCents` is still sent for existing receivers. |
| `budget.threshold` | A spend budget crosses a threshold. Sent once spend budgets are available on your account. |
| `member.invited` | Someone is invited to the organization. |
| `member.joined` | An invitation is accepted. |
| `member.removed` | A member is removed or leaves. |
| `api_key.created` | An API key is created. |
| `api_key.revoked` | An API key is revoked. |
| `api_key.rotated` | An API key is rotated: `data.apiKey` is the new key, `data.previous` the old one with `endsAt`, when its secret stops working. No secret is ever sent. |
| `api_key.updated` | An API key is edited: `data.changes` lists the settings that changed (`name`, `scope`, `permissions`, `expiresAt`, `allowedCidrs`), without their values. |
| `transfer.completed` | A copy between servers (or a backup or restore) finished and was verified. `data.transfer` is the transfer as `GET /api/v1/transfers` lists it. |
| `transfer.failed` | A copy, backup or restore failed; `data.transfer.message` says why. |
| `transfer.unverified` | A copy, backup or restore ended but its completion could not be confirmed (`data.transfer.reason`). Check the files before you rely on them. |
| `volume.created` | A volume is created: `data.volume` has its name, size, region and hourly price. |
| `volume.deleted` | A volume is deleted: `data.reason` is `requested` (a member or key deleted it) or `balance` (deleted after the balance ran out and the grace period ended). |

In **Settings → Notifications** an owner or admin can switch a whole category off for webhooks without deleting the endpoints.

`server.contract_expiring` and `server.contract_expired` are the old names of `server.rental_ending` and `server.rental_ended`. They are deprecated and are removed after 2027-05-31. Until then, a webhook already subscribed to an old name keeps receiving the event under that old name, with `server.statusReason` still `contract_expired`, and the body still carries `data.contract` next to `data.rental`; after that date it receives the event under the new name, without `data.contract`. A webhook subscribed to the new name receives the new name, and one subscribed to both receives the event once, under the new name. A new webhook cannot select an old name, and a change can keep the old names a webhook already has but cannot add one (400 `invalid_body`).

## The request

Every delivery is a `POST` with a JSON body:

```json
{
  "version": 1,
  "id": "evt_8fK2xQp0aZ1mN4tYc7Ld",
  "type": "balance.low",
  "createdAt": "2026-11-21T10:00:00.000Z",
  "orgId": "org_...",
  "data": {
    "balance": { "micros": "1500000", "usd": "1.500000" },
    "hourlyBurn": { "micros": "480000", "usd": "0.480000" },
    "runwayHours": 3
  }
}
```

- `id` identifies the event. The same event can arrive more than once (retries, redelivery), so use `id` to ignore duplicates.
- Money is an object with exact `micros` (a string, millionths of a US dollar) and a `usd` decimal string.
- Server payloads describe the server (`data.server`, including its `tags`) without connection details or access tokens. Fetch those with the [API](/docs/api-reference) when you need them.

Headers:

| Header | Value |
|---|---|
| `Apidly-Signature` | `t=<unix seconds>,v1=<signature>` |
| `Apidly-Event` | The event type. |
| `Apidly-Event-Id` | The event `id`. |
| `Apidly-Delivery` | The id of this delivery. |
| `User-Agent` | `Apidly-Webhooks/1` |

## Verify the signature

The signature is an HMAC-SHA256, in hex, of the text `<t>.<raw body>` using your signing secret as the key. Always verify against the **raw** request body, before parsing it. Reject requests whose timestamp is more than 5 minutes old. During the 24 hours after you rotate a secret the header carries two `v1` values (new and old); accept the request if either matches.

### Node.js

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

export function verify(rawBody, header, secret, toleranceSeconds = 300) {
  const parts = header.split(",").map((p) => p.trim());
  const t = parts.find((p) => p.startsWith("t="))?.slice(2);
  if (!t || Math.abs(Date.now() / 1000 - Number(t)) > toleranceSeconds) {
    return false;
  }
  const expected = createHmac("sha256", secret).update(`${t}.${rawBody}`).digest();
  return parts
    .filter((p) => p.startsWith("v1="))
    .some((p) => {
      const got = Buffer.from(p.slice(3), "hex");
      return got.length === expected.length && timingSafeEqual(got, expected);
    });
}

// Express: use express.raw({ type: "application/json" }) so req.body is the raw bytes.
// app.post("/apidly", express.raw({ type: "application/json" }), (req, res) => {
//   if (!verify(req.body.toString("utf8"), req.get("Apidly-Signature") ?? "", process.env.APIDLY_WEBHOOK_SECRET)) {
//     return res.sendStatus(400);
//   }
//   res.sendStatus(200);
// });
```

### Python

```python
import hashlib
import hmac
import time


def verify(raw_body: bytes, header: str, secret: str, tolerance: int = 300) -> bool:
    parts = [p.strip() for p in header.split(",")]
    t = next((p[2:] for p in parts if p.startswith("t=")), None)
    if t is None or abs(time.time() - int(t)) > tolerance:
        return False
    expected = hmac.new(
        secret.encode(), t.encode() + b"." + raw_body, hashlib.sha256
    ).hexdigest()
    return any(
        hmac.compare_digest(p[3:], expected) for p in parts if p.startswith("v1=")
    )


# Flask: request.get_data() returns the raw body.
# @app.post("/apidly")
# def hook():
#     if not verify(request.get_data(), request.headers.get("Apidly-Signature", ""), SECRET):
#         return "", 400
#     return "", 200
```

## Send events to Slack, Discord or Microsoft Teams

A webhook can post straight into a chat channel. Each event becomes one short message in your organization's language (the language of its owner) with a link to the right page of the console: "Server ready", "Server stopped", "Server failed" with the reason and what the server was charged, low balance, spending limit, a paused interruptible server, a rental that is ending, a plan back in stock, an endpoint that scaled to zero or was paused after failing, and so on.

1. In the chat app, create an incoming webhook for the channel and copy its URL:
   - **Slack**: an app with **Incoming Webhooks** turned on. The URL starts with `https://hooks.slack.com/services/`.
   - **Discord**: **Channel settings → Integrations → Webhooks → New webhook**, then **Copy webhook URL**. The URL starts with `https://discord.com/api/webhooks/`.
   - **Microsoft Teams**: a **Workflows** flow "Post to a channel when a webhook request is received". The URL is on `logic.azure.com` or `api.powerplatform.com`. Older connector URLs on `webhook.office.com` are accepted as well, while Microsoft still serves them.
2. In **Settings → Webhooks**, select **Add webhook**, pick **Slack**, **Discord** or **Microsoft Teams** under **Send to** and paste the URL. We only accept that app's own incoming-webhook addresses.
3. Choose the events, or start from a quick pick: **Tell me when a server is ready or fails** (`server.running`, `server.failed`, `server.stopped`, `server.interrupted`, `server.rental_ending`, `endpoint.paused`) or **Money alerts** (`balance.low`, `balance.exhausted`, `payment.failed`, `budget.threshold`).
4. Select **Send test event**. A test message appears in the channel.

What is different from a JSON webhook:

- There is **no signature**: chat apps cannot check one, so no `Apidly-Signature` header and no signing secret is shown. The webhook URL itself is the secret. Keep it private, and delete the webhook (and the one in the chat app) if it leaks.
- Messages carry names, statuses and amounts only. They never contain secrets, variable values, connection details or passwords.
- Retries, the 20-failures switch-off, the delivery log and **Redeliver** work exactly as for JSON webhooks (see below). A redelivery posts the same text again.
- Discord messages never ping anyone (`@everyone` and mentions are switched off).

With the CLI: `apidly webhooks add https://hooks.slack.com/services/... --format slack --events server.running,server.failed`. With the API, send `"format": "slack"` (or `discord`, `teams`) when you create or change a webhook.

### Other chat tools

For a chat tool we do not post to directly (for example Google Chat), put a small relay between us and the chat: it verifies the signature (see above), turns the event into one line of text and forwards it to the incoming-webhook address of your chat. Keep that address in an environment variable, never in code.

```js
// Node.js 20+ with Express. `verify` is the function from the Node.js example above.
import express from "express";

const CHAT_URL = process.env.CHAT_WEBHOOK_URL; // the incoming-webhook address from your chat tool
const FIELD = process.env.CHAT_FIELD ?? "text"; // Slack and Google Chat: "text". Discord: "content".

const app = express();
app.post("/events", express.raw({ type: "application/json" }), async (req, res) => {
  const raw = req.body.toString("utf8");
  if (!verify(raw, req.get("Apidly-Signature") ?? "", process.env.APIDLY_WEBHOOK_SECRET)) {
    return res.sendStatus(400);
  }
  const event = JSON.parse(raw);
  const server = event.data?.server;
  const line = server
    ? `${event.type}: ${server.label ?? server.id}`
    : `${event.type} (${event.id})`;
  const sent = await fetch(CHAT_URL, {
    method: "POST",
    headers: { "content-type": "application/json" },
    body: JSON.stringify({ [FIELD]: line }),
  });
  // Answer 5xx when the chat refused, so we retry; a 2xx tells us the event is handled.
  res.sendStatus(sent.ok ? 200 : 502);
});
app.listen(3000);
```

Subscribe only to the events you want in the channel; a busy `endpoint.scaled` stream is noisy in chat. Use `id` to skip an event you already posted.

## Delivery, retries and the log

- Answer with any `2xx` status within 5 seconds. We do not follow redirects, and we read only the first part of your response.
- If the delivery fails (a non-2xx status, a timeout or a connection error) we retry after 1 minute, 5 minutes, 30 minutes, 2 hours, 6 hours and 12 hours, then stop. Nothing is retried for more than 24 hours after the event.
- After 20 failed attempts in a row the webhook is switched off and we send you one email. Fix the endpoint, then turn it on again in **Settings → Webhooks**.
- Each webhook has a delivery log with the status, the response code, how long it took and the first 500 characters of your response. Logs are kept for 14 days. Select **Redeliver** to send an event again.
- Events are not guaranteed to arrive in order. Use `createdAt` if order matters.

## Rotate the signing secret

Select **Rotate secret**. You get a new secret once. The old secret keeps signing for 24 hours (both signatures are sent) so you can switch your receiver over without losing events.

## Manage webhooks with the API

These calls need an [API key](/docs/api-keys) created by an owner or admin.

| Call | What it does |
|---|---|
| `GET /api/v1/webhooks` | List webhooks (without secrets) and the event names. |
| `POST /api/v1/webhooks` | Create one. Body: `{ "url": "https://...", "events": ["server.running"], "format": "json", "description": "optional" }`. `format` is `json` (default), `slack`, `discord` or `teams`. The response contains the signing `secret` once (not used by the chat formats). |
| `PATCH /api/v1/webhooks/{id}` | Change `url`, `format`, `description`, `events` or `active`. |
| `POST /api/v1/webhooks/{id}/rotate-secret` | A new signing `secret` (shown once); the old one keeps signing for 24 hours. |
| `POST /api/v1/webhooks/{id}/test` | Send a test event (signed for JSON, a short message for a chat app). |
| `POST /api/v1/webhooks/deliveries/{deliveryId}/redeliver` | Send one past delivery again. |
| `DELETE /api/v1/webhooks/{id}` | Delete one. |
| `GET /api/v1/webhooks/{id}/deliveries` | The delivery log of one webhook, newest first (`?limit=` up to 100). |

```
curl -X POST https://YOUR-DOMAIN/api/v1/webhooks \
  -H "Authorization: Bearer $APIDLY_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"url":"https://example.com/apidly","events":["server.running","balance.low"]}'
```
