Webhook Integration Guide
Hệ thống SOS dispatch webhook events khi có sự kiện quan trọng xảy ra. Sử dụng webhooks để tích hợp real-time với WMS, OMS, BI dashboard, alerting systems, v.v.
1. Đăng Ký Webhook
Tạo subscription
POST /api/webhooks
Content-Type: application/json
{
"subscriber": "wms-system",
"event_type": "seller.order_blocked",
"endpoint_url": "https://your-wms.com/webhook/sos",
"secret_key": "your_hmac_secret_key_here",
"retry_count": 3,
"timeout_seconds": 30
}
| Field | Required | Description |
|---|---|---|
subscriber | ✅ | Tên hệ thống subscriber |
event_type | ✅ | Event type muốn nhận (xem bên dưới) |
endpoint_url | ✅ | URL nhận webhook POST |
secret_key | ✅ | Key để verify HMAC signature |
retry_count | ❌ | Số lần retry (default: 3) |
timeout_seconds | ❌ | Timeout mỗi request (default: 30s) |
Quản lý subscriptions
GET /api/webhooks # List all active subscriptions
PATCH /api/webhooks/:id # Update subscription
DELETE /api/webhooks/:id # Deactivate subscription
GET /api/webhooks/logs # View delivery logs
2. Webhook Event Types
| Event Type | Trigger | Payload |
|---|---|---|
seller.score_finalized | Admin finalize monthly score | seller_code, period, total_sos, tier |
seller.tier_changed | Tier thay đổi sau finalize | seller_code, previous_tier, new_tier, new_sos |
seller.order_blocked | Seller bị block đơn (payment overdue) | seller_code, period, reason |
seller.order_unblocked | Seller được unblock | seller_code, period |
seller.surcharge_created | Phụ phí mới tạo | seller_code, period, surcharge_type, amount |
seller.appeal_decided | Appeal có quyết định | seller_code, period, component, status, decision |
seller.grace_period_ended | Hết grace period | seller_code, period |
3. Webhook Delivery Format
Khi một event xảy ra, hệ thống gửi HTTP POST đến endpoint_url của tất cả active subscribers cho event đó.
Request Headers
POST /webhook/sos HTTP/1.1
Content-Type: application/json
X-Boxme-SOS-Signature: <hmac_sha256_hex>
X-Boxme-SOS-Event: seller.score_finalized
Request Body
{
"seller_code": "SEL001",
"period": "2026-02",
"total_sos": 85.7,
"tier": "Gold"
}
4. HMAC Signature Verification
Hệ thống ký payload bằng HMAC-SHA256 sử dụng secret_key bạn cung cấp khi đăng ký. Bạn PHẢI verify signature ở phía receiver để đảm bảo request đến từ Boxme SOS.
Node.js Example
const crypto = require('crypto');
function verifyWebhook(req) {
const signature = req.headers['x-boxme-sos-signature'];
const event = req.headers['x-boxme-sos-event'];
const body = JSON.stringify(req.body);
const expected = crypto
.createHmac('sha256', process.env.WEBHOOK_SECRET)
.update(body)
.digest('hex');
if (signature !== expected) {
throw new Error('Invalid webhook signature');
}
console.log(`Received event: ${event}`, req.body);
return true;
}
Python Example
import hmac
import hashlib
import json
def verify_webhook(request):
signature = request.headers.get('X-Boxme-SOS-Signature')
event = request.headers.get('X-Boxme-SOS-Event')
body = json.dumps(request.json, separators=(',', ':'))
expected = hmac.new(
WEBHOOK_SECRET.encode('utf-8'),
body.encode('utf-8'),
hashlib.sha256
).hexdigest()
if not hmac.compare_digest(signature, expected):
raise ValueError('Invalid webhook signature')
print(f'Received event: {event}', request.json)
return True
5. Retry Logic
Khi delivery thất bại (HTTP status ≠ 2xx hoặc timeout), hệ thống sẽ:
- Retry tối đa
retry_countlần (default: 3) - Mỗi retry gửi lại request giống hệt
- Nếu tất cả retries fail → status =
failed
Delivery Statuses
| Status | Description |
|---|---|
success | HTTP 2xx received |
retrying | Đang retry (chưa hết retry count) |
failed | Tất cả retries thất bại |
6. Monitoring Deliveries
Xem delivery logs
GET /api/webhooks/logs?subscription_id=1&status=failed&page=1&limit=50
{
"data": [
{
"id": 100,
"subscription_id": 1,
"event_type": "seller.score_finalized",
"payload": "{...}",
"response_status": 500,
"response_body": "Internal Server Error",
"attempt": 3,
"status": "failed",
"delivered_at": "2026-02-22T10:00:00Z",
"subscriber": "wms-system",
"endpoint_url": "https://your-wms.com/webhook/sos"
}
],
"page": 1, "limit": 50
}
7. Best Practices
- Luôn verify HMAC signature trước khi process payload
- Respond nhanh (< 5s): trả 200 OK ngay, xử lý async
- Idempotent handler: webhook có thể deliver trùng → xử lý dedup
- Monitor failed deliveries: check
/api/webhooks/logs?status=failedđịnh kỳ - Rotate secret keys: update secret qua
PATCH /api/webhooks/:id