# 签名 Webhook

> 创建视频时传入 `webhook_url`，任务结束时我们会向这个地址 POST 一次与 `GET /api/v1/videos/:id` 相同的 JSON，并用你账户的密钥签名。校验 `Webhook-Signature` 头之后再处理，回调没到时轮询即可。

Muse Video 是 Meta 开发的视频模型。Muse-Video.dev 是独立的 API 服务，与 Meta 无隶属关系，也未获其背书；Muse Video 名称是其所有者的商标。

## 什么时候发送

视频任务结束时（成功、失败或取消），我们向 `webhook_url` 发送一次 POST。地址必须是 https，不能指向内网。每段视频只尝试一次，超时 10 秒；没有自动重试，所以轮询 `GET /api/v1/videos/:id` 是可靠的兜底。

## 请求内容

```http
POST /hooks/muse-video HTTP/1.1
Content-Type: application/json
User-Agent: Muse-Video.dev-Webhooks/1
Webhook-Signature: t=1764321164,v1=5d2c8f…e41a

{
  "type": "video.succeeded",
  "data": {
    "id": "3f9c2b7e-5a1d-4c8e-9b0f-2d6e8a41c7d3",
    "status": "success",
    "model": "muse-video",
    "resolution": "720p",
    "seconds": 5,
    "credits": 15,
    "creditsHeld": 0,
    "creditsCharged": 15,
    "outputs": ["https://cdn.muse-video.dev/…/video.mp4"],
    …
  }
}
```

- `type`：`video.succeeded`（视频已交付并计费）或 `video.failed`（失败或取消，冻结的积分已释放）。
- `data`：与 `GET /api/v1/videos/:id` 完全相同的视频对象。

## 签名

`Webhook-Signature: t=<Unix 秒>,v1=<十六进制签名>`，其中签名是用你的 `whsec_` 密钥对字符串 `t + "." + 原始请求体` 计算的 HMAC-SHA256。校验步骤：

1. 读取原始请求体，在解析 JSON 之前。
2. 拒绝 `t` 与当前时间相差超过 5 分钟的请求，防止重放。
3. 用常量时间比较你算出的签名和 `v1`。

密钥在 [设置 → API 密钥](https://muse-video.dev/settings/apikeys) 页面，每个账户一个，所有密钥共用。建议存成环境变量 `MUSE_VIDEO_WEBHOOK_SECRET`。

## Node.js（Express）

```js
import crypto from 'node:crypto';
import express from 'express';

const app = express();
const SECRET = process.env.MUSE_VIDEO_WEBHOOK_SECRET; // whsec_…

// Keep the raw body: the signature covers the exact bytes we sent.
app.post('/hooks/muse-video', express.raw({ type: 'application/json' }), (req, res) => {
  const header = req.get('Webhook-Signature') ?? '';
  const match = /^t=(\d+),v1=([0-9a-f]{64})$/.exec(header);
  if (!match) return res.status(400).end();
  const [, t, v1] = match;
  if (Math.abs(Date.now() / 1000 - Number(t)) > 300) return res.status(400).end();

  const expected = crypto
    .createHmac('sha256', SECRET)
    .update(`${t}.${req.body.toString('utf8')}`)
    .digest('hex');
  if (!crypto.timingSafeEqual(Buffer.from(expected), Buffer.from(v1)))
    return res.status(400).end();

  const event = JSON.parse(req.body.toString('utf8'));
  // event.type: "video.succeeded" | "video.failed"; event.data: the video
  res.status(200).end();
});
```

## Python（Flask）

```python
import hashlib, hmac, os, re, time
from flask import Flask, request, abort

app = Flask(__name__)
SECRET = os.environ["MUSE_VIDEO_WEBHOOK_SECRET"].encode()  # whsec_…

@app.post("/hooks/muse-video")
def muse_video_hook():
    header = request.headers.get("Webhook-Signature", "")
    m = re.fullmatch(r"t=(\d+),v1=([0-9a-f]{64})", header)
    if not m or abs(time.time() - int(m[1])) > 300:
        abort(400)
    body = request.get_data()  # raw bytes, before any JSON parsing
    expected = hmac.new(SECRET, m[1].encode() + b"." + body, hashlib.sha256).hexdigest()
    if not hmac.compare_digest(expected, m[2]):
        abort(400)
    event = request.get_json()
    # event["type"]: "video.succeeded" | "video.failed"
    return "", 200
```

## 可靠处理

- **先响应，后处理**：收到后立刻返回 2xx，把下载和入库放进队列。
- **按 id 去重**：同一段视频的回调和你的轮询可能都会拿到结果，用 `data.id` 去重。
- **兜底轮询**：如果几分钟后还没收到回调，就调用 `GET /api/v1/videos/:id`。
- **及时保存文件**：拿到 `outputs[0]` 后下载到你自己的存储。

## FAQ

### Webhook 失败会重试吗？

不会。每段视频只发送一次，10 秒超时。没收到时请轮询 GET /api/v1/videos/:id。

### 签名密钥在哪里？

在 设置 → API 密钥 页面，以 whsec_ 开头，每个账户一个。

### 失败的任务也会发回调吗？

会，事件类型是 video.failed，此时冻结的积分已经释放。

### 可以用 http 地址吗？

不可以。webhook_url 必须是 https，且不能指向内网地址。


---

Source: https://muse-video.dev/zh/webhooks · Site index for AI agents: https://muse-video.dev/llms.txt · Full content: https://muse-video.dev/llms-full.txt
