追蹤
帶有簽名的送達 webhooks
在控制台的 Webhooks 頁面設定一個 HTTPS 端點。當訊息達到最終狀態時,我們會向該端點發送一個帶有 JSON 事件的 POST 請求。
事件
| type | 當 |
|---|---|
| message.delivered | 訊息已送達。 |
| message.failed | 訊息失敗;data.error 包含錯誤代碼。其費用已退款。 |
{
"id": "evt_8F3K2Q9TZ1MXD",
"type": "message.delivered",
"created_at": "2026-11-07T09:30:17.902Z",
"data": {
"id": "msg_8F3K2Q9TZ1MX",
"object": "message",
"batch_id": "bat_4M7Q1X0PK2RS",
"to": "+14155550123",
"country": "US",
"text": "Your Northwind code is 482913. It expires in 10 minutes.",
"segments": 1,
"price": "0.00507",
"currency": "USD",
"status": "delivered",
"error": null,
"reference": "login-7781",
"created_at": "2026-11-07T09:30:12.418Z",
"sent_at": "2026-11-07T09:30:13.020Z",
"done_at": "2026-11-07T09:30:17.902Z"
}
}標頭與簽名
每次呼叫都帶有三個標頭,符合 Standard Webhooks 格式:
| 標頭 | 數值 |
|---|---|
| webhook-id | 事件 ID (evt_...)。同一 ID 用於同一事件的所有重試。 |
| webhook-timestamp | 此嘗試簽署時的 Unix 時間(秒)。 |
| webhook-signature | v1,後接 base64 HMAC-SHA256 簽名。可能會列出多個簽名,以空格分隔:當任一簽名匹配時,接受該呼叫。 |
驗證呼叫:從控制台取得密鑰(以 whsec_ 開頭),將 whsec_ 之後的部分進行 base64url 解碼以取得密鑰,計算 webhook-id + "." + webhook-timestamp + "." + raw body 的 HMAC-SHA256,將其進行 base64 編碼並與簽名進行固定時間比較。拒絕與您的時鐘相差超過五分鐘的時間戳。始終使用原始主體:解析並重新序列化的 JSON 主體將不匹配。
// Express: keep the raw body, check the signature, then answer 2xx quickly
import crypto from "node:crypto";
import express from "express";
const app = express();
const secret = process.env.BULKSMSAPI_WEBHOOK_SECRET; // whsec_...
app.post("/hooks/sms", express.raw({ type: "application/json" }), (req, res) => {
const id = req.header("webhook-id");
const ts = req.header("webhook-timestamp");
const key = Buffer.from(secret.slice("whsec_".length), "base64url");
const expected = crypto.createHmac("sha256", key).update(`${id}.${ts}.${req.body}`).digest("base64");
const sent = (req.header("webhook-signature") || "").split(" ").map((s) => s.replace(/^v1,/, ""));
const fresh = Math.abs(Date.now() / 1000 - Number(ts)) < 300;
if (!fresh || !sent.some((s) => s.length === expected.length && crypto.timingSafeEqual(Buffer.from(s), Buffer.from(expected)))) {
return res.status(401).end();
}
const event = JSON.parse(req.body);
console.log(event.type, event.data.id, event.data.status);
res.status(204).end();
});
app.listen(3000);# Flask: check the signature on the raw body before parsing it
import base64, hashlib, hmac, json, os, time
from flask import Flask, abort, request
app = Flask(__name__)
SECRET = os.environ["BULKSMSAPI_WEBHOOK_SECRET"] # whsec_...
@app.post("/hooks/sms")
def sms_hook():
msg_id = request.headers.get("webhook-id", "")
ts = request.headers.get("webhook-timestamp", "0")
raw = request.get_data()
key = base64.urlsafe_b64decode(SECRET[len("whsec_"):] + "==")
signed = msg_id.encode() + b"." + ts.encode() + b"." + raw
expected = base64.b64encode(hmac.new(key, signed, hashlib.sha256).digest()).decode()
sent = [s.split(",", 1)[-1] for s in request.headers.get("webhook-signature", "").split()]
if abs(time.time() - int(ts)) > 300 or not any(hmac.compare_digest(s, expected) for s in sent):
abort(401)
event = json.loads(raw)
print(event["type"], event["data"]["id"], event["data"]["status"])
return "", 204<?php
// Plain PHP endpoint, for example /hooks/sms.php
$secret = getenv("BULKSMSAPI_WEBHOOK_SECRET"); // whsec_...
$raw = file_get_contents("php://input");
$id = $_SERVER["HTTP_WEBHOOK_ID"] ?? "";
$ts = $_SERVER["HTTP_WEBHOOK_TIMESTAMP"] ?? "0";
$key = base64_decode(strtr(substr($secret, 6), "-_", "+/"));
$expected = base64_encode(hash_hmac("sha256", "$id.$ts.$raw", $key, true));
$ok = false;
foreach (explode(" ", $_SERVER["HTTP_WEBHOOK_SIGNATURE"] ?? "") as $part) {
$sig = substr($part, strpos($part, ",") + 1);
if (hash_equals($expected, $sig)) $ok = true;
}
if (!$ok || abs(time() - (int)$ts) > 300) {
http_response_code(401);
exit;
}
$event = json_decode($raw, true);
error_log($event["type"] . " " . $event["data"]["id"]);
http_response_code(204);package main
import (
"crypto/hmac"
"crypto/sha256"
"encoding/base64"
"encoding/json"
"io"
"log"
"math"
"net/http"
"os"
"strconv"
"strings"
"time"
)
func smsHook(w http.ResponseWriter, r *http.Request) {
secret := os.Getenv("BULKSMSAPI_WEBHOOK_SECRET") // whsec_...
key, _ := base64.RawURLEncoding.DecodeString(strings.TrimPrefix(secret, "whsec_"))
raw, _ := io.ReadAll(r.Body)
id, ts := r.Header.Get("webhook-id"), r.Header.Get("webhook-timestamp")
mac := hmac.New(sha256.New, key)
mac.Write([]byte(id + "." + ts + "." + string(raw)))
expected := base64.StdEncoding.EncodeToString(mac.Sum(nil))
sec, _ := strconv.ParseInt(ts, 10, 64)
ok := false
for _, part := range strings.Fields(r.Header.Get("webhook-signature")) {
sig := part[strings.Index(part, ",")+1:]
if hmac.Equal([]byte(sig), []byte(expected)) {
ok = true
}
}
if !ok || math.Abs(float64(time.Now().Unix()-sec)) > 300 {
w.WriteHeader(http.StatusUnauthorized)
return
}
var event struct {
Type string
Data map[string]any
}
json.Unmarshal(raw, &event)
log.Println(event.Type, event.Data["id"], event.Data["status"])
w.WriteHeader(http.StatusNoContent)
}
func main() {
http.HandleFunc("/hooks/sms", smsHook)
log.Fatal(http.ListenAndServe(":3000", nil))
}回應與重試
- 在 10 秒內以任何 2xx 狀態回應。回應後從佇列中進行慢速工作。
- 不追蹤重定向:將設定指向最終地址。
- 超時或回應非 2xx 狀態的呼叫將在 30 秒、2 分鐘、10 分鐘、30 分鐘、1 小時、2 小時、4 小時、8 小時、8 小時後重試:總共 10 次嘗試,約從第一次嘗試起 24 小時。
- 每次嘗試都會在 Webhooks 頁面上列出,包含 HTTP 狀態和所花費的時間。
重複與順序
事件可能會到達兩次,例如當您的端點保存了它但回應丟失時。儲存 webhook-id 並跳過已處理的 id。不同訊息的事件可能以任何順序到達;請讀取 data.status 和 data.done_at,而不是依賴到達順序。
端點規則
- 僅限 HTTPS,使用公開主機名稱(無 IP 字面值、localhost 或私有網路)。
- 密鑰可以隨時在 Webhooks 頁面上更換;之後簽署的呼叫將使用新密鑰。
- 移除端點將停止新事件;已完成訊息的狀態將保留以供輪詢。