# Webhooks

> 在创建视频时传入 `webhook_url`，视频成功或失败后，我们会向这个地址 POST 一次结果，内容和 `GET /api/v1/videos/{id}` 返回的一样，并用你账户的密钥签名。只投递一次，所以请把轮询当作后备。

## 回调内容

```http
POST /hooks/magi2 HTTP/1.1
Content-Type: application/json
User-Agent: Magi2AI-Webhooks/1
Magi2-Signature: t=1764062012,v1=5d2c8f…e41a

{
  "type": "video.succeeded",
  "data": {
    "id": "3f9c2b7e-5a1d-4c8e-9b0f-2d6e8a41c7d3",
    "status": "success",
    "model": "seedance-2-fast",
    "modelName": "Seedance 2.0 Fast",
    "resolution": "480p",
    "seconds": 5,
    "credits": 95,
    "outputs": ["https://cdn.magi2ai.dev/…/video.mp4"],
    …
  }
}
```

- `type` 是 `video.succeeded` 或 `video.failed`；
- `data` 和 `GET /api/v1/videos/{id}` 的返回完全相同；
- 失败的视频已经自动退回积分，`data.error` 给出原因。

## 签名

请求头 `Magi2-Signature` 的格式是：

```text
t=<unix 秒>,v1=<hex(HMAC-SHA256(secret, "<t>.<原始请求体>"))>
```

签名密钥（`whsec_` 开头）在 [设置 → API 密钥](https://magi2ai.dev/settings/apikeys) 页面查看，每个账户一个。验证步骤：

1. 从请求头解析出 `t` 和 `v1`；
2. 拒绝 `t` 与当前时间相差超过 5 分钟的请求（防重放）；
3. 用密钥对 `t + "." + 原始请求体` 计算 HMAC-SHA256，与 `v1` 做常量时间比较；
4. 通过后再解析 JSON。

一定要用原始请求体：先解析 JSON 再序列化，字节会变，签名就对不上。

## Node.js 验证

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

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

// Keep the raw body: the signature covers the exact bytes we sent.
app.post('/hooks/magi2', express.raw({ type: 'application/json' }), (req, res) => {
  const header = req.get('Magi2-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');
  const ok = crypto.timingSafeEqual(Buffer.from(expected), Buffer.from(v1));
  if (!ok) 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 验证

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

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

@app.post("/hooks/magi2")
def magi2_hook():
    header = request.headers.get("Magi2-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
```

## 投递规则

- 地址必须是 `https`，不能带用户名密码，不能指向 localhost、内网域名或 IP 地址，最长 500 个字符；
- 每支视频只尝试一次，超时 10 秒，不跟随重定向；
- 返回任何 2xx 即可；我们不会重试，所以请把较慢的处理放到队列里，先返回 200；
- 没收到回调时，用 `GET /api/v1/videos/{id}` 查询结果。

更多接口说明见 [API 文档](https://magi2ai.dev/docs)。

## FAQ

### Webhook 会重试吗？

不会。每支视频只投递一次（10 秒超时）。没收到时请用 GET /api/v1/videos/{id} 轮询。

### 在哪里找到签名密钥？

登录后在 设置 → API 密钥 页面，可以显示并复制 whsec_ 开头的签名密钥。

### 为什么签名验证失败？

最常见的原因是用解析后再序列化的 JSON 计算签名。请用收到的原始字节，并确认使用的是本账户的密钥。


---

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