返回首頁

SMTPDog 開發者串接文件

清晰透明的串接規範:網域驗證、SMTP 與 Email API、API Key、Webhook 驗簽與常見問題排查。

06 · webhooks

Webhook

接收郵件狀態事件,驗證簽章並以冪等方式處理重試。

1. 建立接收端點

使用會話 Token 管理 /webhooks,建立僅傳 url。建議公開 HTTPS,私網與回環不可用,不跟隨重新導向。PATCH 可改 url 或 active/disabled,目前無事件選擇欄位。secret 在建立及讀取時均可能回傳,須安全保存,並非 API Key。

curl -X POST "${SMTPDOG_API_ORIGIN}/webhooks" \
  -H "Authorization: Bearer ${SMTPDOG_SESSION_TOKEN}" \
  -H "Content-Type: application/json" \
  --data '{"url":"https://example.com/hooks/email"}'

curl -X PATCH "${SMTPDOG_API_ORIGIN}/webhooks/${SMTPDOG_WEBHOOK_ID}" \
  -H "Authorization: Bearer ${SMTPDOG_SESSION_TOKEN}" \
  -H "Content-Type: application/json" \
  --data '{"status":"disabled"}'

curl -X GET "${SMTPDOG_API_ORIGIN}/webhooks/${SMTPDOG_WEBHOOK_ID}/deliveries" \
  -H "Authorization: Bearer ${SMTPDOG_SESSION_TOKEN}"

2. 四類狀態事件

目前事件為 sent、bounced、deferred、failed,沒有 opened、clicked、delivered。本文 timestamp 是入列時間,與簽章時間不同。同投遞重試的 event_id 不變,不同端點或重複業務事件可能有不同 ID,不保證嚴格順序或必達。

欄位 / 設定型別 / 狀態說明
event_id / message_idUUID string投遞事件 ID 與郵件 ID 用途不同
event_type / statusstringsent / bounced / deferred / failed
from / tostring單一寄件者與收件者
timestampRFC3339 string入列時間,非簽章 Unix 秒數
smtp_responsestring可省略 SMTP 情境
{
  "event_id": "00000000-0000-4000-8000-000000000001",
  "event_type": "sent",
  "message_id": "00000000-0000-4000-8000-000000000000",
  "from": "sender@example.com",
  "to": "recipient@example.com",
  "status": "sent",
  "timestamp": "2026-01-01T00:00:00Z"
}

3. 以原始本文驗證簽章

X-Webhook-Signature 為 t=<Unix秒>,v1=<hex>。以完整 secret 位元組計算 HMAC-SHA256(t + "." + 原始本文),不可重新序列化 JSON 或移除 secret 前綴。請用常數時間比較,時間容差由接收方設定,並非平台固定視窗。

package webhookexample

import (
    "crypto/hmac"
    "crypto/sha256"
    "encoding/hex"
    "strconv"
    "strings"
    "time"
)

// raw must be the original body bytes, before JSON parsing.
// tolerance is configured and reviewed by the receiver.
func Verify(secret string, raw []byte, header string,
    now time.Time, tolerance time.Duration) bool {
    if tolerance <= 0 { return false }
    parts := strings.Split(header, ",")
    if len(parts) != 2 { return false }
    fields := map[string]string{}
    for _, part := range parts {
        pair := strings.SplitN(strings.TrimSpace(part), "=", 2)
        if len(pair) != 2 { return false }
        if _, exists := fields[pair[0]]; exists { return false }
        fields[pair[0]] = pair[1]
    }
    ts, err := strconv.ParseInt(fields["t"], 10, 64)
    if err != nil || ts <= 0 || strconv.FormatInt(ts, 10) != fields["t"] {
        return false
    }
    delta := now.Sub(time.Unix(ts, 0))
    if delta > tolerance || delta < -tolerance { return false }
    sig, err := hex.DecodeString(fields["v1"])
    if err != nil || len(sig) != sha256.Size { return false }
    mac := hmac.New(sha256.New, []byte(secret))
    mac.Write([]byte(fields["t"] + "."))
    mac.Write(raw)
    return hmac.Equal(mac.Sum(nil), sig)
}

// Read the raw request body and verify before parsing JSON.
// Then durably deduplicate event_id and apply business idempotency.
// Return 2xx only when safe; this function is not a full receiver.

4. 去重、確認與記錄

驗證後先完成持久化去重及業務冪等處理,再安全回應 2xx。非 2xx 或網路失敗會重試,目前為初次加最多五次,時刻受排程影響。GET /webhooks/{id}/deliveries 回傳最近 50 筆,不含完整 payload 或 event_id。暫停不清空積壓,刪除會移除投遞歷史。目前沒有測試、重送或 secret 輪替介面。