# Webhooks

:::warning

Preview. The webhook routes, payload and signature scheme may still change without a new version until they are announced as stable. Polling `GET /v1-preview/jobs/{id}` always works and is the source of truth.

:::

A webhook tells your system that a job has finished, so you do not have to poll. You register one or more HTTPS endpoints; when a job reaches a final state we send each subscribed endpoint one signed `POST`.

## Register an endpoint

```
POST /v1-preview/webhooks
{ "url": "https://hooks.example.com/gosmarter", "events": ["job.completed"] }
```

The response contains `secret`. **Store it now: it is shown once** and cannot be retrieved again (rotate to get a new one). Rules for the URL:

- HTTPS only, port 443, no credentials in the URL.
- The host must resolve only to public addresses. Loopback, private, link-local (including cloud metadata addresses), carrier-grade NAT and other reserved ranges are refused when you register and again before every delivery. We connect to the address we checked, and we never follow redirects: a `3xx` answer counts as a failed attempt.
- At most five endpoints per account.

Other routes: `GET /v1-preview/webhooks`, `GET|PUT|DELETE /v1-preview/webhooks/{endpointId}`, and `POST /v1-preview/webhooks/{endpointId}/test` (sends a signed `webhook.test` event and reports the answer).

## When we send

One delivery per job and endpoint, when the job reaches a final state: `completed`, `completedWithErrors`, `failed` or `infected` (the `status` in the payload says which). The event name is `job.completed` in every case.

## The request

Headers:

| Header | Meaning |
|---|---|
| `X-GoSmarter-Signature` | `t=<unix seconds>,v1=<hex>[,v1=<hex>]`, see below |
| `X-GoSmarter-Delivery-Id` | Identical on every attempt of the same delivery. De-duplicate on it. |
| `X-GoSmarter-Event` | `job.completed` (or `webhook.test`) |

Body (thin: ids, statuses and links, never certificate data):

```json
{
  "id": "0b0f9e0a-...",
  "type": "job.completed",
  "createdAt": "2026-12-02T12:00:00+00:00",
  "data": {
    "jobId": "5d1c...",
    "mode": "pack",
    "status": "completedWithErrors",
    "failureReason": null,
    "certificates": [
      { "certificateId": "a1...", "status": "completed", "resultUrl": "https://....blob.core.windows.net/...?sig=..." },
      { "certificateId": "b2...", "status": "failed" }
    ],
    "links": { "job": "/v1-preview/jobs/5d1c...", "result": "/v1-preview/jobs/5d1c.../result" },
    "linksExpireAt": "2026-12-03T12:00:00+00:00"
  }
}
```

`resultUrl` is a read-only signed link to that certificate's JSON result and expires at `linksExpireAt` (24 hours). After that, call `GET /v1-preview/jobs/{id}/result` with your API key. The payload does not carry PDF links: to get the certificates back as PDFs, call `GET /v1-preview/jobs/{id}/pdf` (see [PDF exports](/pdf-exports)) when the webhook arrives.

## Fetch the PDFs when a job finishes

A `job.completed` event is the cue to collect the PDFs. Use the `jobId` from the payload:

```bash
curl "https://<gateway-host>/v1-preview/jobs/<jobId>/pdf?groupBy=certificate" \
  -H "Authorization: Bearer $GOSMARTER_API_KEY"
```

`groupBy` is `certificate`, `supplier` or `heat`. Only certificates that completed are included, so for `completedWithErrors` you get the good ones; `failed` and `infected` jobs have none and the call returns `409`. Exports are not billed and the signed links last one hour, so download them straight away. Because a delivery can arrive more than once, de-duplicate on `X-GoSmarter-Delivery-Id` before you fetch.

## Verify the signature

Each `v1` value is `HMAC-SHA256` with your endpoint secret as the key over the string `"<t>.<raw request body>"`, hex-encoded. Verify it against the **raw bytes** of the body before parsing, reject a `t` more than 5 minutes from your clock (replay protection), and compare in constant time:

```python
import hmac, hashlib, time

def verify(header, raw_body, secrets, tolerance=300):
    parts = [p.split("=", 1) for p in header.split(",")]
    t = next(v for k, v in parts if k == "t")
    sigs = [v for k, v in parts if k == "v1"]
    if abs(time.time() - int(t)) > tolerance:
        return False
    signed = f"{t}.".encode() + raw_body
    for secret in secrets:
        expected = hmac.new(secret.encode(), signed, hashlib.sha256).hexdigest()
        if any(hmac.compare_digest(expected, s) for s in sigs):
            return True
    return False
```

## Rotate a secret without a gap

1. `POST /v1-preview/webhooks/{endpointId}/rotate-secret` returns a new `secret`. From now on every delivery carries two `v1` signatures, one for the new and one for the previous secret.
2. Deploy the new secret to your receiver (accepting either is fine).
3. `POST /v1-preview/webhooks/{endpointId}/retire-previous-secret`. Deliveries are signed with the new secret only.

## Retries

Answer with any `2xx` within 15 seconds. Anything else (including a timeout or a redirect) is retried with growing delays: 30 seconds, 2 minutes, 10 minutes, 30 minutes, 2 hours, 6 hours, then 12 hours, eight attempts in all. After the last attempt the delivery is abandoned; the job and its result are unaffected and stay available by polling. A target that is not allowed (see above) is abandoned immediately.
