# 设置用量限额与超额计费规则

Operation / SDK: `manageBillingLimits` · `manage_billing_limits` · `ManageBillingLimits`

后端为 Customer 设置用量上限、提醒阈值和超额规则。

更新于 2026-11-06

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

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

## 请求

- **凭据**: Server Key，权限 `billing:write`。只在后端调用。
- **SDK**: JavaScript `createLongplayServer().manageBillingLimits` · Python `manage_billing_limits` · Go `ManageBillingLimits`
- **成功状态**: HTTP 200

响应为示例数据。

**cURL: request.sh**

```bash
curl -X POST "$LONGPLAY_API_URL/api/v1/billing/controls/manage" \
  -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": {
    "internal_feature_id": "f317c851-0ef2-4d7a-8e3c-e8a29df676ed",
    "entityId": null,
    "interval": "month",
    "basis": "usage",
    "limit": "1000",
    "thresholds": [
      0.8,
      1
    ],
    "requestId": "0f58d1f8-069f-4288-8ec1-4ed10af55b45"
  }
}'
```

**TypeScript: manageBillingLimits.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 manageBillingLimits() {
  return longplay.manageBillingLimits({
    customerId: "8b258f8b-4228-40fa-8d24-5b16428e686d",
    command: {
      internal_feature_id: "f317c851-0ef2-4d7a-8e3c-e8a29df676ed",
      entityId: null,
      interval: "month",
      basis: "usage",
      limit: "1000",
      thresholds: [
        0.8,
        1,
      ],
      requestId: "0f58d1f8-069f-4288-8ec1-4ed10af55b45",
    },
  });
}
```

**请求体: request.json**

```json
{
  "customerId": "8b258f8b-4228-40fa-8d24-5b16428e686d",
  "command": {
    "internal_feature_id": "f317c851-0ef2-4d7a-8e3c-e8a29df676ed",
    "entityId": null,
    "interval": "month",
    "basis": "usage",
    "limit": "1000",
    "thresholds": [
      0.8,
      1
    ],
    "requestId": "0f58d1f8-069f-4288-8ec1-4ed10af55b45"
  }
}
```

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

```json
{
  "requestId": "44f5fcb8-6ed8-41b8-818f-7571941c5fd5",
  "scope": {
    "projectId": "df5426d6-b335-403c-8f3e-b0f73d2e3511",
    "environment": "sandbox"
  },
  "controls": {
    "authorizations": [
      {
        "id": "ec0718b4-46db-4174-8885-e2ed6354c9e5",
        "terms": {
          "productVersionId": "8c489a1a-5542-44fe-8e80-da2f6a319d01",
          "internal_feature_id": "f317c851-0ef2-4d7a-8e3c-e8a29df676ed",
          "currency": "USD",
          "kind": "auto_topup",
          "threshold": "-1",
          "quantity": "1",
          "purchaseAmountMinor": "1",
          "purchaseUnits": "1"
        },
        "status": "prepared",
        "createdAt": "2026-10-03T12:00:00.000Z",
        "acceptedAt": null,
        "effectiveAt": null,
        "revokedAt": null
      }
    ],
    "limits": [
      {
        "internal_feature_id": "f317c851-0ef2-4d7a-8e3c-e8a29df676ed",
        "entityId": null,
        "interval": "day",
        "basis": "usage",
        "limit": null,
        "thresholds": [
          1
        ]
      }
    ],
    "windows": [
      {
        "internal_feature_id": "f317c851-0ef2-4d7a-8e3c-e8a29df676ed",
        "entityId": null,
        "interval": "day",
        "basis": "usage",
        "startsAt": "2026-10-03T12:00:00.000Z",
        "endsAt": "2099-01-01T00:00:00.000Z",
        "used": "1",
        "reserved": "1",
        "limit": null,
        "thresholds": [
          1
        ],
        "notifiedThresholds": [
          1
        ]
      }
    ],
    "autoTopups": [
      {
        "authorizationId": "ec0718b4-46db-4174-8885-e2ed6354c9e5",
        "status": "idle",
        "taskId": null,
        "invoiceId": null,
        "hostedInvoiceUrl": null,
        "purchaseCount": 0,
        "purchaseWindowEndsAt": null,
        "attemptCount": 0,
        "failedAttemptCount": 0,
        "suspendedAt": null,
        "nextAttemptAt": null,
        "failureReason": null
      }
    ],
    "limited": true
  }
}
```

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

## 请求体参数

**application/json**

- `customerId` (uuid, required): Customer 的 UUID。
- `command` (object | object | object, required): 要执行的命令；其中的 `action` 或 `operation` 决定其余字段。
- `command.internal_feature_id` (uuid | uuid | uuid, required): Feature 的 ID。
- `command.entityId` (uuid | null | uuid | null | uuid | null, required): 当前客户范围内的 Entity ID；只用于已配置的 Entity 和许可 Feature。
- `command.interval` (enum, optional): 周期，取值见允许值。 Values: `"day"`, `"week"`, `"month"`, `"year"`.
- `command.anchor` (enum, optional): 周期对齐方式，取值见允许值。 Values: `"billing_cycle"`, `"utc"`.
- `command.basis` (enum, optional): 计量依据：用量（`usage`）或积分（`credits`）。 Values: `"usage"`, `"credits"`.
- `command.filter` (object, optional): 筛选条件。
- `command.limit` (string | null, optional): 一页返回的最大记录数量，受契约上限限制。
- `command.thresholds` (array, optional): 按上限比例的提醒阈值，如 `0.8`。 maxItems: 8
- `command.includedThresholds` (array, optional): 按套餐内额度比例的提醒阈值。 maxItems: 8
- `command.absoluteThresholds` (array, optional): 按绝对数量的提醒阈值。 maxItems: 8
- `command.requestId` (uuid | uuid | uuid, required): 你的业务请求 UUID；同一次操作重试复用，新的操作生成新值。
- `command.control` ("overage" | "overage", optional): 传 `overage` 表示设置或移除某个 Feature 的超额策略（配合 `action`）；省略则设置用量限制规则。
- `command.action` ("set" | "remove", optional): 本次业务动作。不同动作的目标字段和数量要求不同，见请求结构与示例。
- `command.allowed` (boolean | null, optional): 当前评估时是否允许访问此 Feature。仅用于展示，业务操作仍需后端授权。
- `command.overageLimit` (string | null, optional): 窗口内只计算超出包含额度的单位数量，预扣占用容量。null 不设上限，0 禁止新增超额。
- `command.skipOverageBilling` (boolean, optional): 显式允许超额时免收现金费用，仍记录用量并执行数量上限。

<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"`.
- `controls` (object, required): 计费控制设置。
- `controls.authorizations` (array, required): 授权，字段见下。 maxItems: 100
- `controls.authorizations.id` (uuid, required): 授权 的 ID。
- `controls.authorizations.terms` (object | object, required): 条款内容。
- `controls.authorizations.terms.productVersionId` (uuid | uuid, required): Product Version 的 ID。
- `controls.authorizations.terms.internal_feature_id` (uuid | uuid, required): Feature 的 ID。
- `controls.authorizations.terms.currency` (enum | enum, required): 已发布价格支持的币种代码。
- `controls.authorizations.terms.kind` ("auto_topup" | "postpaid", required): 类型，取值见允许值。
- `controls.authorizations.terms.threshold` (string, optional): 触发阈值，十进制字符串。 pattern: ^-?(0|[1-9]\d{0,11})(\.\d{1,6})?$
- `controls.authorizations.terms.quantity` (string, optional): 数量，十进制字符串，避免浮点误差。 pattern: ^(0|[1-9]\d{0,11})(\.\d{1,6})?$
- `controls.authorizations.terms.purchaseLimit` (object, optional): 自动购买的上限（可选）。
- `controls.authorizations.terms.purchaseAmountMinor` (string, optional): 金额，以最小货币单位计（如美分）。 pattern: ^(?:[1-9]\d{0,7}|1\d{8}|200000000)$
- `controls.authorizations.terms.purchaseUnits` (string, optional): 购买数量。 pattern: ^(0|[1-9]\d{0,11})(\.\d{1,6})?$
- `controls.authorizations.terms.maxAmountMinorPerPeriod` (string, optional): 仅用于 `postpaid` 条款：每个计费周期最多可收取的金额（不含税），以最小货币单位的整数字符串表示（`1`–`200000000`）。 pattern: ^(?:[1-9]\d{0,7}|1\d{8}|200000000)$
- `controls.authorizations.terms.maxOutstandingMinor` (string, optional): 金额，以最小货币单位计（如美分）。 pattern: ^(?:[1-9]\d{0,7}|1\d{8}|200000000)$
- `controls.authorizations.terms.cashPrice` (object, optional): 现金价格。
- `controls.authorizations.status` (enum, required): 状态，取值见允许值。 Values: `"prepared"`, `"active"`, `"revoked"`, `"blocked"`.
- `controls.authorizations.createdAt` (date-time, required): 记录创建时的 ISO 8601 UTC 时间。
- `controls.authorizations.acceptedAt` (date-time | null, required): 时间（ISO 8601）。
- `controls.authorizations.effectiveAt` (date-time | null, required): 时间（ISO 8601）。
- `controls.authorizations.revokedAt` (date-time | null, required): 时间（ISO 8601）。
- `controls.limits` (array, required): 用量上限设置。 maxItems: 100
- `controls.limits.internal_feature_id` (uuid, required): Feature 的 ID。
- `controls.limits.entityId` (uuid | null, required): 当前客户范围内的 Entity ID；只用于已配置的 Entity 和许可 Feature。
- `controls.limits.interval` (enum, required): 周期，取值见允许值。 Values: `"day"`, `"week"`, `"month"`, `"year"`.
- `controls.limits.anchor` (enum, optional): 周期对齐方式，取值见允许值。 Values: `"billing_cycle"`, `"utc"`.
- `controls.limits.basis` (enum, required): 计量依据：用量（`usage`）或积分（`credits`）。 Values: `"usage"`, `"credits"`.
- `controls.limits.filter` (object, optional): 筛选条件。
- `controls.limits.limit` (string | null, required): 一页返回的最大记录数量，受契约上限限制。
- `controls.limits.thresholds` (array, required): 按上限比例的提醒阈值，如 `0.8`。 maxItems: 8
- `controls.limits.includedThresholds` (array, optional): 按套餐内额度比例的提醒阈值。 maxItems: 8
- `controls.limits.absoluteThresholds` (array, optional): 按绝对数量的提醒阈值。 maxItems: 8
- `controls.overages` (array, optional): 超额设置。 maxItems: 100
- `controls.overages.internal_feature_id` (uuid, required): Feature 的 ID。
- `controls.overages.entityId` (uuid | null, required): 当前客户范围内的 Entity ID；只用于已配置的 Entity 和许可 Feature。
- `controls.overages.allowed` (boolean | null, required): 当前评估时是否允许访问此 Feature。仅用于展示，业务操作仍需后端授权。
- `controls.overages.overageLimit` (string | null, required): 窗口内只计算超出包含额度的单位数量，预扣占用容量。null 不设上限，0 禁止新增超额。
- `controls.overages.skipOverageBilling` (boolean, required): 显式允许超额时免收现金费用，仍记录用量并执行数量上限。
- `controls.overages.interval` (enum, required): 周期，取值见允许值。 Values: `"day"`, `"week"`, `"month"`, `"year"`.
- `controls.overages.startsAt` (date-time, required): 时间（ISO 8601）。
- `controls.overages.endsAt` (date-time, required): 时间（ISO 8601）。
- `controls.overages.used` (string, required): 当前计量周期内已用额度。 pattern: ^(0|[1-9]\d{0,23})(\.\d{1,6})?$
- `controls.overages.reserved` (string, required): 已预留的数量。 pattern: ^(0|[1-9]\d{0,23})(\.\d{1,6})?$
- `controls.overages.remaining` (string | null, required): 评估时的剩余额度，不预占，也不保证稍后消费成功。
- `controls.windows` (array, required): 统计窗口，字段见下。 maxItems: 200
- `controls.windows.internal_feature_id` (uuid, required): Feature 的 ID。
- `controls.windows.entityId` (uuid | null, required): 当前客户范围内的 Entity ID；只用于已配置的 Entity 和许可 Feature。
- `controls.windows.interval` (enum, required): 周期，取值见允许值。 Values: `"day"`, `"week"`, `"month"`, `"year"`.
- `controls.windows.anchor` (enum, optional): 周期对齐方式，取值见允许值。 Values: `"billing_cycle"`, `"utc"`.
- `controls.windows.basis` (enum, required): 计量依据：用量（`usage`）或积分（`credits`）。 Values: `"usage"`, `"credits"`.
- `controls.windows.filter` (object, optional): 筛选条件。
- `controls.windows.startsAt` (date-time, required): 时间（ISO 8601）。
- `controls.windows.endsAt` (date-time, required): 时间（ISO 8601）。
- `controls.windows.used` (string, required): 当前计量周期内已用额度。 pattern: ^(0|[1-9]\d{0,12})(\.\d{1,12})?$
- `controls.windows.reserved` (string, required): 已预留的数量。 pattern: ^(0|[1-9]\d{0,12})(\.\d{1,12})?$
- `controls.windows.limit` (string | null, required): 一页返回的最大记录数量，受契约上限限制。
- `controls.windows.thresholds` (array, required): 按上限比例的提醒阈值，如 `0.8`。 maxItems: 8
- `controls.windows.notifiedThresholds` (array, required): 已发送通知的上限比例阈值。 maxItems: 1024
- `controls.windows.includedThresholds` (array, optional): 按套餐内额度比例的提醒阈值。 maxItems: 8
- `controls.windows.includedAllowance` (string, optional): 套餐内包含的额度。 pattern: ^(0|[1-9]\d{0,17})(\.\d{1,12})?$
- `controls.windows.notifiedIncludedThresholds` (array, optional): 已发送通知的套餐内额度阈值。 maxItems: 1024
- `controls.windows.absoluteThresholds` (array, optional): 按绝对数量的提醒阈值。 maxItems: 8
- `controls.windows.notifiedAbsoluteThresholds` (array, optional): 已发送通知的绝对数量阈值。 maxItems: 1024
- `controls.autoTopups` (array, required): 自动充值设置。 maxItems: 100
- `controls.autoTopups.authorizationId` (uuid, required): 授权的 ID。
- `controls.autoTopups.status` (enum, required): 状态，取值见允许值。 Values: `"idle"`, `"pending"`, `"blocked"`.
- `controls.autoTopups.taskId` (uuid | null, required): 任务的 ID。
- `controls.autoTopups.invoiceId` (uuid | null, required): 发票的 ID。
- `controls.autoTopups.hostedInvoiceUrl` (uri | null, required): 发票托管页面链接。
- `controls.autoTopups.purchaseCount` (integer, required): 当前 `purchaseLimit` 窗口（截止于 `purchaseWindowEndsAt`）内已完成的自动充值购买次数；没有进行中的窗口时为 `0`。 min: 0 · max: 9007199254740991
- `controls.autoTopups.purchaseWindowEndsAt` (date-time | null, required): 时间（ISO 8601）。
- `controls.autoTopups.attemptCount` (integer, required): 当前 10 分钟尝试窗口内的自动充值尝试次数；达到 2 次后自动充值暂停，直到 `nextAttemptAt`。没有进行中的窗口时为 `0`。 min: 0 · max: 9007199254740991
- `controls.autoTopups.failedAttemptCount` (integer, required): 当前 1 小时窗口内失败的自动充值尝试次数；失败 1 次后自动充值暂停，直到 `nextAttemptAt`。没有进行中的窗口时为 `0`。 min: 0 · max: 9007199254740991
- `controls.autoTopups.suspendedAt` (date-time | null, required): 时间（ISO 8601）。
- `controls.autoTopups.nextAttemptAt` (date-time | null, required): 时间（ISO 8601）。
- `controls.autoTopups.failureReason` (string | null, required): 失败原因。
- `controls.limited` (boolean, required): 匹配的用量限制规则超过 100 条时为 `true`，此时 `limits` 只列出前 100 条。

<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 | 凭据没有 `billing:write` 权限。 | `check_permissions` |
| `SCOPE_MISMATCH` | 403 | `X-Indiana-Project` 或 `X-Indiana-Environment` 与凭据所属的 App 和环境不一致。 | `check_scope` |
| `CONFLICT` | 409 | 同一个 `requestId` 用了不同的输入（`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#invoices)
