Skip to main content

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
}
FieldRequiredDescription
subscriberTên hệ thống subscriber
event_typeEvent type muốn nhận (xem bên dưới)
endpoint_urlURL nhận webhook POST
secret_keyKey để verify HMAC signature
retry_countSố lần retry (default: 3)
timeout_secondsTimeout 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 TypeTriggerPayload
seller.score_finalizedAdmin finalize monthly scoreseller_code, period, total_sos, tier
seller.tier_changedTier thay đổi sau finalizeseller_code, previous_tier, new_tier, new_sos
seller.order_blockedSeller bị block đơn (payment overdue)seller_code, period, reason
seller.order_unblockedSeller được unblockseller_code, period
seller.surcharge_createdPhụ phí mới tạoseller_code, period, surcharge_type, amount
seller.appeal_decidedAppeal có quyết địnhseller_code, period, component, status, decision
seller.grace_period_endedHết grace periodseller_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ẽ:

  1. Retry tối đa retry_count lần (default: 3)
  2. Mỗi retry gửi lại request giống hệt
  3. Nếu tất cả retries fail → status = failed

Delivery Statuses

StatusDescription
successHTTP 2xx received
retryingĐang retry (chưa hết retry count)
failedTấ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

  1. Luôn verify HMAC signature trước khi process payload
  2. Respond nhanh (< 5s): trả 200 OK ngay, xử lý async
  3. Idempotent handler: webhook có thể deliver trùng → xử lý dedup
  4. Monitor failed deliveries: check /api/webhooks/logs?status=failed định kỳ
  5. Rotate secret keys: update secret qua PATCH /api/webhooks/:id