# Webhooks

> Have Clouduxe call your endpoint when something happens, check every delivery's signature before you trust it, and handle retries and repeats.

Source: https://docs.clouduxe.com/api/webhooks/

A webhook is a signed `POST` from Clouduxe to an HTTPS endpoint you run, sent
when something happens on your account: an order is paid, a server is ready, an
action finishes, an invoice is overdue. It saves your billing system from
polling.

## Add an endpoint

`POST /webhook-endpoints` (reference: https://docs.clouduxe.com/api/reference/webhooks/create-webhook-endpoint/)

```bash
curl -X POST https://api.clouduxe.com/v1/webhook-endpoints \
  -H "Authorization: Bearer $CLOUDUXE_API_KEY" \
  -H "Idempotency-Key: 6f1c2e9a-4b7d-4e3a-9c8f-1a2b3c4d5e6f" \
  -H "Content-Type: application/json" \
  -d '{"url":"https://billing.acme.example/clouduxe/webhooks","description":"WHMCS production","enabledEvents":["service.provisioned","service.suspended","service.terminated","action.completed","invoice.created","invoice.overdue"]}'
```

##### Response (`201`)

```json
{
  "object": "webhook_endpoint",
  "id": "1f4b8e2d-6a9c-4d3f-a7e5-2c0b9d6f3a8e",
  "url": "https://billing.acme.example/clouduxe/webhooks",
  "description": "WHMCS production",
  "enabledEvents": [
    "service.provisioned",
    "service.suspended",
    "service.terminated",
    "action.completed",
    "invoice.created",
    "invoice.overdue"
  ],
  "status": "enabled",
  "apiVersion": "2026-12-01",
  "secret": "cxwhsec_4fT9qLm2Xv7Rk3Np8Wd1Zs6Hc0Yb5Ue2Ja9Gt4Qx7Lp",
  "createdByTokenId": "0b7f3c2a-9e4d-4f1a-8c6b-5d2e7a9f1c3b",
  "updatedByTokenId": "0b7f3c2a-9e4d-4f1a-8c6b-5d2e7a9f1c3b",
  "createdAt": "2026-12-01T08:20:00Z",
  "livemode": true
}
```

The answer holds the endpoint's signing secret, `cxwhsec_` followed by 43
letters and digits. It is shown in this answer only: a replay of the same
request answers `secret: null`. Store it like a token. If you lose it, rotate
it.

An endpoint's URL must:

- use `https`, on port 443 or 8443;
- use a public DNS name, not an IP address;
- not be on a Clouduxe domain.

Otherwise the request answers
[`webhook_url_refused`](https://docs.clouduxe.com/api/errors/#webhook_url_refused). An account can have
up to 10 endpoints
([`webhook_endpoint_limit`](https://docs.clouduxe.com/api/errors/#webhook_endpoint_limit)).

Creating an endpoint, or changing its URL, emails the account owner. Endpoints
are listed beside your tokens on
[API tokens](https://dash.clouduxe.com/account/api-tokens) in the panel.

## The events

Give an endpoint the event types it should receive in `enabledEvents`, or
`["*"]` for all of them. Every type the API sends:

- `order.paid`: Order paid
- `order.held`: Order held
- `order.completed`: Order completed
- `order.cancelled`: Order cancelled
- `service.created`: Service created
- `service.provisioned`: Service provisioned
- `service.provisioning_failed`: Service provisioning failed
- `service.suspended`: Service suspended
- `service.unsuspended`: Service unsuspended
- `service.plan_changed`: Service plan changed
- `service.cancellation_scheduled`: Service cancellation scheduled
- `service.cancellation_removed`: Service cancellation removed
- `service.renewed`: Service renewed
- `service.terminating`: Service terminating
- `service.terminated`: Service terminated
- `action.completed`: Action completed
- `invoice.created`: Invoice created
- `invoice.paid`: Invoice paid
- `invoice.overdue`: Invoice overdue
- `invoice.cancelled`: Invoice cancelled
- `wallet.credited`: Wallet credited
- `ticket.replied`: Ticket replied
- `ticket.closed`: Ticket closed
- `api_token.revoked`: API token revoked
- `protection.attack_started`: Attack started
- `protection.attack_ended`: Attack ended
- `webhook_endpoint.test`: Webhook endpoint test

Each delivery's body is an event:

| Field | What it holds |
| --- | --- |
| `object` | Always `event`. |
| `id` | The event's id. Retries and redeliveries carry the same one. |
| `type` | The event type, such as `action.completed`. |
| `apiVersion` | The API version the payload is written in. |
| `createdAt` | When the change happened. |
| `livemode` | Whether it is a live event. |
| `data.object` | The object as it was when the event happened. |
| `data.previousAttributes` | The fields that changed, with their earlier values. |

## Verify every delivery

Every delivery carries these headers:

| Header | What it holds |
| --- | --- |
| `Clouduxe-Signature` | `t=<unix seconds>,v1=<signature>`. While a secret is being rotated there are two `v1` values. |
| `Clouduxe-Event-Id` | The event's id. |
| `Clouduxe-Event-Type` | The event's type. |
| `User-Agent` | `Clouduxe-Webhooks/1`. |

The signature is the hex HMAC-SHA256 of `<t>.<raw body>`, keyed with the
endpoint's secret. Before you act on a delivery:

### Step 1: Keep the raw body

Compute the signature over the body exactly as it arrived, before any JSON
parsing. A body parsed and serialised again will not match.

### Step 2: Check the signature and the time

Compute the HMAC, compare it with each `v1` value in constant time, and refuse
the delivery if none matches or if `t` is more than 300 seconds from your
clock.

### Step 3: Ignore repeats

Delivery is at least once. Record each event `id` you have handled and ignore
one you have seen.

### Node

```js
import crypto from "node:crypto";

const TOLERANCE_SECONDS = 300;

// rawBody: the request body exactly as received (a Buffer or string), before any JSON parsing.
export function verifyClouduxeSignature(rawBody, header, secret, now = Math.floor(Date.now() / 1000)) {
  const parts = String(header ?? "").split(",").map((p) => p.trim());
  const t = Number(parts.find((p) => p.startsWith("t="))?.slice(2));
  const signatures = parts.filter((p) => p.startsWith("v1=")).map((p) => p.slice(3));
  if (!Number.isInteger(t) || signatures.length === 0) return false;
  if (Math.abs(now - t) > TOLERANCE_SECONDS) return false;

  const expected = crypto.createHmac("sha256", secret).update(`${t}.`).update(rawBody).digest();
  return signatures.some((sig) => {
    const given = Buffer.from(sig, "hex");
    return given.length === expected.length && crypto.timingSafeEqual(given, expected);
  });
}
```

With Express, take the body as raw bytes on the webhook route:
`app.post("/hooks/clouduxe", express.raw({ type: "application/json" }), handler)`,
then pass `req.body` and `req.get("Clouduxe-Signature")`.

### Python

```python
import hashlib
import hmac
import time

TOLERANCE_SECONDS = 300

def verify_clouduxe_signature(raw_body: bytes, header: str, secret: str, now: int | None = None) -> bool:
    """raw_body: the request body exactly as received, before any JSON parsing."""
    parts = [p.strip() for p in (header or "").split(",")]
    t_values = [p[2:] for p in parts if p.startswith("t=")]
    signatures = [p[3:] for p in parts if p.startswith("v1=")]
    if len(t_values) != 1 or not t_values[0].isdigit() or not signatures:
        return False
    t = int(t_values[0])
    if abs((now if now is not None else int(time.time())) - t) > TOLERANCE_SECONDS:
        return False

    expected = hmac.new(secret.encode(), f"{t}.".encode() + raw_body, hashlib.sha256).hexdigest()
    return any(hmac.compare_digest(expected, sig) for sig in signatures)
```

With Flask, pass `request.get_data()` and `request.headers.get("Clouduxe-Signature")`.

### PHP

```php
<?php
const TOLERANCE_SECONDS = 300;

// $rawBody: the request body exactly as received, before any JSON parsing.
function verifyClouduxeSignature(string $rawBody, string $header, string $secret, ?int $now = null): bool
{
    $t = null;
    $signatures = [];
    foreach (explode(',', $header) as $part) {
        $part = trim($part);
        if (str_starts_with($part, 't=')) {
            $t = substr($part, 2);
        } elseif (str_starts_with($part, 'v1=')) {
            $signatures[] = substr($part, 3);
        }
    }
    if ($t === null || !ctype_digit($t) || $signatures === []) {
        return false;
    }
    if (abs(($now ?? time()) - (int) $t) > TOLERANCE_SECONDS) {
        return false;
    }

    $expected = hash_hmac('sha256', $t . '.' . $rawBody, $secret);
    foreach ($signatures as $signature) {
        if (hash_equals($expected, $signature)) {
            return true;
        }
    }
    return false;
}

$valid = verifyClouduxeSignature(
    file_get_contents('php://input'),
    $_SERVER['HTTP_CLOUDUXE_SIGNATURE'] ?? '',
    getenv('CLOUDUXE_WEBHOOK_SECRET')
);
```

The Node and PHP SDKs do the same check with `webhooks.verify(rawBody,
signatureHeader, secret)`.

## Answer quickly

A delivery counts when your endpoint answers any `2xx` within 10 seconds.
Anything else counts as failed: another status, a timeout, or a redirect, which
is never followed. Answer first, then do slow work.

A failed delivery is retried, with longer waits each time:

*Figure: After a failed delivery, Clouduxe waits longer before each retry, from one minute to a day, and keeps trying for up to 3 days. After 3 days of failures the endpoint is disabled and the account owner is emailed.*

Events are kept for 30 days, and the order of deliveries is not guaranteed: use
`createdAt` and the object's own state rather than the order they arrive in.

## Rotate, test and redeliver

- **Rotate the secret** with `rotateWebhookEndpointSecret`. The old secret keeps
  working for `oldSecretExpiresInSeconds`, 0 to 86,400 (a day, the default),
  and during that time each delivery carries both signatures. After a leak,
  send `0`.
- **Test an endpoint** with `testWebhookEndpoint`: it queues one signed
  `webhook_endpoint.test` event and answers `202` with the pending delivery.
- **Redeliver an event** of the last 30 days to one enabled endpoint with
  `redeliverEvent`, for example after your endpoint was down for more than 3
  days. It keeps its event id, so your repeat check still works, and also
  answers `202` with the pending delivery.
- **See how a delivery went** with `getWebhookDelivery` a few seconds later:
  pending, delivered or failed, with your endpoint's status and timing.
- **List past events** with `listEvents`, filtered by `type`, `createdAfter` and
  `createdBefore`.

All of these are in the [Webhooks reference](https://docs.clouduxe.com/api/reference/webhooks/).
