
語言 🇹🇼 繁體中文
概覽
實作
幕後運作
使用 FastComments,可以在評論被新增、更新或從我們的系統中移除時呼叫一個 API 端點。
我們透過 HTTP/HTTPS 的非同步 webhooks 來達成這個目的。
什麼是 Webhooks(網路回呼) 
Webhook 是一種機制,或是兩個系統之間的整合,其中的 "producer" (FastComments) 觸發一個事件 而 "consumer" (您) 則透過 API 呼叫來接收並處理該事件。
支援的事件與資源 
FastComments 僅支援 Comment 資源的 webhooks。
我們支援針對留言的建立、移除與更新的 webhooks。
這些在我們系統中皆被視為獨立事件,因此在 webhook 事件的語義與結構上各有不同。
本地開發設定 
For Local development, use a tool like ngrok.
In order to simplify keeping the system secure, local development follows the same process as setting up and securing other environments.
Step 1: Add "localhost" to domains in your account.
Add "localhost" as a domain here.
Step 2: Pick an API Key
We're going to be adding webhook configuration for your domain, so we'll need an API key. You can do that here.
Under "Associate with domain" - select your "localhost" domain.
注意:或者,您也可以為所有測試活動與暫存環境使用單一 API Secret。只要新增一個針對 "All Domains" 的 API Secret,並為它命名,例如 "test"。
請確保您已為生產網域定義 API Secret。其他所有網域的事件將使用萬用(測試)密鑰。
Step 3: Add Your Webhook
While running ngrok or similar tool, set the value for "localhost" here.
When clicking Send Test Payload, we will send two test events to check that you validate the API key.
Once it validates, hit Save.
Step 4: Add A Comment
Now you can add, edit, or delete comments and should see us call your local development machine with the events, using your testing API key. There may be up to 30 seconds delay for the events to reach your machine.
設定 
對於 localhost,請按照與 production 相同的步驟操作。請確保您已設定 production 網域與 API Secrets。
首先,前往 Webhooks 管理。可透過 Manage Data -> Webhooks 存取。
The configuration page appears as follows:
在此頁面中,您可以為每種類型的留言事件指定端點。
對於每種事件類型,請務必點擊 Send Test Payload 以確認您的整合設定正確。詳情請參見下一節「Testing」。
測試 
在 Webhooks 管理介面中,每個事件類型 (Create, Update, Delete) 都有 Send Test Payload 按鈕。Create 和 Update 事件會傳送一個範例的 WebhookComment 物件,而測試 Delete 時則會傳送只有 ID 的範例請求主體。
驗證有效負載
當測試您的 webhook 整合時,請確認收到的請求包含下列標頭:
token- Your API SecretX-FastComments-Timestamp- Unix timestamp (seconds)X-FastComments-Signature- HMAC-SHA256 signature
使用 HMAC 簽章驗證來確保有效負載的真實性。
測試工具
在開發期間,您可以使用像 webhook.site 或 ngrok 這類工具來檢查收到的 webhook 有效負載。
事件類型
- Create Event: Triggered when a new comment is created. Default method: PUT
- Update Event: Triggered when a comment is edited. Default method: PUT
- Delete Event: Triggered when a comment is deleted. Default method: DELETE
每個事件在請求主體中包含完整的評論資料(有關有效負載格式,請參閱 Data Structures)。
資料結構 
透過 webhook 傳送的唯一結構為下方以 TypeScript 描述的 WebhookComment 物件。
WebhookComment 物件結構
"Create" 事件結構
"create" 事件的請求主體為 WebhookComment 物件。
"Update" 事件結構
"update" 事件的請求主體為 WebhookComment 物件。
"Delete" 事件結構
"delete" 事件的請求主體為 WebhookComment 物件。
Change as of Nov 14th 2023
Previously the "delete" event request body only contained the comment id. It now contains the full comment at the time of deletion.
Run 
When users are tagged in a comment, the information is stored in a list called mentions. Each object in that list
has the following structure.
Run 
HTTP 方法
您可以在管理面板中為每種 webhook 事件類型設定 HTTP 方法:
- Create Event: POST or PUT (default: PUT)
- Update Event: POST or PUT (default: PUT)
- Delete Event: DELETE, POST, or PUT (default: DELETE)
由於所有請求都包含 ID,Create 與 Update 操作預設為冪等(PUT)。重複相同的 Create 或 Update 請求不應在您端產生重複的物件。
請求標頭
每個 webhook 請求都包含下列標頭:
| 標頭 | 說明 |
|---|---|
Content-Type |
application/json |
token |
Your API Secret |
X-FastComments-Timestamp |
Unix timestamp (seconds) when the request was signed |
X-FastComments-Signature |
HMAC-SHA256 signature (sha256=<hex>) |
See 安全性與 API 令牌 for information on verifying the HMAC signature.
安全性與 API 令牌 
FastComments 的 webhook 請求包含多種驗證機制以確保安全性。
Headers Sent
| Header | Description |
|---|---|
token |
您的 API Secret(為了向後相容) |
X-FastComments-Timestamp |
Unix 時間戳(秒),表示請求簽名的時間 |
X-FastComments-Signature |
載荷的 HMAC-SHA256 簽名 |
HMAC Signature Verification (Recommended)
我們強烈建議驗證 HMAC 簽名,以確保 webhook 載荷為真實且未被竄改。
Signature Format: sha256=<hex-encoded-signature>
How the signature is computed:
- 串接:
timestamp + "." + JSON_payload_body - 使用您的 API Secret 作為金鑰計算 HMAC-SHA256
- 將結果進行十六進位編碼
Example Verification (Node.js)
const crypto = require('crypto');
function verifyWebhookSignature(req, apiSecret) {
const timestamp = req.headers['x-fastcomments-timestamp'];
const signature = req.headers['x-fastcomments-signature'];
if (!timestamp || !signature) {
return false;
}
// 驗證時間戳記是否為近期(5 分鐘內)
const now = Math.floor(Date.now() / 1000);
if (Math.abs(now - parseInt(timestamp, 10)) > 300) {
return false; // 防止重放攻擊
}
// 驗證簽名
const payload = JSON.stringify(req.body);
const expectedSignature = crypto
.createHmac('sha256', apiSecret)
.update(`${timestamp}.${payload}`)
.digest('hex');
return signature === `sha256=${expectedSignature}`;
}
Example Verification (Python)
import hmac
import hashlib
import time
import json
def verify_webhook_signature(headers, body, api_secret):
timestamp = headers.get('X-FastComments-Timestamp')
signature = headers.get('X-FastComments-Signature')
if not timestamp or not signature:
return False
# 驗證時間戳記是否為近期
now = int(time.time())
if abs(now - int(timestamp)) > 300:
return False
# 驗證簽名
payload = json.dumps(body, separators=(',', ':'))
message = f"{timestamp}.{payload}"
expected = hmac.new(
api_secret.encode(),
message.encode(),
hashlib.sha256
).hexdigest()
return signature == f"sha256={expected}"
Example Verification (PHP)
function verifyWebhookSignature($headers, $body, $apiSecret) {
$timestamp = $headers['X-FastComments-Timestamp'] ?? null;
$signature = $headers['X-FastComments-Signature'] ?? null;
if (!$timestamp || !$signature) {
return false;
}
// 驗證時間戳記是否為近期(5 分鐘內)
$now = time();
if (abs($now - intval($timestamp)) > 300) {
return false;
}
// 驗證簽名
$payload = json_encode($body, JSON_UNESCAPED_SLASHES);
$message = $timestamp . '.' . $payload;
$expectedSignature = 'sha256=' . hash_hmac('sha256', $message, $apiSecret);
return hash_equals($expectedSignature, $signature);
}
Legacy Authentication
包含您 API Secret 的 token 標頭仍然會為了向後相容而發送。然而,我們建議遷移到 HMAC 驗證以提升安全性,因為它可以防止重放攻擊。
運作原理與重試處理 
系統中對 Comment 物件的所有變更都會觸發一個事件,該事件最終會進入佇列。
初始的 webhook 事件通常會在事件來源發生後約六秒內發送。
你可以在 Webhooks 管理介面中監控此佇列,以防你的 API 故障。
如果對你的 API 的請求失敗,我們會依排程將其重新放入佇列。
該排程為 1 Minute * the retry count。如果呼叫失敗一次,系統將在
一分鐘後重試。如果失敗兩次,則會等待兩分鐘,依此類推。這樣做是為了
避免在你因為負載相關原因而出現故障時,對你的 API 造成過大的負載。
Webhooks 可以從 記錄頁面 取消。
結論
以上即為我們的 Webhooks 文件。
我們希望您覺得 FastComments 的 Webhook 整合容易理解且快速設定。
如果您發現我們的文件有任何遺漏,請在下方讓我們知道。