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

# Webhooks

> Get a signed HTTP request when a video job finishes instead of polling GET /v1/videos/{id}.

Add your server's URL under [Webhooks](https://naga.ac/dashboard/webhooks) in the dashboard, and NagaAI sends it a `video.completed` or `video.failed` event when a video job ends. The events are OpenAI's: the same body, signed by the [Standard Webhooks](https://www.standardwebhooks.com/) spec, so the OpenAI SDK's `webhooks.unwrap()` verifies them as they are.

## Receive an event

The server below checks the signature, then fetches the finished job with your API key. Set `NAGA_WEBHOOK_SECRET` to the signing secret the dashboard showed when you added the endpoint.

```python Python theme={"theme":{"light":"github-light-default","dark":"github-dark-dimmed"}}
import os

import requests
from flask import Flask, Response, request
from openai import InvalidWebhookSignatureError, OpenAI

app = Flask(__name__)
client = OpenAI(
    base_url="https://api.naga.ac/v1",
    api_key=os.environ["NAGA_API_KEY"],
    webhook_secret=os.environ["NAGA_WEBHOOK_SECRET"],
)


@app.post("/webhooks/naga")
def naga_webhook():
    try:
        # Raises when the signature or the timestamp doesn't check out.
        event = client.webhooks.unwrap(request.get_data(as_text=True), request.headers)
    except InvalidWebhookSignatureError:
        return Response("Invalid signature", status=400)

    job = requests.get(
        f"https://api.naga.ac/v1/videos/{event.data.id}",
        headers={"Authorization": f"Bearer {os.environ['NAGA_API_KEY']}"},
    ).json()
    if event.type == "video.completed":
        print("Video ready:", job["urls"][0])
    else:
        print("Video failed:", job["error"])
    return Response(status=200)
```

```javascript Node.js theme={"theme":{"light":"github-light-default","dark":"github-dark-dimmed"}}
import express from "express";
import OpenAI from "openai";

const app = express();
const client = new OpenAI({
  baseURL: "https://api.naga.ac/v1",
  apiKey: process.env.NAGA_API_KEY,
  webhookSecret: process.env.NAGA_WEBHOOK_SECRET,
});

// The signature covers the raw body, so don't parse it as JSON first.
app.use(express.text({ type: "application/json" }));

app.post("/webhooks/naga", async (req, res) => {
  let event;
  try {
    event = await client.webhooks.unwrap(req.body, req.headers);
  } catch (error) {
    if (error instanceof OpenAI.InvalidWebhookSignatureError) {
      return res.status(400).send("Invalid signature");
    }
    throw error;
  }

  const jobId = event.data.id;
  const job = await (
    await fetch(`https://api.naga.ac/v1/videos/${jobId}`, {
      headers: { Authorization: `Bearer ${process.env.NAGA_API_KEY}` },
    })
  ).json();
  if (event.type === "video.completed") {
    console.log("Video ready:", job.urls[0]);
  } else {
    console.log("Video failed:", job.error);
  }
  res.status(200).send();
});

app.listen(8000);
```

Each event arrives as a `POST` with a JSON body and three signature headers:

```text theme={"theme":{"light":"github-light-default","dark":"github-dark-dimmed"}}
POST https://example.com/webhooks/naga
user-agent: NagaAI-Webhooks/1.0 (+https://naga.ac)
content-type: application/json
webhook-id: evt_6f1c2b9a0d3e4f5a8b7c6d5e4f3a2b1c
webhook-timestamp: 1774000095
webhook-signature: v1,K5oZfzN95Z9UVu1EsfQmfVNQhnkZ2pj9o9NDN/H/pI4=

{
  "id": "evt_6f1c2b9a0d3e4f5a8b7c6d5e4f3a2b1c",
  "object": "event",
  "created_at": 1774000095,
  "type": "video.completed",
  "data": { "id": "70418329650183274950618327495061" }
}
```

`data.id` is the job `id` that `POST /v1/videos` returned. The event carries no video, prompt or price. Fetch the job with `GET /v1/videos/{id}` to read `urls`, `usage` or `error`, as [Video generation](https://docs.naga.ac/guides/video-generation.md) shows. That way a leaked event exposes nothing, and only your key reads the result.

## Add an endpoint

Open [Webhooks](https://naga.ac/dashboard/webhooks) in the dashboard and choose **Add endpoint**. The page is in the Account group of the sidebar, and only the account's owners and admins see it. Enter three things:

* the URL, which must be `https` and reach a public server;
* an optional description, for your own reference;
* the events to send: `video.completed`, `video.failed`, or both.

The dashboard then shows the signing secret, which starts with `whsec_`. Copy it at once: NagaAI stores it encrypted and can't show it again. If you lose it, delete the endpoint and add it again. An account can have up to 10 endpoints, and every endpoint subscribed to an event gets its own copy.

An endpoint gets the events of every video job in the account, whichever API key or workspace started it. A job that fails before NagaAI returns its `id` gets no event, because your `POST /v1/videos` already received the error.

## Test the endpoint

In the endpoint's menu, **Send test video.completed** queues a real, signed event to that endpoint alone. Its `data.id` starts with `video_test_` and isn't a job, so `GET /v1/videos/{id}` answers `404` for it. Within a few seconds the test appears under **Recent deliveries** with the status your server returned.

To check your verification code without a deploy, sign a sample event the way NagaAI does and pass it to `unwrap()`. The script below uses a throwaway secret, so it runs anywhere:

```python Python theme={"theme":{"light":"github-light-default","dark":"github-dark-dimmed"}}
import base64
import hashlib
import hmac
import json
import os
import time

from openai import OpenAI

# A throwaway secret in the dashboard's format; your server uses its endpoint's own.
secret = "whsec_" + base64.b64encode(os.urandom(24)).decode()

client = OpenAI(
    base_url="https://api.naga.ac/v1",
    api_key=os.environ["NAGA_API_KEY"],
    webhook_secret=secret,
)

# The event NagaAI sends when a video job finishes, signed the way NagaAI signs it.
event_id = "evt_0123456789abcdef0123456789abcdef"
timestamp = str(int(time.time()))
body = json.dumps({
    "id": event_id,
    "object": "event",
    "created_at": int(timestamp),
    "type": "video.completed",
    "data": {"id": "video_test_0123456789abcdef"},
})
key = base64.b64decode(secret.removeprefix("whsec_"))
signed = f"{event_id}.{timestamp}.{body}".encode()
signature = base64.b64encode(hmac.new(key, signed, hashlib.sha256).digest()).decode()
headers = {
    "webhook-id": event_id,
    "webhook-timestamp": timestamp,
    "webhook-signature": f"v1,{signature}",
}

event = client.webhooks.unwrap(body, headers)
print(event.type, event.data.id)
```

```javascript Node.js theme={"theme":{"light":"github-light-default","dark":"github-dark-dimmed"}}
import { createHmac, randomBytes } from "node:crypto";
import OpenAI from "openai";

// A throwaway secret in the dashboard's format; your server uses its endpoint's own.
const secret = `whsec_${randomBytes(24).toString("base64")}`;

const client = new OpenAI({
  baseURL: "https://api.naga.ac/v1",
  apiKey: process.env.NAGA_API_KEY,
  webhookSecret: secret,
});

// The event NagaAI sends when a video job finishes, signed the way NagaAI signs it.
const eventId = "evt_0123456789abcdef0123456789abcdef";
const timestamp = Math.floor(Date.now() / 1000);
const body = JSON.stringify({
  id: eventId,
  object: "event",
  created_at: timestamp,
  type: "video.completed",
  data: { id: "video_test_0123456789abcdef" },
});
const key = Buffer.from(secret.slice("whsec_".length), "base64");
const signature = createHmac("sha256", key)
  .update(`${eventId}.${timestamp}.${body}`)
  .digest("base64");
const headers = {
  "webhook-id": eventId,
  "webhook-timestamp": String(timestamp),
  "webhook-signature": `v1,${signature}`,
};

const event = await client.webhooks.unwrap(body, headers);
console.log(event.type, event.data.id);
```

It prints `video.completed video_test_0123456789abcdef`. Without the OpenAI SDK, use any [Standard Webhooks library](https://github.com/standard-webhooks/standard-webhooks#reference-implementations): it verifies the same headers.

## Retries and duplicates

Answer with any `2xx` status within 10 seconds, and do the slow work after you answer. Any other status, a redirect, a timeout or a refused connection counts as a failure, and NagaAI tries again. The first retry comes 5 seconds later. Each next one waits twice as long, up to 6 hours apart. The last try comes 72 hours after the event, and then NagaAI marks the delivery failed. NagaAI never follows a redirect, so register the final URL.

Every retry of an event carries the same `webhook-id`, the event's `id`. Store the ids you've handled and skip one you've seen. A retry can arrive after your server handled the first copy, before NagaAI read its answer.

The dashboard's Recent deliveries section lists the last 50 deliveries with their state and attempts. It also shows the last answer: an HTTP status, or what happened instead, such as `no answer in 10 s`. Disabling an endpoint pauses its queued deliveries. They resume if you enable it again within 72 hours of their event.

## Troubleshooting

### The dashboard says the URL must point to a public server

NagaAI sends events only to public addresses. The host of the URL must not be or resolve to a private, loopback, link-local or other internal address. The dashboard refuses such a URL when you add it, and the gateway refuses it again on every delivery. To test from your own machine, expose the local server through a tunnel such as [ngrok](https://ngrok.com/) and register the tunnel's `https` URL.

### `InvalidWebhookSignatureError` on every event

The signature covers the body byte for byte. If your framework parsed the JSON and you pass a re-serialized copy to `unwrap()`, the bytes differ and the check fails. Pass the raw body, as both examples do. Check also that `NAGA_WEBHOOK_SECRET` is the secret of this endpoint, including the `whsec_` prefix. `unwrap()` also rejects a `webhook-timestamp` more than five minutes from your server's clock, so keep the clock in sync.

### A delivery shows `HTTP 404` or `HTTP 405`

The URL reaches your server, but no route there accepts a `POST` on that path. Compare the path in the endpoint with the route in your code, then send a test event again.


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