Webhooks
失败 Webhook
当 UKey 操作失败或连接问题时触发。
负载:
json
{
"event": "ukey_malfunction",
"timestamp": 1723809415000,
"error": "错误描述",
"details": {
"type": "operation_failure",
"method": "cus-sec_SpcGetCertNo",
"errors": [
"error1",
"error2"
]
}
}
失败类型:
operation_failure
:UKey 方法执行失败connection_failure
:WebSocket 连接丢失health_check_failure
:健康检查失败
审计 Webhook
为所有请求(成功或失败)触发,用于审计目的。
负载:
json
{
"event": "api_audit",
"timestamp": 1723809415000,
"request_id": "uuid-here",
"method": "cus-sec_SpcGetCertNo",
"request": {},
"response": {},
"success": true,
"error": "",
"duration_ms": 125
}
Webhook 身份验证
Webhooks 使用与传入请求相同的认证机制:
X-Timestamp
头包含当前时间戳X-Signature
头包含 MD5 签名
验证 Webhook 签名
要验证 Webhook 是否来自代理服务器,请实现相同的签名验证:
javascript
// Node.js 示例
const crypto = require('crypto');
function verifyWebhookSignature(req, appSecret) {
const timestamp = req.headers['x-timestamp'];
const signature = req.headers['x-signature'];
const method = req.method;
const path = req.path; // 例如 '/webhook/audit'
const body = req.rawBody; // 原始请求体字符串
// 检查时间戳(3 秒内)
const now = Date.now();
const timeDiff = Math.abs(now - parseInt(timestamp));
if (timeDiff > 3000) {
return false; // 时间戳过期
}
// 计算预期签名
const plaintext = method.toUpperCase() + path + timestamp + body + appSecret;
const expectedSignature = crypto.createHash('md5').update(plaintext).digest('hex');
return expectedSignature === signature;
}
// Express.js 中间件示例
app.use(express.json({
verify: (req, res, buf) => {
req.rawBody = buf.toString('utf8');
}
}));
app.post('/webhook/audit', (req, res) => {
if (!verifyWebhookSignature(req, 'your-secret-key')) {
return res.status(401).json({error: '无效签名'});
}
// 处理 Webhook
console.log('审计事件:', req.body);
res.json({status: '已接收'});
});