Skip to content
bitzorcas
EN

Reference

Webhooks 模块

完整的 Webhook 系统 — 订阅管理、HMAC-SHA256 请求签名、指数退避重试、死信队列、IP 白名单和每订阅者限流。

Last updated

Webhooks 模块提供生产级 Webhook 投递系统,支持订阅 CRUD、HMAC-SHA256 请求签名、可配置重试策略、死信队列、IP 白名单和每订阅者限流。

端点

端点方法描述
/api/webhooks/subscriptionsPOST创建订阅
/api/webhooks/subscriptionsGET列出订阅
/api/webhooks/subscriptions/{id}GET获取订阅详情
/api/webhooks/subscriptions/{id}PATCH更新订阅
/api/webhooks/subscriptions/{id}DELETE取消订阅
/api/webhooks/subscriptions/{id}/rotate-secretPOST轮换签名密钥
/api/webhooks/subscriptions/{id}/pingPOST测试投递

架构

WebhookSubscriptionService
├── IWebhookSubscriptionRepository → SqlSugarWebhookSubscriptionRepository
├── IWebhookEventTypeRegistry → InMemoryWebhookEventTypeRegistry
├── IWebhookHttpClient → DefaultWebhookHttpClient
├── IWebhookDeadLetterQueue → NullWebhookDeadLetterQueue
├── IWebhookIpAllowlistPolicy → AllowAllWebhookIpAllowlistPolicy
└── IWebhookRateLimitPolicy → AllowAllWebhookRateLimitPolicy
WebhookDeliveryService
├── 签名生成 (HMAC-SHA256)
├── 重试策略 (指数退避)
├── 死信队列 (投递失败)
└── 投递日志 (WebhookDeliveryLogEntity)

Webhook 订阅

public class WebhookSubscriptionEntity : TenantSoftDeleteEntityBase
{
public string CallbackUrl { get; set; }
public string EventTypes { get; set; } // 事件类型模式 JSON 数组
public string Secret { get; set; } // HMAC 签名密钥(哈希后)
public bool IsActive { get; set; }
public int MaxRetries { get; set; }
}

请求签名

每次 Webhook 投递包含 HMAC-SHA256 签名头:

POST /webhook/callback HTTP/1.1
Content-Type: application/json
X-Webhook-Signature: sha256=abc123...
X-Webhook-Timestamp: 2026-06-22T10:00:00Z
X-Webhook-Event: ticket.created
X-Webhook-Delivery-Id: del-789
X-Webhook-Subscription-Id: sub-456
{"eventId": "...", "eventType": "ticket.created", "payload": {...}}

验证(订阅者侧):

var signature = WebhookSignature.Compute(secret, payload, timestamp);
var isValid = signature == request.Headers["X-Webhook-Signature"];

重试策略

指数退避,可配置限制:

public class WebhookRetryPolicy
{
public int MaxRetries { get; set; } = 5;
public TimeSpan InitialDelay { get; set; } = TimeSpan.FromSeconds(5);
public TimeSpan MaxDelay { get; set; } = TimeSpan.FromHours(1);
public double BackoffMultiplier { get; set; } = 2.0;
}

事件类型模式

订阅支持通配符模式:

ticket.* → 所有工单事件
ticket.created → 仅工单创建
chat.message_sent → 仅新聊天消息
*.created → 所有创建事件

可用事件类型

定义在 WebhookEventTypes 中:

模式来源模块
ticket.*Tickets
chat.*Chat
file.*Files
billing.*PlatformBilling
notification.*Notifications
catalog.*Catalog

投递日志

public class WebhookDeliveryLogEntity : TenantSoftDeleteEntityBase
{
public Guid SubscriptionId { get; set; }
public string EventType { get; set; }
public int HttpStatusCode { get; set; }
public string? ResponseBody { get; set; }
public string? ErrorMessage { get; set; }
public int AttemptNumber { get; set; }
public DateTimeOffset DeliveredAt { get; set; }
}

另见