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 規格,因此可以使用它的任何函式庫來驗證,也可以自行驗證:
- 以句點串接
webhook-id、webhook-timestamp和原始本文:{id}.{timestamp}.{body}。 - 使用 HMAC-SHA256 和密鑰的位元組進行簽署:也就是
whsec_之後的部分,經 Base64 解碼後的位元組。 - 將結果以 Base64 編碼,與
webhook-signature中v1,之後的簽章比較,並使用常數時間比較。 - 拒絕時間戳記超過 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 訊息,讓您在正式上線前檢查伺服器。