外观
奖励资格与交付
广告系统产生一笔奖励资格和稳定的 grantId。APP 或业务后端负责兑现金币、体力、道具、复活等权益。奖励资格通过、凭证已领取、业务资产已到账是不同状态。 初版没有通用钱包、现金支付、提现或游戏资产账户。
三个需要分别判断的问题
| 问题 | 读取字段 | 说明 |
|---|---|---|
| 是否满足观看规则? | reward.eligibility | 服务端依据会话和证据判定 |
| 通过什么方式交付? | reward.deliveryMode | 创建会话时从应用配置快照 |
| 是否已经领取或确认? | reward.deliveryStatus | 广告系统中的交付进度,不能替代游戏账本 |
一次 complete 请求并不保证播放结束或资格成立;证据不足时可能仍返回 SHOWING + PENDING。提前关闭后的会话也可能是 ENDED + PENDING。一次 claim 成功会返回 CLAIMED,但并不会自动修改你的金币数据库。
关键字段
ts
import type { Reward } from './lib/ad-client';
export function describeReward(reward: Reward): string {
return [
`${reward.amount} ${reward.code}`,
`type=${reward.type}`,
`grantId=${reward.grantId}`,
`eligibility=${reward.eligibility}`,
`delivery=${reward.deliveryMode}/${reward.deliveryStatus}`,
].join(' · ');
}1
2
3
4
5
6
7
8
9
10
11
2
3
4
5
6
7
8
9
10
11
| 字段 | 用途 |
|---|---|
id | 广告系统内部的奖励记录 ID,用于 claim()、reportApplied() 等接口 |
grantId | 跨重试保持不变的发奖标识;本地或服务端入账的防重依据 |
sessionId | 对应广告会话;当前客户端类型中是可选字段 |
code | 业务奖励代码,例如 coins、energy |
type | 业务奖励类型,客户端或服务端自行解释 |
amount | 正整数数量,不能由客户端修改后作为可信发奖金额 |
rewardIntentId / businessKey | 有后端场景中关联已验证的业务机会;没有绑定时可能为空 |
placementCode | 对应业务广告位,便于核对入账场景 |
目前每个激励会话对应一个奖励条目,不是任意多项奖励礼包。若权益是“复活这局”或“恢复某个关卡的一次机会”,应由业务后端创建并绑定奖励意图,将具体业务上下文保留在服务端。广告位可设置 requireRewardIntent=true,服务端强制要求对应意图;这类规则只适用于有后端的激励交付。Player Lab 的意图输入框只是传递后端已创建的 ID,不提供创建可信业务机会的权限。
状态与显示建议
资格状态
eligibility | 含义 | 建议显示 |
|---|---|---|
PENDING | 尚未达到资格或等待有效证据处理 | 待验证;保留重试与查询入口 |
ELIGIBLE | 服务端已通过观看资格 | 按交付模式显示“可领取”或“等待业务确认” |
REJECTED | 本次资格被拒绝,例如开始前关闭 | 未满足要求;不能在客户端强行领取 |
EXPIRED | 资格或相应预留已过期 | 已过期;不要伪造补发 |
部分清理会在后续会话请求或查询时触发,列表状态不能替代当前会话与领取接口的最终检查。API 运行时还可能返回 reason、createdAt、expiresAt;当前 Reward TypeScript 接口未声明这些扩展字段。需要展示时应做运行时字段检查,不能假定类型里已提供。
交付状态
deliveryStatus | 典型场景 | 是否代表已可信入账 |
|---|---|---|
NOT_READY | 观看资格尚未成立 | 否 |
AVAILABLE | 资格成立,等待客户端领取或服务端拉取 | 否 |
CLAIMED | client_claim 已领取同一凭证 | 否;客户端仍需本地应用 |
CONSUMED_PENDING_ACK | 服务端已 consume,等待业务确认 | 否;业务账本需要完成事务 |
DELIVERY_PENDING | webhook 交付等待发送、重试或确认 | 否 |
FULFILLED | 业务服务已确认交付 | 广告系统已收到确认;账本仍由业务服务负责 |
EXPIRED | 待验证资格超出窗口,被清理为过期 | 否 |
创建后尚未具备资格时的交付状态不应单独驱动“发奖”按钮。必须同时检查资格和模式,已领取恢复除外。
无后端:client_claim
适用于本地存档、低价值游戏内演示或接受客户端信任边界的产品。
text
真实观看 → ELIGIBLE
↓ client.claim(reward.id)
CLAIMED,获得稳定 grantId
↓ 本地存档按 grantId 防重
本地权益已应用
↓ client.reportApplied(reward.id),仅观测报告1
2
3
4
5
6
2
3
4
5
6
claim() 可以重复请求;已经领取的记录返回同一凭证。当前服务端的核心防重依赖奖励记录和事务,claim() 发送的 Idempotency-Key 头并没有被当前控制器读取。业务入账不能只依赖这个请求头。
首次领取需在资格成立后的 24 小时内。当前实现对首次领取过期返回 REWARD_EXPIRED,不保证同时把已有 ELIGIBLE 字段改成 EXPIRED,因此不能仅看列表中的 ELIGIBLE 就认为仍在领取期内。已经 CLAIMED 的记录会在重复调用时返回同一凭证,不因超过首次领取窗口而生成新奖励。
最容易重复发奖的错误
不要把下面任何一次回调当作“金币加一次”的信号:
- 每次
claim()Promise 成功。 - 每次页面恢复时查询到
CLAIMED。 - 每次点击“领取”按钮。
- 每次收到网络重试后的成功响应。
它们可能都指向同一个 grantId。正确做法是“持久化发奖记录 + 改变存档”在同一个可恢复操作中完成,并让重复 grantId 返回已有结果。
可复制:IndexedDB 本地防重示例
仓库 Player Lab 已使用 IndexedDB,以应用、用户和 grantId 组成唯一键,在事务中保存凭证;展示余额从同一凭证集合计算,避免跨标签页覆盖或重复应用。下面的独立 Web 示例另用一个事务写入发奖记录和余额表,展示同样的防重原则。
它仍是用户可修改、可清除的本地演示数据。事务只能改善本机一致性,不能把浏览器余额变成可信资产。保存为 src/local-rewards.ts:
ts
// src/local-rewards.ts
import { AdClient, type Reward } from './lib/ad-client';
export type LocalScope = { appId: string; subjectId: string };
export type LocalBalance = LocalScope & {
key: string;
code: string;
type: string;
amount: number;
};
type LocalGrant = LocalScope & {
key: string;
grantId: string;
code: string;
type: string;
amount: number;
};
function openDatabase(): Promise<IDBDatabase> {
return new Promise((resolve, reject) => {
const request = indexedDB.open('ad-system-local-demo', 1);
request.onupgradeneeded = () => {
const db = request.result;
db.createObjectStore('grants', { keyPath: 'key' });
db.createObjectStore('balances', { keyPath: 'key' });
};
request.onsuccess = () => resolve(request.result);
request.onerror = () => reject(request.error);
request.onblocked = () => reject(new Error('本地数据库升级被其他页面阻止'));
});
}
export async function applyClaimedLocally(
scope: LocalScope,
reward: Reward,
): Promise<boolean> {
if (reward.deliveryMode !== 'client_claim' || reward.deliveryStatus !== 'CLAIMED') {
throw new Error('仅允许应用已经领取的 client_claim 凭证');
}
if (!reward.grantId || !Number.isSafeInteger(reward.amount) || reward.amount <= 0) {
throw new Error('奖励数据无效');
}
const db = await openDatabase();
try {
return await new Promise<boolean>((resolve, reject) => {
const tx = db.transaction(['grants', 'balances'], 'readwrite');
const grants = tx.objectStore('grants');
const balances = tx.objectStore('balances');
const grantKey = JSON.stringify([scope.appId, scope.subjectId, reward.grantId]);
const balanceKey = JSON.stringify([scope.appId, scope.subjectId, reward.type, reward.code]);
let applied = false;
let problem: Error | undefined;
tx.oncomplete = () => resolve(applied);
tx.onabort = () => reject(problem ?? tx.error ?? new Error('本地存档事务已回滚'));
const existingRequest = grants.get(grantKey);
existingRequest.onsuccess = () => {
const existing = existingRequest.result as LocalGrant | undefined;
if (existing) {
if (
existing.code !== reward.code ||
existing.type !== reward.type ||
existing.amount !== reward.amount
) {
problem = new Error('同一 grantId 的奖励内容冲突,需要人工检查');
tx.abort();
}
return; // 同一凭证已经应用,不再改变余额。
}
const balanceRequest = balances.get(balanceKey);
balanceRequest.onsuccess = () => {
const previous = balanceRequest.result as LocalBalance | undefined;
const amount = (previous?.amount ?? 0) + reward.amount;
if (!Number.isSafeInteger(amount) || amount <= 0) {
problem = new Error('本地余额超出安全整数范围');
tx.abort();
return;
}
const grant: LocalGrant = {
...scope,
key: grantKey,
grantId: reward.grantId,
code: reward.code,
type: reward.type,
amount: reward.amount,
};
const balance: LocalBalance = {
...scope,
key: balanceKey,
code: reward.code,
type: reward.type,
amount,
};
grants.add(grant);
balances.put(balance);
applied = true;
};
};
});
} finally {
db.close();
}
}
export async function readLocalBalances(scope: LocalScope): Promise<LocalBalance[]> {
const db = await openDatabase();
try {
return await new Promise((resolve, reject) => {
const tx = db.transaction('balances', 'readonly');
const request = tx.objectStore('balances').getAll();
tx.oncomplete = () => {
const rows = request.result as LocalBalance[];
resolve(rows.filter((row) => row.appId === scope.appId && row.subjectId === scope.subjectId));
};
tx.onabort = () => reject(tx.error ?? new Error('无法读取本地存档'));
});
} finally {
db.close();
}
}
export async function claimAndApply(
client: AdClient,
scope: LocalScope,
rewardId: string,
) {
const reward = await client.claim(rewardId);
const applied = await applyClaimedLocally(scope, reward);
let reportRecorded = false;
try {
await client.reportApplied(reward.id);
reportRecorded = true;
} catch {
// 本地事务已成功。报告失败不能再次增加余额,可在恢复时重报。
}
return { reward, applied, reportRecorded };
}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
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
scope 必须使用本次登录对应的公开 App ID 和服务端返回的 subjectId。不要在切换账号后继续用旧命名空间,也不要把奖励应用给任意界面输入的用户。
此示例使用正整数余额模拟金币等可加权益。复活、道具、关卡状态等应在同一业务事务中应用各自规则,不能一律相加。对有业务后端的产品,应把这个事务放在业务数据库中。
恢复已领取结果
以下示例只恢复已经 CLAIMED 的凭证,不自动领取所有历史可领取奖励。重复运行不会再次应用同一 grantId:
ts
import { AdClient } from './lib/ad-client';
import { applyClaimedLocally, type LocalScope } from './local-rewards';
export async function restoreClaimed(client: AdClient, scope: LocalScope) {
let newlyApplied = 0;
let after: string | undefined;
const seen = new Set<string>();
do {
const page = await client.getRewardsPage({ after });
for (const reward of page.items) {
if (reward.deliveryMode !== 'client_claim' || reward.deliveryStatus !== 'CLAIMED') continue;
if (await applyClaimedLocally(scope, reward)) newlyApplied += 1;
// 失败留给下一次恢复;它只是观测报告,不撤销已提交的本地存档。
await client.reportApplied(reward.id).catch(() => undefined);
}
if (!page.hasMore) break;
if (!page.nextCursor || seen.has(page.nextCursor)) throw new Error('奖励历史游标未前进');
after = page.nextCursor;
seen.add(after);
} while (true);
return newlyApplied;
}1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
兼容方法 getRewards() 只返回最近最多 100 条;完整恢复使用 getRewardsPage({ after }) 逐页遍历,仓库播放器的 Restore history 已采用这种方式。客户端游标按创建时间倒序翻阅历史,限定原应用和用户,有效期 7 天;它不是业务后端增量同步水位。中途失败可以从第一页重新恢复,grantId 防重保证不会再加一遍。
如果本地保存了某个 sessionId,也可在同一身份下用 getSession() 获取这次奖励,再对已有 reward.id 重复 claim()。若安装 ID 或业务账号变化,原奖励不会自动归入新身份。
清除 IndexedDB、localStorage 或重装应用,会丢失本地防重与存档信息。重新导入旧凭证只能重建可访问记录对应的本地演示结果,不保证恢复完整游戏状态。
有后端:server_pull
客户端仍负责播放与查询,但不调用 claim() 为玩家发奖。业务后端持有 X-App-Key:
- 从经过认证的业务账号确定
subjectId,申请短期客户端 token。 - 根据业务需要创建奖励意图,并把意图 ID 交给客户端创建广告会话。
- 拉取广告系统中的可交付奖励。
- consume 得到稳定的奖励交付数据。
- 在业务数据库事务中按
grantId唯一约束记录入账,并修改该用户资产。 - 事务提交后向广告系统确认,推进至
FULFILLED。
如果在第 5 步成功后网络断开,重复 consume / 拉取时必须识别同一 grantId,返回已有入账结果,再补发确认。不要先确认再入账;否则业务事务失败时,广告系统可能已经认为交付完成。
客户端可显示“资格已通过,等待到账”,然后查询自己的游戏服务获取真实余额。广告系统返回 FULFILLED 是确认信号,实际金币余额仍以游戏服务为准。
有后端:server_webhook
资格成立后由 worker 投递签名通知。业务后端需要:
- 对原始请求体和时间戳按约定验证 HMAC,不能把重新序列化的 JSON 当作原始字节。
- 核对应用、用户、奖励字段和预期业务上下文。
- 使用稳定
grantId幂等入账;重复通知返回成功,不重复加资产。 - 入账事务提交后确认交付;异常时允许广告系统重试。
通知可能重复、延迟或因为配置问题失败。不要将 webhook 的“收到次数”当成奖励次数,也不要因为客户端显示已完成就绕过验签自行补发。
仓库 examples/business-server 提供签名验证、文件持久化防重、令牌与 consume 示例。它是本地协议验证服务,不是生产资产服务;正式接入需要你自己的认证、数据库事务、审计和恢复策略。
查询与轮询
AdClient 不自动轮询。在页面前台、会话需要恢复时,可以用一个单飞的查询循环;每次查询只读取状态,不生成任何观看证据:
ts
import { AdClient, type AdSession } from './lib/ad-client';
export function watchRewardStatus(
client: AdClient,
sessionId: string,
onUpdate: (session: AdSession) => void,
onError: (error: unknown) => void,
) {
let stopped = false;
let timer: ReturnType<typeof setTimeout> | undefined;
const poll = async () => {
if (stopped) return;
try {
if (!document.hidden) {
const session = await client.getSession(sessionId);
if (stopped) return;
onUpdate(session);
const reward = session.reward;
if (!reward || ['REJECTED', 'EXPIRED'].includes(reward.eligibility) ||
['CLAIMED', 'FULFILLED'].includes(reward.deliveryStatus)) return;
}
} catch (error) {
if (!stopped) onError(error);
}
if (!stopped) timer = setTimeout(() => void poll(), 5000);
};
void poll();
return () => {
stopped = true;
if (timer) clearTimeout(timer);
};
}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
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
这个示例遇到错误会继续隔 5 秒查询,属于调用方显式实现的策略。实际产品应对 UNAUTHORIZED 暂停并重新认证,对终态或退出场景停止轮询,并设置产品需要的等待上限。它不意味着 SDK 内置自动重试。
故障恢复决策
| 故障点 | 恢复动作 |
|---|---|
claim() 超时,不知道是否成功 | 同一身份、同一 reward.id 重试,取得相同凭证 |
| 已领取,但本地存档写入失败 | 不显示到账;保留奖励 ID,恢复后重试本地事务 |
本地入账成功,但 reportApplied() 失败 | 保留本地结果;重报观测,不能再加资产 |
| 服务端入账成功,ack 超时 | 用 grantId 查业务已提交结果,补确认 |
| webhook 重复 | 验签后命中已有 grantId,返回原处理结果 |
| 未完成观看且证据无法恢复 | 展示未获资格或待查状态,不能在客户端伪造补发 |
| 身份已切换 | 切回原身份后查询,不能把旧会话交给新账号领取 |
完整客户端接入见Web 配方,方法参数见TypeScript 参考。