# 功能开关、实验与事件

功能开关与实验、事件采集、网页跳转与可视化实验。

更新于 2026-11-06

[网页版本](https://www.longplayai.com/zh-hans/docs/guides/features)

<a id="prepare"></a>

## 准备实验与采集

- 在当前 App/环境创建并发布要读取的功能开关定义或实验，记录功能开关 key 和环境 UUID。商业计量 Feature 的 UUID 不能替代功能开关 key。
- 需要 Customer 求值和事件采集时，由后端签发包含 features:read 和 events:write 的 Customer Token，并配置浏览器 Origin。
- 在同一环境打开需要的行为事件、实验曝光和功能开关使用采集。要查看统计结果，还须配置曝光来源、指标和对应事件。

- [Customer 与会话](https://www.longplayai.com/zh-hans/docs/guides/customers.md#sessions)

<a id="flags"></a>

## 读取功能开关

**flags.ts**

```ts
import { createLongplay } from "@tinkerlandai/longplay-sdk";

const longplay = createLongplay({
  baseUrl: "https://api.longplayai.com",
  scope: { projectId: "<APP_UUID>", environment: "sandbox" },
});

export async function loadFlags(
  customerToken: string,
  customer: { id: string; externalUserId: string | null },
) {
  longplay.identify(customerToken);
  const identity = { id: customer.id, externalUserId: customer.externalUserId };
  const flags = await longplay.features({ attributes: { ...identity, country: "CA" } });
  const enabled = flags.getFeatureValue("new-checkout", false);
  const unsubscribe = flags.subscribe(() => console.log(flags.isOn("new-checkout")));
  longplay.track("Checkout Viewed", { source: "pricing" });
  await longplay.flush();
  return { enabled, stop: () => (unsubscribe(), flags.destroy()) };
}
```

- 传入 `id`（Customer UUID）和 `externalUserId`，同一用户在各处得到一致的实验分组。
- 这两个字段供本地功能开关使用。远程功能开关读取会话已验证的 Customer，SDK 不会把它们放进远程求值请求。
- `setAttributes()` 会替换全部属性，更新时保留这两个字段。
- 后端可以用 `getFeatures` 或 `evaluateFeatures` 读取和求值（需要 `features:read`）。
- 带 `customerId` 调用 `evaluateFeatures` 时，`attributes` 不能包含 `id`、`externalUserId`、`createdAt`、`ageDays` 或 `subscription`：这些值来自 Customer，传入时返回写明字段名的 `INVALID_REQUEST`。

<a id="events"></a>

## 上报事件

> 使用官方 SDK 上报事件，至少需要 `0.10.20`。`POST /api/v1/events` 只接受带 `kind` 的类型化事件（`custom`、`experiment_exposure` 或 `feature_usage`），旧 SDK 无法上报事件。直接使用 HTTP 时须遵循当前的类型化请求与逐事件结果契约，无需安装 SDK。

`track(name, properties)` 记录行为事件，`flush()` 立即发送。实验曝光和功能开关使用会自动记录；可在 Console 中按环境开关每类采集。

上例在读取 new-checkout 后上报 Checkout Viewed 并调用 flush()。将 key、事件名和属性替换为你的真实业务定义；组件卸载或换号时调用 stop() 并清理 Customer 客户端。

<a id="verify"></a>

## 核对求值与事件结果

**结果与排错**

| 现象 | 检查 |
| --- | --- |
| 一直得到默认值 | 检查 key、发布环境、定向属性和流量条件；默认值不是命中实验的证明。 |
| 401 / 403 | 检查 Customer Token、features:read / events:write、Origin 与 App/环境。 |
| 事件已发送但没有统计结果 | 区分发送与接收，再检查采集开关、事件名、曝光关联、指标配置及数据量。flush 完成不等于已产生统计结论。 |

<a id="page-experiments"></a>

## 网页实验

在页面中加载 URL 跳转实验和可视化实验，不需要凭据。环境 UUID 可从 Console 的实验页面复制。

**experiments.ts**

```ts
import { createPageExperiments } from "@tinkerlandai/longplay-sdk/page";
import { createVisualExperiments } from "@tinkerlandai/longplay-sdk/visual";

// The environment UUID is public; it selects published experiments and authenticates nothing.
const redirects = createPageExperiments({ environmentId: "<ENVIRONMENT_UUID>", baseUrl: "https://api.longplayai.com" });
const visual = createVisualExperiments({ environmentId: "<ENVIRONMENT_UUID>", baseUrl: "https://api.longplayai.com" });

export async function startExperiments() {
  await Promise.all([redirects.start(), visual.start()]);
}
```

<a id="operations"></a>

## 相关接口

- **功能开关、求值与事件 (3)**:  [getFeatures](https://www.longplayai.com/zh-hans/docs/api/get-features.md); [evaluateFeatures](https://www.longplayai.com/zh-hans/docs/api/evaluate-features.md); [trackEvents](https://www.longplayai.com/zh-hans/docs/api/track-events.md)

- [路径、凭据与权限见全部接口](https://www.longplayai.com/zh-hans/docs/api/operations.md#features)
