跳到主要内容

菜单

  • 媒体
  • 定价
  • 文档
  • 语言:简体中文

    此页面不提供灰色显示的语言版本。

    • English
    • Español
    • Português
    • Français
    • Deutsch
    • Italiano
    • Nederlands
    • Polski
    • 日本語
    • 한국어
    • Bahasa Indonesia
    • Tiếng Việt
    • Türkçe
    • العربية
    • ไทย
    • Български
    • Català
    • Hrvatski
    • Eesti
    • Magyar
    • Latviešu
    • Lietuvių
    • Srpski
    • Slovenčina
    • Slovenščina
    • Українська
    • Čeština
    • Română
    • Svenska
    • Dansk
    • Norsk bokmål
    • Suomi
    • עברית
    • हिन्दी
    • Tagalog
    • Bahasa Melayu
    • Ελληνικά
    • 简体中文
    • 繁體中文

热门工具

Webhook

作业结束时,Webhook 会向您的服务器发送一条签名消息,您无需反复查询。

本页内容

事件

事件发送时机
job.completed作业已结束,且除已取消的任务外,所有任务均已完成。其结果已可下载。
job.partly_failed作业已结束,部分任务完成,部分任务失败。
job.failed作业已结束,除已取消的任务外,所有任务均失败。
job.cancelled作业在任何任务完成之前被取消。
credits.low工作区的积分低于其“账单”页面上设置的提醒阈值。它与积分不足提醒邮件一同发送,因此关闭该邮件也会停止发送此事件。

作业事件针对使用该工作区 API 密钥启动的作业发送。所有事件及其有效负载,请参阅 Webhook 事件参考。

添加端点

端点是公共互联网上的一个 HTTPS 地址,我们会向它发送消息。您可以在工作区的设置中进入 Webhook,点击添加端点,也可以通过 API 添加。请选择它接收的事件:如果省略 events,则接收所有事件。

curl -X POST https://api.filesokay.com/v1/webhooks \
  -H "Authorization: Bearer $FILESOKAY_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "url": "https://example.com/webhooks/filesokay",
    "events": [
      "job.completed",
      "job.partly_failed",
      "job.failed"
    ]
  }'
const res = await fetch("https://api.filesokay.com/v1/webhooks", {
  method: "POST",
  headers: {
    Authorization: `Bearer ${process.env.FILESOKAY_KEY}`,
    "Content-Type": "application/json",
  },
  body: JSON.stringify({
    url: "https://example.com/webhooks/filesokay",
    events: [
      "job.completed",
      "job.partly_failed",
      "job.failed"
    ]
  }),
});
const endpoint = await res.json();
import os

import requests

res = requests.post(
    "https://api.filesokay.com/v1/webhooks",
    headers={
        "Authorization": f"Bearer {os.environ['FILESOKAY_KEY']}",
    },
    json={
      "url": "https://example.com/webhooks/filesokay",
      "events": [
        "job.completed",
        "job.partly_failed",
        "job.failed"
      ]
    },
)
endpoint = res.json()
响应
{
  "id": "wh_5b0e3c1f9a7d42e8b6c4d2f0a8e61b37",
  "url": "https://example.com/webhooks/filesokay",
  "events": [
    "job.completed",
    "job.partly_failed",
    "job.failed"
  ],
  "enabled": true,
  "disabled_at": null,
  "created_at": "2026-12-03T09:25:50Z",
  "secret": "whsec_…"
}

响应中包含该端点的签名密钥,以 whsec_ 开头。它只显示这一次:请将其保存在您的服务器上。一个工作区最多可拥有 20 个端点。

消息

每条消息都是一个 POST 请求,包含 JSON 请求体和三个请求头:

webhook-id: msg_0f1e2d3c4b5a69788796a5b4c3d2e1f0
webhook-timestamp: 1796289832
webhook-signature: v1,agm4oAVNWfBnEdXQnRGD9O2uh2MVVu8hPeQf/mc6UB4=
请求体
{
  "type": "job.completed",
  "timestamp": "2026-12-03T09:23:52Z",
  "data": {
    "id": "job_a1c9531eeb00434aba0058796f1ca517",
    "operation": "video.compress",
    "status": "completed",
    "client_reference": "lecture-0412",
    "settings": {
      "audio": "keep",
      "codec": "same",
      "method": "target_size",
      "target": {
        "unit": "percent",
        "value": 50
      },
      "frame_rate": "original",
      "resolution": "auto",
      "output_format": "same"
    },
    "created_at": "2026-12-03T09:23:14Z",
    "started_at": "2026-12-03T09:23:33Z",
    "finished_at": "2026-12-03T09:23:50Z",
    "reserved_credits": 2,
    "charged_credits": 1,
    "tasks": [
      {
        "id": "task_3f648f64472b4ea4b88568eea9d4f88c",
        "status": "completed",
        "progress": 100,
        "reserved_credits": 2,
        "charged_credits": 1,
        "inputs": [
          {
            "file_id": "file_3cf0737aefa34b89b7b4443c9467d60c",
            "name": "lecture.mp4"
          }
        ],
        "outputs": [
          {
            "file_id": "file_a1c8014998a14c4da72d6e6a0c74314c",
            "name": "lecture-compressed.mp4",
            "size": 6054914,
            "download_url": "https://…",
            "download_expires_at": "2026-12-06T09:23:50Z"
          }
        ]
      }
    ]
  }
}

对于作业事件,data 即 GET /v1/jobs/{id} 返回的作业,附带新的下载链接和您的 client_reference。

验证签名

在处理每条消息之前,请先验证它。我们的 Webhook 遵循 Standard Webhooks 规范,因此可以使用该规范的任意库来验证,也可以自行验证:

  1. 用点号连接 webhook-id、webhook-timestamp 和原始请求体:{id}.{timestamp}.{body}。
  2. 使用密钥的字节进行 HMAC-SHA256 签名:即 whsec_ 之后的部分,经 Base64 解码。
  3. 将签名转为 Base64,与 webhook-signature 中 v1, 之后的签名进行比较,比较时使用常量时间算法。
  4. 拒绝时间戳超过 5 分钟的消息,以防消息被重放。

请使用原样收到的请求体:一旦经过解析再重新序列化,它就无法与签名匹配了。

import crypto from "node:crypto";
import http from "node:http";

const SECRET = process.env.FILESOKAY_WEBHOOK_SECRET; // whsec_…

// 如果此消息由该端点的签名密钥在最近 5 分钟内签名,则为 true。
function verify(headers, body) {
  const id = headers["webhook-id"];
  const timestamp = headers["webhook-timestamp"];
  if (!id || !(Math.abs(Date.now() / 1000 - Number(timestamp)) <= 300)) {
    return false;
  }

  const key = Buffer.from(SECRET.slice("whsec_".length), "base64");
  const expected = crypto
    .createHmac("sha256", key)
    .update(`${id}.${timestamp}.${body}`)
    .digest();
  return (headers["webhook-signature"] ?? "").split(" ").some((entry) => {
    const [version, signature] = entry.split(",");
    const given = Buffer.from(signature ?? "", "base64");
    return (
      version === "v1" &&
      given.length === expected.length &&
      crypto.timingSafeEqual(given, expected)
    );
  });
}

http
  .createServer((req, res) => {
    let body = "";
    req.setEncoding("utf8");
    req.on("data", (chunk) => (body += chunk));
    req.on("end", () => {
      if (!verify(req.headers, body)) return res.writeHead(400).end();
      res.writeHead(200).end(); // 先响应,再处理业务。
      const message = JSON.parse(body);
      console.log(message.type, message.data.id);
    });
  })
  .listen(3000);
import base64
import hashlib
import hmac
import json
import os
import time
from http.server import BaseHTTPRequestHandler, HTTPServer

SECRET = os.environ["FILESOKAY_WEBHOOK_SECRET"]  # whsec_…


def verify(headers, body):
    """如果此消息由该端点的签名密钥在最近 5 分钟内签名,则为 true。"""
    msg_id = headers.get("webhook-id")
    timestamp = headers.get("webhook-timestamp", "")
    if not msg_id or not timestamp.isdigit() or abs(time.time() - int(timestamp)) > 300:
        return False

    key = base64.b64decode(SECRET.removeprefix("whsec_"))
    signed = f"{msg_id}.{timestamp}.".encode() + body
    expected = base64.b64encode(hmac.new(key, signed, hashlib.sha256).digest()).decode()
    entries = (entry.partition(",") for entry in headers.get("webhook-signature", "").split())
    return any(v == "v1" and hmac.compare_digest(sig, expected) for v, _, sig in entries)


class Webhook(BaseHTTPRequestHandler):
    def do_POST(self):
        body = self.rfile.read(int(self.headers["Content-Length"]))
        if not verify(self.headers, body):
            self.send_response(400)
            self.end_headers()
            return
        self.send_response(200)  # 先响应,再处理业务。
        self.end_headers()
        message = json.loads(body)
        print(message["type"], message["data"].get("id"))


HTTPServer(("", 3000), Webhook).serve_forever()

响应与重试

  • 在 15 秒内返回任意 2xx 状态码。先响应,再处理业务。
  • 其他任何响应、重定向或无响应都会触发重试,在约 3 天内最多再重试 9 次。
  • 持续失败 72 小时的端点会被停用,工作区的管理员会收到一封电子邮件。在“设置”中点击重新启用即可恢复。
  • 同一条消息可能会送达多次。webhook-id 在每次重试中保持不变:请确保每条消息只处理一次。

“设置”中会显示每个端点最近 30 天的投递记录,点击重新发送可再次发送某条消息。发送测试事件会发送一条 webhook.test 消息,方便您在正式上线前检查服务器。