# 上报行为与实验事件

Operation / SDK: `trackEvents` · `track` · `flush` · `track_events` · `TrackEvents`

上报行为、实验曝光和功能开关使用事件。

更新于 2026-11-06

[网页版本](https://www.longplayai.com/zh-hans/docs/api/track-events)

<a id="request"></a>

## 请求

- **凭据**: Server Key（传 `customerId`）或 Customer Token，权限 `events:write`。
- **SDK**: JavaScript `createLongplayServer().trackEvents` · JavaScript `createLongplay().track` · Python `track_events` · Go `TrackEvents`
- **成功状态**: HTTP 200

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

- [事件上报版本要求](https://www.longplayai.com/zh-hans/docs/guides/version-support.md#event-recording)

响应为示例数据。

**cURL: request.sh**

```bash
curl -X POST "$LONGPLAY_API_URL/api/v1/events" \
  -H "Authorization: Bearer $LONGPLAY_SERVER_KEY" \
  -H "X-Indiana-Protocol: 0.10" \
  -H "Content-Type: application/json" \
  -d '{
  "events": [
    {
      "eventUuid": "b4eaa1be-aa5e-42c4-85d4-f83fd95d74e9",
      "timestamp": "2026-10-03T12:00:00.000Z",
      "kind": "custom",
      "name": "Pro"
    }
  ],
  "customerId": "8b258f8b-4228-40fa-8d24-5b16428e686d"
}'
```

**TypeScript: trackEvents.ts**

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

const longplay = createLongplayServer({
  baseUrl: process.env.LONGPLAY_API_URL!,
  apiKey: process.env.LONGPLAY_SERVER_KEY!,
  scope: { projectId: process.env.LONGPLAY_PROJECT_ID!, environment: "sandbox" },
});

export async function trackEvents() {
  return longplay.trackEvents({
    events: [
      {
        eventUuid: "b4eaa1be-aa5e-42c4-85d4-f83fd95d74e9",
        timestamp: "2026-10-03T12:00:00.000Z",
        kind: "custom",
        name: "Pro",
      },
    ],
    customerId: "8b258f8b-4228-40fa-8d24-5b16428e686d",
  });
}
```

**请求体: request.json**

```json
{
  "events": [
    {
      "eventUuid": "b4eaa1be-aa5e-42c4-85d4-f83fd95d74e9",
      "timestamp": "2026-10-03T12:00:00.000Z",
      "kind": "custom",
      "name": "Pro"
    }
  ],
  "customerId": "8b258f8b-4228-40fa-8d24-5b16428e686d"
}
```

**响应示例: response.json**

```json
{
  "requestId": "44f5fcb8-6ed8-41b8-818f-7571941c5fd5",
  "scope": {
    "projectId": "df5426d6-b335-403c-8f3e-b0f73d2e3511",
    "environment": "sandbox"
  },
  "inserted": 1,
  "duplicates": 0,
  "rejected": 0,
  "skipped": 0,
  "rejections": [],
  "analyticsConfig": {
    "eventsEnabled": true,
    "experimentViewsEnabled": true,
    "featureUsageEnabled": true
  }
}
```

<a id="parameters"></a>

## 请求体参数

**application/json**

- `customerId` (uuid, optional): Customer 的 UUID。
- `events` (array, required): 事件列表。 minItems: 1 · maxItems: 100
- `events.eventUuid` (uuid | uuid | uuid, required): 该事件的唯一 ID：生成一次并在重试时复用。ID 已记录过的事件计入 `duplicates`，不会重复存储。
- `events.timestamp` (date-time | date-time | date-time, required): 时间。
- `events.merchandise` (object | object | object | object | object | object, optional): 事件关联的当前 App 和环境的商品引用。
- `events.merchandise.id` (string | string | string, optional): 商户登记的稳定商品 ID，由服务端解析为当前范围内的商品。
- `events.merchandise.internalId` (uuid | uuid | uuid, optional): 内部的 ID。
- `events.deviceId` (string | string | string, optional): 产生该事件的设备或浏览器的稳定标识，例如匿名 cookie 值；随事件一起存储用于分析。
- `events.sessionId` (string | string | string, optional): 会话的 ID。
- `events.kind` ("custom" | "experiment_exposure" | "feature_usage", required): 事件类型：`custom` 是你自己记录的事件；`experiment_exposure` 和 `feature_usage` 是本地评估产生的记录，SDK 会自动发送。
- `events.name` (string, optional): 自定义事件的名称。`Experiment Viewed` 和 `Feature Evaluated` 是保留名称，使用时该事件会被拒绝。 minLength: 1 · maxLength: 255
- `events.properties` (object, optional): 服务端校验的计价属性，用于匹配维度和倍率。 default: {}
- `events.generation` (string | string, optional): 产生这条记录的功能开关配置代次，取自配置内容的 `generation`。
- `events.experimentId` (string, optional): 用户看到的实验的 key。 minLength: 1 · maxLength: 255
- `events.variationId` (string | string, optional): 用户分到的变体的 key。
- `events.feature` (string, optional): 被读取的功能开关的 key。 minLength: 1 · maxLength: 255
- `events.value` (object, optional): 这次评估返回的值。
- `events.source` (enum, optional): 这个值的来源，例如默认值、规则或实验。 Values: `"unknownFeature"`, `"defaultValue"`, `"force"`, `"override"`, `"experiment"`, `"prerequisite"`, `"cyclicPrerequisite"`.
- `events.ruleId` (string, optional): 决定这个值的规则 ID；没有规则时为空字符串。 maxLength: 255

<a id="response"></a>

## 响应字段

成功响应都包含 `requestId`（本次请求 ID，排查时提供）和 `scope`（App 与环境）。

**HTTP 200 · application/json**

- `requestId` (uuid, required): 服务端为这次 HTTP 请求生成的 UUID，排查时提供；它不是你的业务 requestId。
- `scope` (object, required): 响应实际所属的 App 和环境。Header 只能核对，不能切换 Key 范围。
- `scope.projectId` (string, required): 凭据绑定的 App ID。 minLength: 1
- `scope.environment` (enum, required): 独立数据范围：sandbox 或 live。 Values: `"sandbox"`, `"live"`.
- `inserted` (integer, required): 新写入的事件数。 min: 0 · max: 9007199254740991
- `duplicates` (integer, required): 重复（已存在）的事件数。 min: 0 · max: 9007199254740991
- `rejected` (integer, required): 被拒绝的事件数。 min: 0 · max: 9007199254740991
- `skipped` (integer, required): 因采集设置关闭而跳过的事件数。 min: 0 · max: 9007199254740991
- `rejections` (array, required): 被拒绝的事件，每条一项。同批其他事件不受影响。 maxItems: 100
- `rejections.eventUuid` (uuid, required): 被拒绝事件的 `eventUuid`。
- `rejections.reason` (enum, required): 拒绝原因：`invalid_event`、`invalid_merchandise`、`not_delivered` 或 `reserved_name`。被拒绝的事件不要重试，结果不会改变。 Values: `"invalid_event"`, `"invalid_merchandise"`, `"not_delivered"`, `"reserved_name"`.
- `analyticsConfig` (object, required): 当前环境的事件采集设置。
- `analyticsConfig.eventsEnabled` (boolean, required): 是否采集行为事件。
- `analyticsConfig.experimentViewsEnabled` (boolean, required): 是否采集实验曝光。
- `analyticsConfig.featureUsageEnabled` (boolean, required): 是否采集功能开关使用事件。

<a id="errors"></a>

## 错误

失败时返回错误对象，按 `error.code` 与 `error.recovery` 处理。下表是这个接口的凭据、作用域和幂等字段决定的错误；视请求内容还可能返回 `NOT_FOUND`（引用的资源不存在）、`NOT_CONFIGURED`（所需的集成未连接）或 `PAYLOAD_TOO_LARGE`。有些拒绝（如余额不足）不是错误，而是成功响应里的 `reason`。

**可能的错误**

| code | HTTP | 何时 | recovery |
| --- | --- | --- | --- |
| `INVALID_REQUEST` | 400 | 请求不符合本页的参数。缺少或无法解析协议头时分别返回 `UNSUPPORTED_PROTOCOL_VERSION` 或 `INVALID_PROTOCOL_VERSION`。 | `fix_request` |
| `UNAUTHENTICATED` | 401 | 凭据缺失、无效、过期或已撤销。 | `authenticate` |
| `FORBIDDEN` | 403 | 凭据没有 `events:write` 权限。 | `check_permissions` |
| `SCOPE_MISMATCH` | 403 | `X-Indiana-Project` 或 `X-Indiana-Environment` 与凭据所属的 App 和环境不一致。 | `check_scope` |
| `RATE_LIMITED` | 429 | 请求过多；按 `Retry-After` 等待后用同一请求重试。 | `retry_same_request` |
| `SERVICE_UNAVAILABLE` | 503 | 服务暂时不可用；用同一请求重试。 | `retry_same_request` |
| `INTERNAL_ERROR` | 500 | 结果未知；稍后重试。 | `recover_operation` |

- [错误码与恢复](https://www.longplayai.com/zh-hans/docs/api/errors.md)
- [请求约定](https://www.longplayai.com/zh-hans/docs/api.md)
- [全部接口](https://www.longplayai.com/zh-hans/docs/api/operations.md#features)
