外观
客户端完整配方
本页提供一个可运行的浏览器参考项目,使用真实 API、真实媒体和真实播放测量。它支持图片、完整视频、最短时长视频、匿名登录、关闭、证据重试、本地凭证防重和已领取恢复。
它与仓库 Player Lab 使用相同接口,但为了便于复制,采用更小的 UI 和独立 IndexedDB 示例。更完整的页面、展示样式和业务 token 输入可直接参考仓库 apps/player-demo/src/main.ts。
示例范围
本配方针对 client_claim 应用,不是生产 SDK。它不支持页面重启后的播放续传、无限离线观看、自动 token 刷新或可信资产入账。有业务后端时,沿用播放部分,并替换身份获取与奖励交付;不要把服务端密钥复制进这个项目。
本页保留便于理解的内存播放队列,与仓库已升级的 Player Lab 明确区分:仓库播放器会持久化原事件、支持同身份刷新凭据后补传,并为完成/关闭预留容量。若需要这些恢复能力,使用 apps/player-demo/src/playback-journal.ts 及其调用流程;只复制本页代码不会获得相同的跨刷新保证。下面仍会发送真实 elapsedSeconds,支持本页存活期间的合法延迟补传。
1. 文件结构
创建一个独立目录,例如 ad-web-example,准备以下文件:
text
ad-web-example/
package.json
tsconfig.json
vite.config.ts
index.html
src/
main.ts
ad-events.ts
local-rewards.ts
lib/
ad-client.ts1
2
3
4
5
6
7
8
9
10
11
2
3
4
5
6
7
8
9
10
11
其中三个文件来自前面的文档:
- 下载 client-core.ts,保存为
src/lib/ad-client.ts。 - 将播放页的完整队列实现保存为
src/ad-events.ts。 - 将奖励页的 IndexedDB 完整示例保存为
src/local-rewards.ts。
这三个文件与下面的 main.ts 可以一起编译。@ad/client-core 尚未发布 npm;这里不需要安装该私有包。
2. 项目配置
package.json:
json
{
"name": "ad-web-example",
"private": true,
"version": "0.1.0",
"type": "module",
"scripts": {
"dev": "vite --host 127.0.0.1 --port 5180",
"build": "tsc --noEmit && vite build"
},
"devDependencies": {
"typescript": "5.9.3",
"vite": "6.3.6"
}
}1
2
3
4
5
6
7
8
9
10
11
12
13
14
2
3
4
5
6
7
8
9
10
11
12
13
14
tsconfig.json:
json
{
"compilerOptions": {
"target": "ES2022",
"module": "ESNext",
"moduleResolution": "Bundler",
"lib": ["ES2022", "DOM", "DOM.Iterable"],
"strict": true,
"skipLibCheck": true,
"noEmit": true
},
"include": ["src"]
}1
2
3
4
5
6
7
8
9
10
11
12
2
3
4
5
6
7
8
9
10
11
12
vite.config.ts:
ts
import { defineConfig } from 'vite';
export default defineConfig({
server: {
strictPort: true,
proxy: {
'/v1': { target: 'http://127.0.0.1:3000', changeOrigin: true },
'/media': { target: 'http://127.0.0.1:3000', changeOrigin: true },
},
},
});1
2
3
4
5
6
7
8
9
10
11
2
3
4
5
6
7
8
9
10
11
这里通过同源代理调用 API,避免额外的浏览器跨域配置。正式部署时可以使用反向代理或明确配置的 API URL;不要把本地地址原样发布。素材 URL 来自服务端会话,API 必须配置客户端可访问的公开素材地址。
index.html:
html
<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>广告客户端接入示例</title>
</head>
<body>
<div id="app"></div>
<script type="module" src="/src/main.ts"></script>
</body>
</html>1
2
3
4
5
6
7
8
9
10
11
12
2
3
4
5
6
7
8
9
10
11
12
3. 完整客户端入口
保存以下内容为 src/main.ts。app_demo、daily_bonus 是开发种子配置;自有环境请把 APP_ID 换成管理后台的公开 App ID。广告位列表从接口读取,不需要在代码中伪造素材。
ts
// src/main.ts
import { AdClient, AdApiError, type AdSession, type Reward } from './lib/ad-client';
import { OrderedEventQueue, type PlaybackSample } from './ad-events';
import {
applyClaimedLocally,
claimAndApply,
readLocalBalances,
type LocalScope,
} from './local-rewards';
const APP_ID = 'app_demo';
const client = new AdClient({ baseUrl: '/v1', timeoutMs: 12_000 });
const installationKey = `example:installation:${APP_ID}`;
let installationId = localStorage.getItem(installationKey);
if (!installationId) {
installationId = crypto.randomUUID();
localStorage.setItem(installationKey, installationId);
}
document.querySelector<HTMLDivElement>('#app')!.innerHTML = `
<main style="max-width:860px;margin:40px auto;font-family:system-ui;padding:16px">
<h1>广告接入示例</h1>
<p>真实图片 / 视频;本地库存仅用于演示,不是可信业务余额。</p>
<button id="connect">连接 / 刷新匿名令牌</button>
<select id="placement" aria-label="广告位" disabled></select>
<button id="watch" disabled>加载并观看</button>
<button id="retry" disabled>重试证据并查询</button>
<button id="claim" disabled>领取 / 恢复当前奖励</button>
<button id="restore" disabled>恢复近期已领取凭证</button>
<p id="status" role="status">尚未连接</p>
<pre id="inventory">本地演示库存为空</pre>
<pre id="error" role="alert" style="white-space:pre-wrap;color:#a22"></pre>
<dialog id="dialog" style="max-width:800px;width:90%;border-radius:12px">
<p>广告 <button id="close">关闭</button>
<button id="pause" hidden>暂停 / 继续</button></p>
<div id="media"></div>
<p id="progress">准备媒体…</p>
<p>提前关闭可能无法获得奖励。隐藏页面会暂停计时。</p>
</dialog>
</main>`;
const element = <T extends HTMLElement>(id: string) => document.getElementById(id) as T;
const button = (id: string) => element<HTMLButtonElement>(id);
const dialog = element<HTMLDialogElement>('dialog');
const placement = element<HTMLSelectElement>('placement');
let scope: LocalScope | undefined;
let session: AdSession | undefined;
let queue: OrderedEventQueue | undefined;
let video: HTMLVideoElement | undefined;
let operationKey = sessionStorage.getItem(`example:load:${APP_ID}`) ?? crypto.randomUUID();
let busy = false;
let open = false;
let completed = false;
let closing = false;
let visibleSeconds = 0;
let previousFrame = 0;
let previousPosition = 0;
let playbackStartClock: number | null = null;
let lastVisibleSample: PlaybackSample | undefined;
let lastQueuedVisible = 0;
let frame = 0;
let timer: ReturnType<typeof setInterval> | undefined;
function explain(error: unknown): void {
element('error').textContent = error instanceof AdApiError
? `${error.code}: ${error.message}${error.requestId ? ` (request ${error.requestId})` : ''}`
: error instanceof Error ? error.message : String(error);
}
function render(): void {
const reward = session?.reward;
element('status').textContent = session
? `${session.id} · ${session.status} · ${reward ? `${reward.eligibility} / ${reward.deliveryStatus}` : '无奖励展示广告'}`
: scope ? `已连接 ${scope.appId} / ${scope.subjectId}` : '尚未连接';
button('connect').disabled = busy || open;
placement.disabled = busy || open || !scope || !placement.options.length;
button('watch').disabled = busy || open || !scope || !placement.value ||
Boolean(queue?.size) || Boolean(session && session.status !== 'ENDED');
button('retry').disabled = busy || !session;
button('claim').disabled = busy || open || !reward || reward.deliveryMode !== 'client_claim' ||
(reward.eligibility !== 'ELIGIBLE' && reward.deliveryStatus !== 'CLAIMED');
button('restore').disabled = busy || open || !scope;
button('close').disabled = busy;
if (reward?.eligibility === 'ELIGIBLE') {
element('progress').textContent = reward.deliveryMode === 'client_claim'
? '奖励已就绪,关闭后领取。' : '奖励资格已通过,等待业务后端确认。';
} else if (completed) {
element('progress').textContent = '播放结束;按服务端资格为准,可关闭后重试或查询。';
}
}
function accept(updated: AdSession): void {
session = updated;
if (scope) localStorage.setItem(`example:last:${APP_ID}:${scope.subjectId}`, updated.id);
render();
}
async function inventory(): Promise<void> {
if (!scope) return;
const rows = await readLocalBalances(scope);
element('inventory').textContent = rows.length
? rows.map((row) => `${row.code} (${row.type}): ${row.amount}`).join('\n')
: '本地演示库存为空';
}
async function action(work: () => Promise<void>): Promise<void> {
if (busy) return;
busy = true;
element('error').textContent = '';
render();
try { await work(); } catch (error) { explain(error); }
finally { busy = false; render(); }
}
function sample(): PlaybackSample {
return {
visible: open && !document.hidden,
visibleSeconds,
...(video ? { positionSeconds: video.currentTime } : {}),
...(playbackStartClock === null ? {} : {
elapsedSeconds: Math.max(0, (performance.now() - playbackStartClock) / 1000),
}),
};
}
function enqueueEvent(type: 'heartbeat' | 'complete' | 'close', evidence = sample()): void {
if (!queue) throw new Error('尚未建立播放队列');
queue.enqueue(type, evidence);
lastQueuedVisible = Math.max(lastQueuedVisible, evidence.visibleSeconds);
}
function requiredSeconds(): number {
if (!session) return 0;
if (session.creative.kind === 'image') return session.rules.imageSeconds;
if (session.rules.videoMode === 'minimum') return session.rules.videoSeconds;
const duration = session.creative.durationSeconds;
if (!duration || duration <= 0) throw new Error('视频缺少有效素材时长');
return duration;
}
function stopClock(): void {
cancelAnimationFrame(frame);
if (timer) clearInterval(timer);
timer = undefined;
video?.pause();
}
function measure(now: number): void {
const elapsed = Math.min(Math.max((now - previousFrame) / 1000, 0), 0.25);
previousFrame = now;
if (open && !document.hidden && session?.status === 'SHOWING' && !completed && !closing) {
if (!video) visibleSeconds += elapsed;
else {
const progress = video.currentTime - previousPosition;
if (!video.paused && !video.seeking && video.playbackRate === 1 && progress >= 0 && progress < 0.7) {
visibleSeconds += Math.min(progress, elapsed + 0.05);
}
}
lastVisibleSample = sample();
}
if (video) previousPosition = video.currentTime;
}
async function finish(): Promise<void> {
if (completed || closing || !queue || !open) return;
measure(performance.now());
completed = true;
try {
enqueueEvent('heartbeat');
enqueueEvent('complete');
} catch (error) {
stopClock();
throw error;
}
video?.pause();
render();
await queue.flush();
}
function tick(now: number): void {
measure(now);
if (!completed && session?.status === 'SHOWING') {
const target = requiredSeconds();
element('progress').textContent = `${visibleSeconds.toFixed(1)} / ${target.toFixed(1)} 秒有效观看`;
if ((!video || session.rules.videoMode === 'minimum') && visibleSeconds >= target + 0.05) {
void finish().catch(explain);
}
}
if (open) frame = requestAnimationFrame(tick);
}
async function prepareMedia(): Promise<void> {
if (!session) throw new Error('没有会话');
const current = session;
video = undefined;
element('media').replaceChildren();
await new Promise<void>((resolve, reject) => {
const timeout = setTimeout(() => reject(new Error('媒体加载超过 15 秒')), 15_000);
const ready = () => { clearTimeout(timeout); resolve(); };
const failed = () => { clearTimeout(timeout); reject(new Error('媒体加载失败')); };
const media = document.createElement(current.creative.kind === 'image' ? 'img' : 'video');
media.style.cssText = 'display:block;width:100%;max-height:65vh;object-fit:contain';
if (media instanceof HTMLImageElement) {
media.alt = '广告';
media.onload = ready;
media.onerror = failed;
} else {
video = media;
media.muted = true;
media.playsInline = true;
media.preload = 'auto';
media.addEventListener('loadeddata', ready, { once: true });
media.addEventListener('error', failed, { once: true });
media.addEventListener('ratechange', () => {
if (media.playbackRate !== 1) media.playbackRate = 1;
});
media.addEventListener('ended', () => void finish().catch(explain));
}
media.src = current.creative.url;
element('media').append(media);
});
button('pause').hidden = !video;
}
button('connect').onclick = () => void action(async () => {
const identity = await client.initializeAnonymous(APP_ID, installationId!);
if (scope && scope.subjectId !== identity.subjectId) throw new Error('身份改变,请重新打开页面');
scope = { appId: APP_ID, subjectId: identity.subjectId };
const config = await client.getConfig();
placement.replaceChildren(...config.placements.map((item) => new Option(item.name, item.code)));
if (!session) {
const saved = localStorage.getItem(`example:last:${APP_ID}:${scope.subjectId}`);
if (saved) accept(await client.getSession(saved));
}
await inventory();
});
button('watch').onclick = () => void action(async () => {
sessionStorage.setItem(`example:load:${APP_ID}`, operationKey);
const loaded = await client.load(placement.value, { idempotencyKey: operationKey });
accept(loaded);
operationKey = crypto.randomUUID();
sessionStorage.removeItem(`example:load:${APP_ID}`);
if (loaded.status !== 'CREATED') throw new Error('已有会话不能重播,请查询其奖励状态');
queue = new OrderedEventQueue(client, loaded.id, accept);
visibleSeconds = 0;
playbackStartClock = null;
lastVisibleSample = undefined;
lastQueuedVisible = 0;
completed = false;
closing = false;
open = true;
dialog.showModal();
element('progress').textContent = '准备媒体…';
await prepareMedia();
accept(await client.start(loaded.id));
if (session?.status !== 'SHOWING') throw new Error('服务端未允许播放,请关闭后检查会话');
playbackStartClock = performance.now();
previousFrame = performance.now();
previousPosition = video?.currentTime ?? 0;
frame = requestAnimationFrame(tick);
timer = setInterval(() => {
if (!queue) return;
try {
if (open && !completed && !closing && session?.status === 'SHOWING') {
enqueueEvent('heartbeat');
}
// flush 是单飞操作。定时器不是 async,不会并发发送不同批次。
void queue.flush().catch(explain);
} catch (error) {
stopClock();
explain(error); // 队列满时停止媒体,保留已有证据供手动恢复。
}
}, 1000);
if (video && !document.hidden) {
try { await video.play(); }
catch { throw new Error('浏览器拦截自动播放,请点击“暂停 / 继续”开始真实播放'); }
}
});
async function closeAd(): Promise<void> {
if (!open || busy || closing) return;
measure(performance.now());
closing = true;
try {
if (queue && session?.status === 'SHOWING') {
enqueueEvent('heartbeat');
enqueueEvent('close');
} else if (queue && session?.status === 'CREATED') {
enqueueEvent('close');
}
} finally {
// 即使队列已满,也允许用户退出;未成功上报关闭时只能查询并等待服务端释放。
open = false;
stopClock();
dialog.close();
render();
await queue?.flush();
}
}
button('close').onclick = () => void closeAd().catch(explain);
dialog.addEventListener('cancel', (event) => {
event.preventDefault();
void closeAd().catch(explain);
});
button('pause').onclick = () => {
if (!video || completed || closing) return;
previousFrame = performance.now();
previousPosition = video.currentTime;
if (video.paused) void video.play().catch(explain);
else video.pause();
};
document.addEventListener('visibilitychange', () => {
previousFrame = performance.now();
previousPosition = video?.currentTime ?? 0;
if (document.hidden) video?.pause();
if (open && queue && session?.status === 'SHOWING' && !completed && !closing) {
try {
// 先保存切后台前最后一帧的原始可见采样,避免丢掉上次心跳后的有效区间。
if (document.hidden && lastVisibleSample && lastVisibleSample.visibleSeconds > lastQueuedVisible) {
enqueueEvent('heartbeat', lastVisibleSample);
}
enqueueEvent('heartbeat');
void queue.flush().catch(explain);
} catch (error) { stopClock(); explain(error); }
}
});
button('retry').onclick = () => void action(async () => {
await queue?.flush();
if (session) accept(await client.getSession(session.id));
});
button('claim').onclick = () => void action(async () => {
if (!scope || !session?.reward) return;
const result = await claimAndApply(client, scope, session.reward.id);
session.reward = result.reward;
await inventory();
if (!result.reportRecorded) element('error').textContent = '本地存档成功;观测报告失败,可通过恢复历史重报。';
});
button('restore').onclick = () => void action(async () => {
if (!scope) return;
let after: string | undefined;
const seen = new Set<string>();
do {
const page = await client.getRewardsPage({ after });
for (const reward of page.items as Reward[]) {
if (reward.deliveryMode !== 'client_claim' || reward.deliveryStatus !== 'CLAIMED') continue;
await applyClaimedLocally(scope, reward);
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);
await inventory();
if (session) accept(await client.getSession(session.id));
});
render();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
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
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
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
4. 运行与验证
先按快速开始启动广告系统。在新项目目录运行:
sh
pnpm install
pnpm build
pnpm dev1
2
3
2
3
打开 http://127.0.0.1:5180,按照以下顺序验证:
- 点击“连接”,选择图片广告位,点击“加载并观看”。
- 保持弹层前台可见,等待真实计时达到要求;界面应显示奖励已就绪。
- 关闭弹层,领取奖励;检查本地库存。
- 重复领取和恢复历史,库存不应因为同一个
grantId再次增加。 - 选择视频广告位,暂停、恢复、切后台,确认这些间隔不计入有效观看。
- 提前关闭一次新会话,确认没有直接调用本地加币逻辑。
- 短暂断网,观察错误与保留的事件;恢复网络后重试。服务端实际状态决定是否有资格,不保证离线获奖。
频控、冷却、活动额度不足或没有有效投放时,load() 会返回明确错误,这是正常业务结果。不要修改示例生成假素材或本地直接授予奖励来绕过这些状态。
5. 这个配方的恢复边界
| 情况 | 示例行为 |
|---|---|
| 创建会话响应丢失 | 同一页面复用原创建幂等键,重新请求同一操作 |
| 页面刷新后重试创建 | sessionStorage 保留尚未确认的幂等键;仍需选择相同广告位,改变请求参数会冲突 |
| 事件响应丢失 | 页面内队列保留原事件,自动心跳或手动重试串行重发 |
| 弹层关闭后事件失败 | 保留内存队列,点击“重试证据并查询”;没有关闭后后台无限重试 |
| token 过期 | 显示 UNAUTHORIZED,关闭播放后用同一安装 ID 重新连接,再重试原操作 |
| 页面刷新 | 恢复身份和已保存会话的状态;不会恢复播放采样或待发送事件 |
恢复会话仍为 CREATED / SHOWING | 仅查询;本示例不重建未知序号的队列。需等待服务端到期释放,或在未刷新页面的原队列中正常关闭 |
claim() 结果不确定 | 对同一奖励重试,IndexedDB 事务按 grantId 防重 |
| 存储被清空 | 安装身份、本地库存或防重记录可能丢失;不能保证恢复完整存档 |
初始化和媒体准备阶段按钮会临时禁用,素材加载最多等待 15 秒,HTTP 默认最多等待 12 秒;失败后可关闭释放预留。正式 SDK 可进一步实现准备过程取消、原生生命周期适配与持久化队列,但需要维护同样的状态和顺序约束。
6. 改为有业务后端的客户端
替换匿名登录部分:客户端先向自己的业务服务获取经过用户认证的短期 token,再传给广告系统。下面的 /api/ads/client-token 是你要实现的业务路由,不是广告系统自带路由:
ts
import { AdClient } from './lib/ad-client';
export async function connectWithBusinessLogin() {
const response = await fetch('/api/ads/client-token', {
method: 'POST',
credentials: 'include',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({}),
});
if (!response.ok) throw new Error('业务登录或广告令牌申请失败');
const data: unknown = await response.json();
if (!data || typeof data !== 'object' || !('token' in data) || typeof data.token !== 'string') {
throw new Error('业务服务未返回有效 token');
}
const client = new AdClient({ baseUrl: '/v1', token: data.token });
return { client, config: await client.getConfig() };
}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
业务服务应从已验证的登录会话确定用户,而不是相信前端任意传入的 subjectId。若业务登录使用 Cookie,还需由业务服务实现适合其架构的 CSRF 防护。
对于 server_pull / server_webhook,保留播放和 getSession() 查询,移除本地领取入库按钮。资格成立后由业务服务交付资产,APP 查询自己的业务余额或权益状态。完整模式说明见奖励交付。
业务广告位若要求 requireRewardIntent=true,还要先由自己的业务后端为这次对局或权益机会创建意图,再在 load() 中传入它:
ts
// ads 是已用业务 token 认证的 AdClient;两个 ID 均由这次业务机会持久保存。
const session = await ads.load('revive', {
idempotencyKey: savedCreateKey,
rewardIntentId: intentIdFromYourAuthenticatedBackend,
});1
2
3
4
5
2
3
4
5
不要从浏览器自由指定奖励金额或任意玩家 ID。rewardIntentId 与 businessKey 关联结果可从奖励对象读取,但最终业务入账仍需由后端验证。
7. 接入游戏引擎时保留哪些职责
| Web 示例职责 | 游戏引擎 / 原生 SDK 对应职责 |
|---|---|
fetch + AdClient | 平台网络层、认证头、超时与明确重试策略 |
localStorage 安装 ID | 可持久化且不轻易变化的本地安装标识 |
requestAnimationFrame | 游戏帧循环 / 原生展示时钟,后台不累计 |
HTMLVideoElement 进度 | 原生播放器实际进度、暂停、结束与错误回调 |
visibilitychange | APP 前后台、场景切换、广告视图销毁生命周期 |
OrderedEventQueue | 每会话独立的保序、保留原事件的发送队列 |
| IndexedDB 事务 | 本地存档事务,或由可信业务后端事务入账 |
初版没有发布这些平台 SDK。复用 HTTP 接口时,应先实现并验证表中的平台职责,再对外包装成统一 load / show / reward API;不能把 Web 播放器直接称为已经支持 Unity、Cocos 或原生广告联盟。