AttributionRepository 深度解析:Instagram 归因上报接口的实现与调用链
AttributionRepository 深度解析:Instagram 归因上报接口的实现与调用链
导读
AttributionRepository 是 instagram-private-api(NodeJS Instagram 私有 API SDK,TypeScript 编写)中负责归因数据上报的核心仓库类。它承载两个接口:logAttribution() 与 logResurrectAttribution(),分别对应 Instagram 客户端启动与登录后回访场景的设备归因上报。本文基于官方 API 文档与源码,完整讲解该类在 Repository 继承体系中的位置、两个方法的请求结构与签名参数、adid 等状态字段的来源,以及它在模拟登录流程(SimulateService)中的实际调度关系,读完即可理解并复现这两个接口的完整调用链。
1. 类概览与继承体系
AttributionRepository 定义于文档 repositories 模块 之下,类层次为:
Repository
↳ AttributionRepository
它直接继承自抽象基类 Repository(src/core/repository.ts),构造函数接收一个 IgApiClient 实例并通过基类保存为受保护属性 client:
// src/core/repository.ts
export abstract class Repository {
@Enumerable(false)
protected client: IgApiClient;
constructor(client: IgApiClient) {
this.client = client;
}
}
所有仓库类(AccountRepository、MediaRepository、AttributionRepository 等)共用这套构造模式。IgApiClient 在实例化时(src/core/client.ts)将 AttributionRepository 挂载为公开属性 attribution,因此业务代码中通过 ig.attribution 即可访问:
// src/core/client.ts:48-49
public account = new AccountRepository(this);
public attribution = new AttributionRepository(this);
该类的公开 API 只有两个方法,均返回 Promise<any>:
| 方法 | 签名 | 源码位置 |
|---|---|---|
logAttribution |
logAttribution(): Promise<any> |
src/repositories/attribution.repository.ts:4 |
logResurrectAttribution |
logResurrectAttribution(): Promise<any> |
src/repositories/attribution.repository.ts:16 |
说明:返回类型为
any,因为接口响应体结构不固定,直接透传服务端body。
2. logAttribution():登录前的归因上报
logAttribution() 对应 Instagram 的首次归因上报接口,源码实现非常精简:
// src/repositories/attribution.repository.ts:4-13
public async logAttribution() {
const { body } = await this.client.request.send({
method: 'POST',
url: '/api/v1/attribution/log_attribution/',
form: this.client.request.sign({
adid: this.client.state.adid,
}),
});
return body;
}
其请求特征可以拆解为三层:
(1)请求端点:POST /api/v1/attribution/log_attribution/,baseUrl 由 src/core/request.ts 统一注入为 https://i.instagram.com/,因此最终请求为 https://i.instagram.com/api/v1/attribution/log_attribution/。
(2)签名机制:this.client.request.sign() 是 Request 层提供的签名方法(src/core/request.ts:115-122),其内部使用 HMAC-SHA256 + state.signatureKey(src/core/constants.ts 中定义的 SIGNATURE_KEY)对 JSON 序列化后的 payload 计算签名,输出 signed_body 与 ig_sig_key_version(固定为 4):
public sign(payload: Payload): SignedPost {
const json = typeof payload === 'object' ? JSON.stringify(payload) : payload;
const signature = this.signature(json);
return {
ig_sig_key_version: this.client.state.signatureVersion,
signed_body: `${signature}.${json}`,
};
}
也就是说,浏览器/抓包工具看到的 signed_body=签名.JSON字符串 与 ig_sig_key_version=4 两个表单字段,就是由这一层生成的。
(3)核心参数 adid:adid(Google Play Advertising ID)由 State.generateDevice() 生成(src/core/state.ts:245-257):
public generateDevice(seed: string): void {
const chance = new Chance(seed);
this.deviceString = chance.pickone(devices);
...
this.uuid = chance.guid();
this.phoneId = chance.guid();
this.adid = chance.guid(); // ← adid 在此生成
this.build = chance.pickone(builds);
}
在使用前必须显式调用 ig.state.generateDevice(seed)(如 ig.state.generateDevice(process.env.IG_USERNAME),见 examples/session.example.ts),否则 adid 为 undefined。
手动调用示例:
import { IgApiClient } from 'instagram-private-api';
const ig = new IgApiClient();
ig.state.generateDevice('my-device-seed');
// 单独触发一次归因上报
const result = await ig.attribution.logAttribution();
console.log(result); // 服务端返回的 body,例如 { status: 'ok' }
3. logResurrectAttribution():登录后的“回访”归因上报
第二个方法对应 log_resurrect_attribution 接口(“resurrect”意为复活/回访,指老用户重新登录后的归因上报),源码实现为:
// src/repositories/attribution.repository.ts:16-32
// This method participates in post-login flow
// And it crashes in official IG app, so we just catch it and return error
public async logResurrectAttribution() {
try {
const { body } = await this.client.request.send({
method: 'POST',
url: '/api/v1/attribution/log_resurrect_attribution/',
form: this.client.request.sign({
_csrftoken: this.client.state.cookieCsrfToken,
_uid: this.client.state.cookieUserId,
adid: this.client.state.adid,
_uuid: this.client.state.uuid,
}),
});
return body;
} catch (e) {
return e;
}
}
对比 logAttribution(),该方法有两个值得注意的设计:
(1)四个表单参数,其中三个来自登录后建立起的 Cookie/会话状态(src/core/state.ts):
| 参数 | 取值来源 | 含义 |
|---|---|---|
_csrftoken |
state.cookieCsrfToken(从 Cookie 中提取 csrftoken,state.ts:159-166) |
防跨站请求伪造令牌 |
_uid |
state.cookieUserId(从 Cookie 中提取 ds_user_id,state.ts:168-170) |
当前登录用户 ID |
adid |
state.adid(generateDevice 生成的广告 ID) |
Google Play 广告标识 |
_uuid |
state.uuid(generateDevice 生成的设备 GUID) |
客户端设备 UUID |
注意 cookieCsrfToken 与 cookieUserId 的读取基于 tough-cookie 的 cookieJar(extractCookieValue 方法),若 Cookie 中缺少对应 key,会抛出 IgCookieNotFoundError——这也是为什么该方法必须出现在登录之后。
(2)try/catch 兜底:源码注释明确说明“This method participates in post-login flow and it crashes in official IG app, so we just catch it and return error”。即该接口在官方 App 中也会崩溃,因此 SDK 故意将异常捕获并原样返回错误对象而不是抛出,避免中断整个登录后流程。
手动调用示例:
// 必须先完成登录,以获得 csrftoken / ds_user_id 等 Cookie
await ig.account.login(username, password);
const result = await ig.attribution.logResurrectAttribution();
// 正常时返回 body;接口异常时返回错误对象(不会抛出)
if (result instanceof Error) {
console.warn('resurrect attribution failed, ignoring:', result.message);
}
4. 在模拟流程中的调度位置:与 SimulateService 的联动
AttributionRepository 的两个方法虽然可以独立调用,但它们真正的设计用途是参与 SimulateService(ig.simulate)所编排的“模拟官方客户端行为”请求流(src/services/simulate.service.ts):
- preLoginFlow(登录前):
logAttribution()被安排在account.readMsisdnHeader、qe.syncLoginExperiments等请求附近(第 14 行),与获取预填充候选、同步登录实验等一起构成“冷启动”行为; - postLoginFlow(登录后):
logAttribution()与logResurrectAttribution()连续成对出现(第 24-25 行),紧随zr.tokenResult()、launcher.postLoginSync()、qe.syncExperiments()之后,再衔接loom.fetchConfig()、direct.rankedRecipients、时间线刷新等后续请求。
private get postLoginFlowRequests(): Array<() => any> {
return [
() => this.client.zr.tokenResult(),
() => this.client.launcher.postLoginSync(),
() => this.client.qe.syncExperiments(),
() => this.client.attribution.logAttribution(), // ← 第一次归因上报
() => this.client.attribution.logResurrectAttribution(), // ← 登录后回访归因上报
() => this.client.loom.fetchConfig(),
...
];
}
executeRequestsFlow 默认对请求列表 shuffle 并以并发数 1 顺序执行(Bluebird.map(requests, request => request(), { concurrency })),两个归因请求可能被随机打散但不会并行。
在真实业务中模拟客户端行为时的推荐用法:
import { IgApiClient } from 'instagram-private-api';
const ig = new IgApiClient();
ig.state.generateDevice(process.env.IG_USERNAME);
ig.state.proxyUrl = process.env.IG_PROXY;
await ig.simulate.preLoginFlow(); // 内部包含 logAttribution()
await ig.account.login(process.env.IG_USERNAME, process.env.IG_PASSWORD);
await ig.simulate.postLoginFlow(); // 内部包含 logAttribution() + logResurrectAttribution()
5. 请求链路总结:一次归因上报发生了什么
综合 request.ts、state.ts、constants.ts 与 attribution.repository.ts,一次 logAttribution() 的完整链路为:
ig.attribution.logAttribution()
└─ ig.client.request.sign({ adid })
├─ HMAC-SHA256(SIGNATURE_KEY, JSON) → signature
└─ 组装 { ig_sig_key_version: '4', signed_body: signature + '.' + json }
└─ ig.client.request.send({
method: 'POST',
url: '/api/v1/attribution/log_attribution/',
form: 上述签名结果,
})
├─ defaultsDeep 注入 baseUrl=https://i.instagram.com/、cookieJar、proxy、gzip、默认头
├─ 发送请求 → updateState() 同步 ig-set-* 响应头
└─ 校验 body.status === 'ok',否则抛出对应 IgClientError 子类
其中 send 的默认参数(baseUrl、Cookie Jar、代理、gzip、请求头)在 src/core/request.ts:59-75 中统一注入,所有 Repository 请求共享同一套链路,这也是 AttributionRepository 实现如此精简的原因——它只负责“定义端点与参数”,传输层全部复用 Request。
6. 注意事项与适用前提
基于源码可以确认以下几点使用边界:
- 必须先
generateDevice:adid、uuid等字段依赖设备种子生成,未调用ig.state.generateDevice()时参数缺失,接口行为不可预期; logResurrectAttribution依赖登录态 Cookie:_csrftoken与_uid来自登录后 Cookie(csrftoken、ds_user_id),未登录调用会触发IgCookieNotFoundError;该异常由 SDK 内部的try/catch消化后原样返回;- 签名版本固定:当前仓库
SIGNATURE_VERSION = '4'(src/core/constants.ts:5),Instagram 服务端可能更新签名要求,届时需要同步升级 SDK 版本; - 两个接口均为内部上报接口:官方客户端在启动/登录后自动静默调用,开发者通常无需手动高频触发,过度调用可能触发风控(
IgActionSpamError等),建议仅在simulate.preLoginFlow/postLoginFlow场景中使用。
7. 相关文档与源码索引
- 类文档:AttributionRepository、SimulateService、IgApiClient
- 模块入口:repositories 模块
- 核心实现:src/repositories/attribution.repository.ts、src/core/repository.ts、src/core/client.ts、src/core/request.ts、src/core/state.ts、src/core/constants.ts、src/services/simulate.service.ts
- 实战参考:examples/session.example.ts(设备生成与状态序列化完整示例)