外观
Webhook 接入与验签
应用使用 server_webhook 时,广告系统在奖励达标后建立持久化通知任务,由独立 Worker POST 到配置的业务后端地址。接收方完成验签与自己的数据库幂等发奖后,返回约定的确认 JSON。
这是可重试的异步交付。网络超时、进程重启或响应丢失都可能导致重复通知,接收端必须按 grantId 去重。通知接收成功不等于资产到账,只有真实业务事务提交后才能确认 fulfilled。
配置接收地址
在管理后台将应用 deliveryMode 设置为 server_webhook,配置 webhookUrl。当前约束:
| 项目 | 当前行为 |
|---|---|
| 协议 | 生产发送要求 HTTPS |
| 端口 | 443,URL 可省略默认端口 |
| URL | 不允许用户名、密码或 fragment(#...) |
| 地址解析 | DNS 返回地址必须通过当前公网地址检查;请求固定到检查过的地址 |
| 重定向 | 不跟随;3xx 不算成功确认 |
| DNS 超时 | 最多 3 秒 |
| 单次发送截止 | DNS 与 HTTP 合计约 8 秒的绝对截止;连接也有超时 |
| 响应大小 | 响应文本超过 65,536 字符时中止;应返回很小的 JSON |
| 本地调试 | 仅非 production 且 ALLOW_LOCAL_WEBHOOKS=true 时,允许 localhost/127.0.0.1/::1 本机地址调试 |
内网服务、私有 IP、仅 VPN 可达地址不能作为常规生产通知目标。把公网 HTTPS 入口反向代理到自己的业务服务即可;入口不能改写待验签的原始 JSON 内容。
地址与签名密钥在广告会话创建时冻结到奖励记录。后台修改 webhookUrl 后,历史奖励仍会发送到旧地址。迁移接收服务时需保留旧地址,直到其未完成奖励处理完,或在旧地址后使用保持请求体的服务转发;不要只依赖 HTTP 301/302 跳转。
请求头与 payload
http
POST /webhooks/rewards HTTP/1.1
Content-Type: application/json
X-Ad-Timestamp: 1794988805
X-Ad-Notification-Id: 5a84cb21-5514-4760-a4ef-45ae010752b4
X-Ad-Signature: <64位十六进制HMAC-SHA256>1
2
3
4
5
2
3
4
5
| 请求头 | 类型 | 含义 |
|---|---|---|
X-Ad-Timestamp | Unix 秒数字符串 | 本次发送时间,每次重试刷新;不是毫秒 |
X-Ad-Notification-Id | string,当前 UUID | 同一通知任务的稳定 ID |
X-Ad-Signature | hex string,64 字符 | HMAC-SHA256 签名 |
Content-Type | application/json | UTF-8 JSON 请求体 |
json
{
"notificationId": "5a84cb21-5514-4760-a4ef-45ae010752b4",
"grantId": "7fc5e85b-6aa3-40c2-92cc-5e6015d0c5cc",
"rewardId": "cm_reward_01",
"appId": "app_game_public",
"subjectId": "player_42",
"sessionId": "cm_session_01",
"placementCode": "daily_bonus",
"rewardIntentId": "cm_intent_01",
"businessKey": "daily-bonus:player_42:2026-11-18",
"reward": {
"code": "coin",
"type": "currency",
"amount": 100
},
"createdAt": "2026-11-18T08:00:00.000Z"
}1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
| 字段 | 类型 | 必有 | 说明 |
|---|---|---|---|
notificationId | string | 是 | 必须与 X-Ad-Notification-Id 一致 |
grantId | string | 是 | 稳定资产发放去重键;不是 rewardId |
rewardId | string,最多 32 | 是 | 广告系统奖励 ID,用于查询结果关联与后端确认 |
appId | string,最多 64 | 是 | 公开应用 ID,必须匹配接收端配置的应用 |
subjectId | string,1–191 | 是 | 业务后端签发 Token 时的用户 ID,大小写敏感 |
reward.code | string,1–64 | 是 | 奖励代码,映射到自己后端的白名单处理器 |
reward.type | enum string | 是 | currency / energy / revive / item / entitlement / custom |
reward.amount | integer,1–1,000,000,000 | 是 | 数量;来自创建会话时的后台配置快照 |
createdAt | ISO 时间 string | 是 | 奖励记录的创建时间,不是本次投递时间,也不是资格达成时间 |
payload 还包含以下业务关联字段:
| 字段 | 类型 | 必有 | 说明 |
|---|---|---|---|
sessionId | string,最多 32 | 是 | 对应观看会话 |
placementCode | string,1–64 | 是 | 广告位业务编码 |
rewardIntentId | string / null | 是 | 绑定的业务意图,未使用意图时为 null |
businessKey | string / null | 是 | 创建意图时后端指定的业务操作键,未使用意图时为 null |
启用 requireRewardIntent 的广告位,接收方应将 rewardIntentId/businessKey/subjectId/placementCode 与自己保存的授权记录核对。这些字段被原始 body 签名覆盖,不能再相信客户端另外提交的局 ID 来替代它们。当前仍不回传资格完成时间、密钥版本或任意自定义 metadata。
签名计算
签名密钥为该奖励创建时使用的应用 serverKey,按 UTF-8 字符串直接作为 HMAC key;不是 SHA256(serverKey)、不是内部加密密文,也不是全局 JWT_SECRET。
text
signingBytes = UTF8(timestamp + "." + notificationId + ".") + 原始HTTP请求体字节
signature = lowercaseHex(HMAC-SHA256(serverKey, signingBytes))1
2
2
Node 等价实现:
js
const expected = createHmac('sha256', serverKey)
.update(`${timestamp}.${notificationId}.`, 'utf8')
.update(rawBodyBuffer)
.digest();1
2
3
4
2
3
4
必须使用收到的原始请求体。先 JSON.parse 再 JSON.stringify 会改变空格、属性顺序或转义表示,使签名失败。Express/Nest 等框架应为这条路由保留 raw body,并保证在全局 JSON 解析器丢失原文之前取得字节;下方使用 Node 原生 HTTP 避免中间件顺序问题。
接收方建议检查时间差不超过 5 分钟,并同步服务器时钟。这个 5 分钟是接收方反重放策略,不是广告系统的奖励有效期。重试会生成新的 timestamp 和 signature,所以前一天产生的奖励在今天重试仍可通过当前时间窗口。
完整 Node 原始 body 验签接收器
以下为 Node 22+ 的 ESM 示例,可保存为 ad-webhook.mjs。它实现 HTTP 路由、原始字节读取、大小限制、时间窗口、常量时间签名比较、新旧密钥验签、应用绑定、字段校验和成功/失败响应。
唯一需要接入方提供的是 fulfillGrant:它必须调用自己的业务数据库事务,成功返回时代表已经实际发奖;示例不会用内存集合伪装真实入账。
js
import { createServer } from 'node:http';
import { createHmac, timingSafeEqual } from 'node:crypto';
class WebhookError extends Error {
constructor(status, message) {
super(message);
this.status = status;
}
}
function sendJson(response, status, value) {
response.writeHead(status, {
'Content-Type': 'application/json; charset=utf-8',
'Cache-Control': 'no-store',
});
response.end(JSON.stringify(value));
}
function singleHeader(request, name) {
// 显式拒绝重复安全头,避免代理/框架合并方式不一致。
let count = 0;
for (let index = 0; index < request.rawHeaders.length; index += 2) {
if (request.rawHeaders[index].toLowerCase() === name) count++;
}
const value = request.headers[name];
if (count !== 1 || typeof value !== 'string' || !value) {
throw new WebhookError(401, 'Missing or duplicate signature header');
}
return value;
}
async function readRawBody(request) {
const chunks = [];
let length = 0;
for await (const chunk of request) {
const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
length += buffer.length;
if (length > 65_536) throw new WebhookError(413, 'Body too large');
chunks.push(buffer);
}
return Buffer.concat(chunks);
}
function requiredText(value, max, field) {
if (typeof value !== 'string' || value.length < 1 || value.length > max) {
throw new WebhookError(400, `Invalid ${field}`);
}
return value;
}
function nullableText(value, max, field) {
return value === null ? null : requiredText(value, max, field);
}
function verifyNotification(request, rawBody, expectedAppId, verificationKeys) {
const timestamp = singleHeader(request, 'x-ad-timestamp');
const notificationId = singleHeader(request, 'x-ad-notification-id');
const signature = singleHeader(request, 'x-ad-signature');
if (!/^\d{10}$/.test(timestamp) || notificationId.length > 64) {
throw new WebhookError(401, 'Invalid signature headers');
}
if (Math.abs(Date.now() - Number(timestamp) * 1000) > 300_000) {
throw new WebhookError(401, 'Signature timestamp outside allowed window');
}
if (!/^[0-9a-f]{64}$/i.test(signature)) {
throw new WebhookError(401, 'Invalid signature format');
}
const received = Buffer.from(signature, 'hex');
let valid = false;
// keys 只属于预期的同一个应用,可包含当前和尚在过渡期的旧密钥。
for (const key of verificationKeys) {
const expected = createHmac('sha256', key)
.update(`${timestamp}.${notificationId}.`, 'utf8')
.update(rawBody)
.digest();
const matches = timingSafeEqual(received, expected);
valid = matches || valid;
}
if (!valid) throw new WebhookError(401, 'Invalid signature');
let data;
try {
data = JSON.parse(rawBody.toString('utf8'));
} catch {
throw new WebhookError(400, 'Invalid JSON');
}
if (!data || typeof data !== 'object' || Array.isArray(data)) {
throw new WebhookError(400, 'Expected an object');
}
if (data.notificationId !== notificationId) {
throw new WebhookError(400, 'Notification ID mismatch');
}
if (data.appId !== expectedAppId) {
throw new WebhookError(403, 'Unexpected application');
}
const reward = data.reward;
const types = new Set(['currency', 'energy', 'revive', 'item', 'entitlement', 'custom']);
if (!reward || typeof reward !== 'object' || Array.isArray(reward)) {
throw new WebhookError(400, 'Invalid reward');
}
if (
!types.has(reward.type) ||
!Number.isSafeInteger(reward.amount) ||
reward.amount < 1 ||
reward.amount > 1_000_000_000
) {
throw new WebhookError(400, 'Invalid reward type or amount');
}
const createdAt = requiredText(data.createdAt, 64, 'createdAt');
if (!Number.isFinite(Date.parse(createdAt))) {
throw new WebhookError(400, 'Invalid createdAt');
}
// 只把经过验证、业务需要的字段交给发奖函数。
return {
appId: expectedAppId,
grantId: requiredText(data.grantId, 64, 'grantId'),
rewardId: requiredText(data.rewardId, 32, 'rewardId'),
subjectId: requiredText(data.subjectId, 191, 'subjectId'),
sessionId: requiredText(data.sessionId, 32, 'sessionId'),
placementCode: requiredText(data.placementCode, 64, 'placementCode'),
rewardIntentId: nullableText(data.rewardIntentId, 32, 'rewardIntentId'),
businessKey: nullableText(data.businessKey, 128, 'businessKey'),
reward: {
code: requiredText(reward.code, 64, 'reward.code'),
type: reward.type,
amount: reward.amount,
},
};
}
export function createAdWebhookServer({ expectedAppId, verificationKeys, fulfillGrant }) {
if (
typeof expectedAppId !== 'string' ||
!expectedAppId ||
!Array.isArray(verificationKeys) ||
verificationKeys.length === 0 ||
verificationKeys.some((key) => typeof key !== 'string' || key.length < 20) ||
typeof fulfillGrant !== 'function'
) {
throw new Error('Provide application ID, verification keys and database grant handler');
}
const server = createServer(async (request, response) => {
try {
const path = new URL(request.url || '/', 'http://localhost').pathname;
if (request.method !== 'POST' || path !== '/webhooks/rewards') {
return sendJson(response, 404, { error: 'Not found' });
}
const contentType = request.headers['content-type'] || '';
if (
!contentType.toLowerCase().startsWith('application/json') ||
(request.headers['content-encoding'] && request.headers['content-encoding'] !== 'identity')
) {
throw new WebhookError(415, 'Expected uncompressed JSON');
}
const raw = await readRawBody(request);
const grant = verifyNotification(request, raw, expectedAppId, verificationKeys);
// 必须等待真实业务事务提交,重复 grant 返回 repeated:true。
const result = await fulfillGrant(grant);
return sendJson(response, 200, {
grantId: grant.grantId,
status: 'fulfilled',
repeated: Boolean(result?.repeated),
});
} catch (error) {
const status = error instanceof WebhookError ? error.status : 500;
// 不回传数据库异常、密钥或完整用户数据。
return sendJson(response, status, {
error: status === 500 ? 'Reward could not be committed' : error.message,
});
}
});
server.requestTimeout = 15_000;
server.headersTimeout = 10_000;
return server;
}1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
连接自己的业务数据库实现:
js
// server.mjs
import { createAdWebhookServer } from './ad-webhook.mjs';
// 这个文件需要接入方实现,参见业务后端接入页的事务伪代码。
import { fulfillGrantInBusinessDatabase } from './business-rewards.mjs';
const verificationKeys = JSON.parse(process.env.AD_WEBHOOK_KEYS_JSON || '[]');
const server = createAdWebhookServer({
expectedAppId: process.env.AD_PUBLIC_APP_ID,
verificationKeys,
fulfillGrant: fulfillGrantInBusinessDatabase,
});
server.listen(3010, '127.0.0.1'); // 生产由公网 HTTPS 网关转发到此服务。1
2
3
4
5
6
7
8
9
10
11
12
2
3
4
5
6
7
8
9
10
11
12
AD_WEBHOOK_KEYS_JSON 是这个示例接收端采用的环境变量名,内容为当前/历史 serverKey 的 JSON 数组;它不是广告系统新增的配置项。密钥由密钥管理或安全环境配置注入,不写入源码、前端构建参数或日志。
业务数据库实现见 事务发奖方案。由于通知发送方约 8 秒超时,接收端数据库操作也应有合理超时,尽快提交;如果响应丢失,依靠同一 grantId 重试恢复。
成功确认的严格语义
合格响应必须同时满足:
- HTTP 状态为 2xx。
- 响应体可解析为 JSON。
grantId与本次通知中的 grantId 完全一致。status严格等于小写字符串fulfilled。
http
HTTP/1.1 200 OK
Content-Type: application/json
{"grantId":"7fc5e85b-6aa3-40c2-92cc-5e6015d0c5cc","status":"fulfilled"}1
2
3
4
2
3
4
允许额外字段,例如 repeated: true。以下情况都视为失败并触发重试:空 204、纯文本 OK、{"ok":true}、status 为 FULFILLED、返回其他 grantId、业务错误 JSON 配合 200、3xx 重定向、HTML 网关页。
重复通知命中已入账 grantId 后,核对不可变字段一致,再返回同样的成功确认。不能因为“这条已经处理过”就返回 409,否则广告系统会继续认为投递失败。
重试节奏与任务状态
当前实现是首次发送加最多 6 次自动重试,共 7 次尝试。每次失败后,相对于该次失败处理完成时间安排下一次;没有随机抖动,也不是全部相对于第一次发送的绝对时间表。
| 本次尝试失败 | 到下一次尝试的等待 |
|---|---|
| 第 1 次 | 1 分钟 |
| 第 2 次 | 5 分钟 |
| 第 3 次 | 15 分钟 |
| 第 4 次 | 1 小时 |
| 第 5 次 | 6 小时 |
| 第 6 次 | 24 小时 |
| 第 7 次 | 停止自动重试,任务标为 failed |
等待间隔累计约 31 小时 21 分钟,实际还受 Worker 运行状态和处理耗时影响。奖励的 24 小时首次领取期限不会截断已有 Webhook 任务。通知仍有自动或人工重试可能时,不要提前删除业务幂等记录。
Worker 使用数据库任务租约领取工作。若进程崩溃,过期租约可被其他 Worker 接管,因此即使一次 HTTP 已送达,也可能再次发送。这种设计需要接收方的持久化去重,而不是依赖内存集合或“只启动一个实例”。
达到 failed 后,运营可在管理后台查看投递错误与尝试记录,修复原因后手动重试。手动重试重置自动尝试计数,沿用原 grantId 和 notificationId;不会修改奖励创建时冻结的通知 URL/密钥。奖励的 deliveryStatus 可能仍为 DELIVERY_PENDING,不存在一个公开的奖励 FAILED 状态。
密钥轮换与多应用
应用 serverKey 有两个用途:业务后端请求 API 的 X-App-Key,以及 Webhook 的 HMAC 签名密钥。API 轮换后旧 key 立即失去请求认证权限;历史奖励的签名 key 则不会被改写。
建议轮换步骤:
- 接收端先支持按应用加载多把验证密钥,并保留当前 key。
- 在管理后台轮换,安全取得新 key,尽快同步业务后端 API 调用配置和接收端验证列表。
- API 调用只使用新 key,Webhook 接收端在过渡期间同时接受该应用的新旧 key。
- 确认所有使用旧 key 的奖励都已完成、无需再重试,并完成历史对账后,再移除旧 key。
当前没有 X-Ad-Key-Version 请求头,也没有自动发布验签公钥的接口。只用新 key 验签会拒绝历史会话的合法通知;仅保留旧 key 会拒绝新会话通知。
多应用可以各用独立路径/接收实例,并配置各自 expectedAppId/key 列表。若共用一条路由,可从未验证 JSON 中读取 appId 仅用于从本地允许名单选择候选密钥,然后必须对完整原始 body 验签,并重新检查 appId;不能在验签前执行发奖,也不能根据任意请求内容联网获取密钥或在所有应用密钥中无差别匹配后跳过应用绑定。
常见排查
| 现象 | 优先检查 |
|---|---|
| 每次签名都失败 | 是否拿到原始字节;是否误用毫秒;是否使用 serverKey 原文;签名串的两个点号是否一致 |
| 只有轮换前的奖励失败 | 是否还保留该应用旧验证 key;旧奖励仍用冻结 key |
| 只有部署到公网后失败 | 网关是否重写 JSON;时钟是否同步;是否重定向到登录页 |
| 后台显示 HTTPS/地址错误 | 域名是否解析到私有/受限地址;端口是否为 443;URL 是否包含 userinfo/fragment |
| 服务已经加金币,但广告系统一直重试 | 是否先提交后返回;响应是不是 JSON;grantId 是否匹配;status 是否小写 fulfilled;是否超 8 秒 |
| 只有重试造成重复金币 | 业务数据库是否有唯一 grantId;资产修改与去重记录是否同一事务;是否错误用 notificationId 或内存去重 |
| 已改新 Webhook URL,旧地址仍有请求 | 奖励创建时冻结地址,历史奖励属于预期行为 |
验签失败不应发放任何权益。数据库异常返回非 2xx,让广告系统重试;不要为了停止告警返回伪成功。日志保留 notificationId、grantId、rewardId 和失败分类即可,避免输出原始密钥或整个用户资料。