# 上报 Feature 或事件用量

Operation / SDK: `trackUsage` · `track_usage` · `TrackUsage`

按事件名或 Feature 上报用量，返回逐条受理回执。

更新于 2026-11-06

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

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

## 请求

- **凭据**: Server Key，权限 `credits:consume`。只在后端调用。
- **SDK**: JavaScript `createLongplayServer().trackUsage` · Python `track_usage` · Go `TrackUsage`
- **成功状态**: HTTP 200

响应为示例数据。

**cURL: request.sh**

```bash
curl -X POST "$LONGPLAY_API_URL/api/v1/usage/track" \
  -H "Authorization: Bearer $LONGPLAY_SERVER_KEY" \
  -H "X-Indiana-Protocol: 0.10" \
  -H "Content-Type: application/json" \
  -d '{
  "customerId": "8b258f8b-4228-40fa-8d24-5b16428e686d",
  "command": {
    "eventName": "document_exported",
    "quantity": "1",
    "properties": {},
    "idempotencyKey": "export:export_123"
  }
}'
```

**TypeScript: trackUsage.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 trackUsage() {
  return longplay.trackUsage({
    customerId: "8b258f8b-4228-40fa-8d24-5b16428e686d",
    command: {
      eventName: "document_exported",
      quantity: "1",
      properties: {},
      idempotencyKey: "export:export_123",
    },
  });
}
```

**请求体: request.json**

```json
{
  "customerId": "8b258f8b-4228-40fa-8d24-5b16428e686d",
  "command": {
    "eventName": "document_exported",
    "quantity": "1",
    "properties": {},
    "idempotencyKey": "export:export_123"
  }
}
```

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

```json
{
  "requestId": "44f5fcb8-6ed8-41b8-818f-7571941c5fd5",
  "scope": {
    "projectId": "df5426d6-b335-403c-8f3e-b0f73d2e3511",
    "environment": "sandbox"
  },
  "receipts": [
    {
      "id": "a8b14e0c-6576-49a4-812c-7a1587e55255",
      "internal_feature_id": "13fca2b7-63e8-4e82-881f-173a43762c65",
      "kind": "consume",
      "originalId": null,
      "quantity": "1",
      "accepted": true,
      "reason": null,
      "createdAt": "2026-10-03T12:00:00.000Z",
      "reservationStatus": null,
      "expiresAt": null,
      "allocations": [
        {
          "funding": "postpaid",
          "invoiceLineId": "73701ec0-ca86-4128-81a7-f9d99b63dd8d",
          "units": "1",
          "authorizationId": "ec0718b4-46db-4174-8885-e2ed6354c9e5"
        }
      ]
    }
  ]
}
```

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

## 请求体参数

**application/json**

- `customerId` (uuid, required): Customer 的 UUID。
- `command` (object | object, required): 要执行的命令；其中的 `action` 或 `operation` 决定其余字段。
- `command.eventName` (string, optional): 在 Feature 上配置的事件名：所有列出该事件名且未归档的计量或积分 Feature 都会被消耗，每个 Feature 返回一条回执。与 `internal_feature_id` 二选一。 minLength: 1
- `command.quantity` (string | string, optional): 数量，十进制字符串，避免浮点误差。
- `command.properties` (object | object, optional): 服务端校验的计价属性，用于匹配维度和倍率。
- `command.entityId` (uuid | uuid, optional): 当前客户范围内的 Entity ID；只用于已配置的 Entity 和许可 Feature。
- `command.idempotencyKey` (string | string, required): 稳定的业务幂等 Key。同一 Key 和同一参数返回同一结果；不要每次重试随机生成。
- `command.internal_feature_id` (uuid, optional): Feature 的 ID。

<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"`.
- `receipts` (array, required): 逐条回执；检查每条的 `accepted` 与 `reason`。 minItems: 1
- `receipts.id` (uuid, required): 回执 的 ID。
- `receipts.internal_feature_id` (uuid, required): Feature 的 ID。
- `receipts.kind` (enum, required): 类型，取值见允许值。 Values: `"consume"`, `"reserve"`, `"confirm"`, `"refund"`, `"release"`, `"expire"`.
- `receipts.originalId` (uuid | null, required): 原始记录的 ID。
- `receipts.quantity` (string, required): 数量，十进制字符串，避免浮点误差。 pattern: ^(0|[1-9]\d{0,11})(\.\d{1,6})?$
- `receipts.requestedQuantity` (string, optional): 显式 cap／overflow 的原请求数量；quantity 是实际接受或拒绝的数量。 pattern: ^(0|[1-9]\d{0,11})(\.\d{1,6})?$
- `receipts.overageBehavior` (enum, optional): cap 接受当前许可及上限内的最大数量，可为 0；overflow 请求完整数量并检查超额许可、用量上限和现金预算。省略时维持整次不足就拒绝。 Values: `"cap"`, `"overflow"`.
- `receipts.accepted` (boolean, required): 操作是否被业务规则接受。HTTP 200 不等于 accepted 为 true。
- `receipts.reason` (enum | null, required): 拒绝原因或账本操作说明；结合 accepted / 状态判断结果。
- `receipts.createdAt` (date-time, required): 记录创建时的 ISO 8601 UTC 时间。
- `receipts.reservationStatus` (enum | null, required): 预留状态，取值见允许值。
- `receipts.expiresAt` (date-time | null, required): 到期时间（ISO 8601，UTC）。
- `receipts.allocations` (array, required): 本次规则计算或账本操作涉及的余额分配明细。 maxItems: 500
- `receipts.allocations.funding` ("balance" | "unbilled" | "prepaid" | "postpaid", required): 扣减来源，取值见允许值。
- `receipts.allocations.sourceId` (uuid | uuid, optional): 余额来源的 ID。
- `receipts.allocations.rolloverId` (uuid | null, optional): 结转记录的 ID。
- `receipts.allocations.units` (string | string | string | string, required): 该分配覆盖的操作数量，以操作所属 Feature 的单位计；十进制字符串。所有分配的 `units` 之和等于 `quantity`。
- `receipts.allocations.amount` (string | string, optional): 积分或账本金额，按字段的十进制字符串或整数类型传入。
- `receipts.allocations.pricing` (array, optional): 计价明细。 minItems: 1 · maxItems: 12
- `receipts.allocations.pricing.internal_credit_feature_id` (uuid | null, required): 积分 Feature 的 ID。
- `receipts.allocations.pricing.internal_metered_feature_id` (uuid, required): 计量 Feature 的 ID。
- `receipts.allocations.pricing.dimension` (string, required): 计价维度。 minLength: 1 · maxLength: 64
- `receipts.allocations.pricing.counterKey` (string, required): 计数器键。 minLength: 1 · maxLength: 240
- `receipts.allocations.pricing.cycleStart` (date-time, required): 周期开始时间。
- `receipts.allocations.pricing.unitCost` (string, required): 单价。 pattern: ^(0|[1-9]\d{0,11})(\.\d{1,6})?$
- `receipts.allocations.pricing.units` (string, required): 数量，十进制字符串。 pattern: ^(0|[1-9]\d{0,11})(\.\d{1,6})?$
- `receipts.allocations.pricing.amount` (string, required): 积分或账本金额，按字段的十进制字符串或整数类型传入。 pattern: ^(0|[1-9]\d{0,12})(\.\d{1,12})?$
- `receipts.allocations.pricing.tier` (integer | null, required): 阶梯档位。
- `receipts.allocations.invoiceLineId` (uuid | null, optional): 发票行的 ID。
- `receipts.allocations.authorizationId` (uuid, optional): 授权的 ID。

<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 | 凭据没有 `credits:consume` 权限。 | `check_permissions` |
| `SCOPE_MISMATCH` | 403 | `X-Indiana-Project` 或 `X-Indiana-Environment` 与凭据所属的 App 和环境不一致。 | `check_scope` |
| `CONFLICT` | 409 | 同一个 `idempotencyKey` 用了不同的输入（`reason: IDEMPOTENCY_CONFLICT`）。 | `resolve_conflict` |
| `RATE_LIMITED` | 429 | 请求过多；按 `Retry-After` 等待后用同一请求重试。 | `retry_same_request` |
| `SERVICE_UNAVAILABLE` | 503 | 服务暂时不可用；用同一请求重试。 | `retry_same_request` |
| `INTERNAL_ERROR` | 500 | 结果未知；先读取原操作，或用原 ID 和原输入重放。 | `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#credits)
