# 查询客户账本

Operation / SDK: `readLedger` · `read_ledger` · `ReadLedger`

读取 Customer 账本页及其业务引用。

更新于 2026-11-06

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

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

## 请求

- **凭据**: Server Key（传 `customerId`）或 Customer Token，权限 `credits:read`。
- **SDK**: JavaScript `createLongplayServer().readLedger` · JavaScript `createLongplay().readLedger` · Python `read_ledger` · Go `ReadLedger`
- **成功状态**: HTTP 200

响应为示例数据。

**cURL: request.sh**

```bash
curl -X POST "$LONGPLAY_API_URL/api/v1/customer-ledger" \
  -H "Authorization: Bearer $LONGPLAY_SERVER_KEY" \
  -H "X-Indiana-Protocol: 0.10" \
  -H "Content-Type: application/json" \
  -d '{
  "query": {
    "type": null,
    "from": null,
    "to": null,
    "after": null,
    "limit": 50
  },
  "customerId": "8b258f8b-4228-40fa-8d24-5b16428e686d"
}'
```

**TypeScript: readLedger.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 readLedger() {
  return longplay.readLedger({
    query: {
      type: null,
      from: null,
      to: null,
      after: null,
      limit: 50,
    },
    customerId: "8b258f8b-4228-40fa-8d24-5b16428e686d",
  });
}
```

**请求体: request.json**

```json
{
  "query": {
    "type": null,
    "from": null,
    "to": null,
    "after": null,
    "limit": 50
  },
  "customerId": "8b258f8b-4228-40fa-8d24-5b16428e686d"
}
```

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

```json
{
  "requestId": "44f5fcb8-6ed8-41b8-818f-7571941c5fd5",
  "scope": {
    "projectId": "df5426d6-b335-403c-8f3e-b0f73d2e3511",
    "environment": "sandbox"
  },
  "ledger": {
    "customerId": "8b258f8b-4228-40fa-8d24-5b16428e686d",
    "rows": [
      {
        "id": "943d12d9-ac64-41f2-816e-aa9a70aaf4e5",
        "occurredAt": "2026-10-03T12:00:00.000Z",
        "type": "invoice",
        "status": "1Example",
        "paid": "1",
        "refunded": "1",
        "currency": "USD",
        "externalId": "1Example"
      }
    ],
    "nextCursor": null
  }
}
```

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

## 请求体参数

**application/json**

- `customerId` (uuid, optional): Customer 的 UUID。
- `query` (object, required): 查询条件。
- `query.type` (enum | null, required): 只返回该类型的条目；为 `null` 时返回所有类型。
- `query.resourceKey` (string, optional): 余额返回的资源标识；独立额度是 Feature key，池为 pool:<poolId>。 minLength: 1 · pattern: ^[a-zA-Z0-9_-]+$
- `query.kind` (enum, optional): 类型，取值见允许值。 Values: `"purchase"`, `"refund"`.
- `query.topup` (boolean, optional): 为 `true` 时只返回包含充值（top-up）Product 的发票；为 `false` 或省略时不筛选。
- `query.from` (date | null, required): 时间范围起点（ISO 8601）。
- `query.to` (date | null, required): 时间范围终点（ISO 8601）。
- `query.after` (object | null, required): 分页游标：传上一页返回的值获取下一页；首页传 `null`。
- `query.after.at` (date-time, required): 游标字段：上一页最后一行的发生时间（ISO 8601）。原样传回上一页的 `nextCursor`。
- `query.after.id` (uuid, required): 游标字段：上一页最后一行的 ID（账本中为条目 `id`，积分对账单中为 `operationId`）。原样传回上一页的 `nextCursor`。
- `query.after.type` (enum, required): 游标字段：上一页最后一行的条目类型。原样传回上一页的 `nextCursor`。 Values: `"source"`, `"usage"`, `"transaction"`, `"invoice"`, `"debt"`, `"settlement"`.
- `query.limit` (integer, required): 一页返回的最大记录数量，受契约上限限制。 min: 1 · max: 50

<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"`.
- `ledger` (object, required): Customer 财务账本的一页条目，按时间从新到旧排列，并附带用于读取下一页的 `nextCursor`。
- `ledger.customerId` (uuid, required): Customer 的 UUID。
- `ledger.rows` (array, required): 数据行。 maxItems: 50
- `ledger.rows.id` (uuid | uuid | uuid | uuid | uuid | uuid, required): 该行记录的 UUID：余额发放记录（可作为 `grantId` 使用）、账本条目（与 `type` 一起唯一）或发票（可作为 `invoiceId` 使用）。
- `ledger.rows.occurredAt` (date-time | date-time | date-time | date-time | date-time | date-time, required): 时间（ISO 8601）。
- `ledger.rows.type` ("invoice" | "source" | "usage" | "transaction" | "debt" | "settlement", required): 条目类型：`source` 为余额授予；`usage` 为余额操作；`transaction` 为已验证的付款或退款；`invoice` 为已验证的发票；`debt` 为某个余额来源上的欠款；`settlement` 为冲抵欠款的付款、用量退还或付款退回。
- `ledger.rows.status` (string | enum, optional): 状态，取值见允许值。
- `ledger.rows.paid` (string, optional): 该发票已支付的金额，以 `currency` 的主币单位计（例如 `12.5`）；十进制字符串。 pattern: ^(0|[1-9]\d{0,17})(\.\d{1,12})?$
- `ledger.rows.refunded` (string, optional): 已退款部分。 pattern: ^(0|[1-9]\d{0,17})(\.\d{1,12})?$
- `ledger.rows.currency` (enum | enum | null, optional): 已发布价格支持的币种代码。
- `ledger.rows.externalId` (string | null, optional): 外部系统中的 ID。
- `ledger.rows.internal_feature_id` (uuid | uuid | uuid | uuid, optional): Feature 的 ID。
- `ledger.rows.key` (string | string | string, optional): 该条目所属 Feature 的 key。
- `ledger.rows.name` (string | string | string | string, optional): 展示名称，不作为唯一标识。
- `ledger.rows.kind` (enum | enum | enum | enum | enum, optional): 类型，取值见允许值。
- `ledger.rows.reason` (enum | enum | null, optional): 拒绝原因或账本操作说明；结合 accepted / 状态判断结果。
- `ledger.rows.quantity` (string | string, optional): 数量，十进制字符串，避免浮点误差。
- `ledger.rows.unlimited` (boolean, optional): 是否不限量。
- `ledger.rows.startsAt` (date-time, optional): 时间（ISO 8601）。
- `ledger.rows.expiresAt` (date-time | null | date-time | null, optional): 到期时间（ISO 8601，UTC）。
- `ledger.rows.orderId` (uuid | null | uuid, optional): 订单的 ID。
- `ledger.rows.parentSourceId` (uuid | null, optional): 若该来源由更早的来源结转（rollover）而来，则为那个来源的 ID；否则为 `null`。
- `ledger.rows.originalId` (uuid | null | uuid | null, optional): 原始记录的 ID。
- `ledger.rows.accepted` (boolean, optional): 操作是否被业务规则接受。HTTP 200 不等于 accepted 为 true。
- `ledger.rows.properties` (object, optional): 服务端校验的计价属性，用于匹配维度和倍率。
- `ledger.rows.reservationStatus` (enum | null, optional): 预留状态，取值见允许值。
- `ledger.rows.charges` (array, optional): 已接受的用量操作的资金来源：扣减的余额来源（`balance`）、未从任何余额扣减的数量（`unbilled`），以及预付或后付费用。被拒绝的操作、设置用量条目和数量为 0 的消耗为空数组。 maxItems: 500
- `ledger.rows.charges.funding` ("balance" | "unbilled" | "prepaid" | "postpaid", required): 扣减来源，取值见允许值。
- `ledger.rows.charges.sourceId` (uuid, optional): 余额来源的 ID。
- `ledger.rows.charges.rolloverId` (uuid | null, optional): 结转记录的 ID。
- `ledger.rows.charges.units` (string | string | string, optional): 该费用覆盖的用量数量，以该用量条目所属 Feature 的单位计；十进制字符串。
- `ledger.rows.charges.amount` (string | string, optional): 积分或账本金额，按字段的十进制字符串或整数类型传入。
- `ledger.rows.charges.internal_feature_id` (uuid, optional): Feature 的 ID。
- `ledger.rows.charges.key` (string, optional): 该 `prepaid` 费用所扣减的 Feature 的 key；仅出现在 `prepaid` 费用中。 minLength: 1 · pattern: ^[a-zA-Z0-9_-]+$
- `ledger.rows.charges.name` (string, optional): 展示名称，不作为唯一标识。 minLength: 1 · maxLength: 120
- `ledger.rows.charges.kind` (enum, optional): 类型，取值见允许值。 Values: `"access"`, `"metered"`, `"credit"`.
- `ledger.rows.charges.invoiceId` (uuid, optional): 发票的 ID。
- `ledger.rows.charges.invoiceLineId` (uuid, optional): 发票行的 ID。
- `ledger.rows.charges.authorizationId` (uuid, optional): 授权的 ID。
- `ledger.rows.charges.currency` (enum, optional): 已发布价格支持的币种代码。 Values: `"USD"`, `"EUR"`, `"CNY"`, `"GBP"`, `"JPY"`, `"CAD"`, `"AUD"`, `"NZD"`, `"CHF"`, `"HKD"`, `"SGD"`, `"KRW"`, `"INR"`, `"BRL"`, `"MXN"`, `"TWD"`, `"THB"`, `"IDR"`, `"MYR"`, `"PHP"`, `"VND"`, `"ZAR"`, `"AED"`, `"SAR"`, `"SEK"`, `"NOK"`, `"DKK"`, `"PLN"`, `"CZK"`, `"HUF"`, `"ILS"`, `"TRY"`, `"RON"`.
- `ledger.rows.purpose` (enum, optional): 付款用途：`product` 为购买 Product Version；`invoice` 为支付发票。 Values: `"product"`, `"invoice"`.
- `ledger.rows.productVersionId` (uuid | null, optional): Product Version 的 ID。
- `ledger.rows.productName` (string | null, optional): Product 名称。
- `ledger.rows.productVersion` (integer | null, optional): 所购 Product Version 的版本号；`purpose` 为 `invoice` 时为 `null`。
- `ledger.rows.invoiceId` (uuid | null, optional): 发票的 ID。
- `ledger.rows.amountMinor` (integer | null, optional): 金额，以最小货币单位计（如美分）。
- `ledger.rows.sourceId` (uuid | uuid, optional): 余额来源的 ID。
- `ledger.rows.transactionId` (uuid, optional): 原消费返回的账本交易 UUID，退款必须引用这个记录。
- `ledger.rows.amount` (string | string, optional): 积分或账本金额，按字段的十进制字符串或整数类型传入。
- `ledger.rows.debtId` (uuid, optional): 该结清记录所冲抵的 `debt` 条目 ID。
- `ledger.nextCursor` (object | null, required): 下一页游标；null 表示结束。原样传回，改筛选条件时清空。
- `ledger.nextCursor.at` (date-time, required): 本页最后一行的发生时间（ISO 8601）；属于游标的一部分，原样作为 `after` 传回。
- `ledger.nextCursor.id` (uuid, required): 本页最后一行的 ID。读取下一页时，原样传回整个 `nextCursor` 对象。
- `ledger.nextCursor.type` (enum, required): 本页最后一行的条目类型；属于游标的一部分，原样作为 `after` 传回。 Values: `"source"`, `"usage"`, `"transaction"`, `"invoice"`, `"debt"`, `"settlement"`.

<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:read` 权限。 | `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#credits)
