# 权益、余额与用量

检查权益、上报用量、管理余额与 Entity，并为 AI 调用计费。

更新于 2026-11-06

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

<a id="check"></a>

## 检查权益并上报用量

执行功能前调用 `checkEntitlement`，完成后调用 `trackUsage`。数量都是十进制字符串。

**TypeScript: usage.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" },
});
const featureId = process.env.LONGPLAY_FEATURE_ID!;

async function main() {
  // 1. Find or create the Customer for your signed-in user.
  const { customer } = await longplay.getOrCreateCustomer({ externalUserId: "user-42" });

  // 2. Check access before doing the work.
  const { check } = await longplay.checkEntitlement({
    customerId: customer.id,
    requirement: { internal_feature_id: featureId, quantity: "1", properties: {} },
  });
  if (!check.allowed) return console.log("blocked:", check.reason);

  // 3. Report usage after the work succeeds. Use your own event ID in production.
  const { receipts } = await longplay.trackUsage({
    customerId: customer.id,
    command: { internal_feature_id: featureId, quantity: "1", idempotencyKey: crypto.randomUUID() },
  });
  console.log("recorded:", receipts[0]?.accepted);
}

main().catch((error) => {
  console.error(error);
  process.exitCode = 1;
});
```

**Python: usage.py**

```python
import os
import uuid

from longplay import Longplay

feature_id = os.environ["LONGPLAY_FEATURE_ID"]

with Longplay(
    api_key=os.environ["LONGPLAY_SERVER_KEY"],
    project_id=os.environ["LONGPLAY_PROJECT_ID"],
    environment="sandbox",
    base_url=os.environ["LONGPLAY_API_URL"],
) as client:
    # 1. Find or create the Customer for your signed-in user.
    customer_id = client.get_or_create_customer(external_user_id="user-42")["customer"]["id"]

    # 2. Check access before doing the work.
    check = client.check_entitlement(
        customer_id=customer_id, internal_feature_id=feature_id, quantity="1"
    )["check"]
    if not check["allowed"]:
        print("blocked:", check["reason"])
    else:
        # 3. Report usage after the work succeeds. Use your own event ID in production.
        usage = client.track_usage(
            customer_id=customer_id,
            internal_feature_id=feature_id,
            quantity="1",
            idempotency_key=str(uuid.uuid4()),
        )
        print("recorded:", usage["receipts"][0]["accepted"])
```

**Go: main.go**

```go
package main

import (
	"context"
	"crypto/rand"
	"encoding/hex"
	"log"
	"os"

	longplay "longplayai.com/sdk/go"
)

func main() {
	client, err := longplay.NewClient(longplay.Config{
		APIKey:      os.Getenv("LONGPLAY_SERVER_KEY"),
		ProjectID:   os.Getenv("LONGPLAY_PROJECT_ID"),
		Environment: longplay.Sandbox,
		BaseURL:     os.Getenv("LONGPLAY_API_URL"),
	})
	if err != nil {
		log.Fatal(err)
	}
	defer client.Close()
	ctx := context.Background()
	featureID := os.Getenv("LONGPLAY_FEATURE_ID")

	// 1. Find or create the Customer for your signed-in user.
	customer, err := client.GetOrCreateCustomer(ctx, longplay.CreateCustomerParams{
		ExternalUserID: longplay.Ptr("user-42"),
	})
	if err != nil {
		log.Fatal(err)
	}

	// 2. Check access before doing the work.
	access, err := client.CheckEntitlement(ctx, longplay.CheckEntitlementParams{
		CustomerID: customer.Customer.ID,
		Requirement: longplay.CheckEntitlementParamsRequirement{
			InternalFeatureID: featureID,
			Quantity:          "1",
			Properties:        map[string]any{},
		},
	})
	if err != nil {
		log.Fatal(err)
	}
	if !access.Check.Allowed {
		log.Println("blocked")
		return
	}

	// 3. Report usage after the work succeeds. Use your own event ID in production.
	key := make([]byte, 16)
	if _, err := rand.Read(key); err != nil {
		log.Fatal(err)
	}
	usage, err := client.TrackUsage(ctx, longplay.TrackUsageParams{
		CustomerID: customer.Customer.ID,
		Command: longplay.TrackUsageParamsCommand{
			InternalFeatureID: longplay.Ptr(featureID),
			Quantity:          longplay.Ptr("1"),
			IdempotencyKey:    hex.EncodeToString(key),
		},
	})
	if err != nil {
		log.Fatal(err)
	}
	log.Println("recorded:", usage.Receipts[0].Accepted)
}
```

- 为每次用量生成并保存 `idempotencyKey`；结果未知时用同一个 key 重试，不会重复计费。
- HTTP 200 不代表已扣减：检查每条回执的 `accepted` 和 `reason`。

- [产品概览：用量计费](https://www.longplayai.com/zh-hans/usage-based-billing)

<a id="reserve"></a>

## 先预留、后确认

耗时任务可以先预留余额，完成后按实际数量确认，失败时释放。

**reserve.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" },
});

const feature = process.env.LONGPLAY_FEATURE_ID!;

// Hold credits before long-running work; keys are persisted per job.
export async function runJob(customerId: string, jobId: string, estimate: string) {
  const { receipt } = await longplay.mutateBalance({
    customerId,
    command: {
      operation: "reserve",
      internal_feature_id: feature,
      quantity: estimate,
      properties: {},
      idempotencyKey: `${jobId}:reserve`,
      expiresInSeconds: 600,
    },
  });
  if (!receipt.accepted) return { started: false as const, reason: receipt.reason };
  return { started: true as const, reservationId: receipt.id };
}

export async function finishJob(customerId: string, jobId: string, reservationId: string, actual: string | null) {
  const command = actual
    ? { operation: "confirm" as const, operationId: reservationId, quantity: actual, idempotencyKey: `${jobId}:confirm` }
    : { operation: "release" as const, operationId: reservationId, idempotencyKey: `${jobId}:release` };
  const { receipt } = await longplay.mutateBalance({ customerId, command });
  return receipt;
}
```

<a id="balances"></a>

## 读取余额与账本

**balances.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 readBalances(customerId: string) {
  const { holdings } = await longplay.readHoldings({ customerId });
  const { ledger } = await longplay.readLedger({
    customerId,
    query: { type: null, from: null, to: null, after: null, limit: 20 },
  });
  return { holdings, ledger };
}
```

**余额管理**

| 任务 | 方法 |
| --- | --- |
| 创建或撤销余额发放 | `manageBalanceGrant`, `listBalanceGrants` |
| 修正单个余额 | `adjustBalance`, `readBalanceSource` |
| 直接设定用量 | `setUsage`, `readUsage` |
| 批量上报用量 | `submitUsageBatch`, `readUsageBatch` |
| 对账单与统计 | `readCreditStatement`, `readUsageAnalytics`, `readCreditAnalytics` |
| 按工作区或设备计量 | `manageUsageEntity` |
| 席位分配 | `readSeats`, `manageSeat` |

<a id="ai"></a>

## 按 AI 调用计费

把中间件传给 AI SDK 的 `wrapLanguageModel`，每次调用按实际 token 用量计费。

**ai-billing.ts**

```ts
import {
  createAiUsageMiddleware,
  createConfiguredAiPricing,
  createLongplayServer,
  type AiUsageRecord,
} 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" },
});

// Your own durable store for usage records and frozen quotes.
declare function saveUsageRecord(record: AiUsageRecord): Promise<void>;

export async function billingMiddleware(customerId: string, callId: string) {
  const featureId = process.env.LONGPLAY_AI_FEATURE_ID!;
  const pricing = await createConfiguredAiPricing(longplay, {
    internal_feature_id: featureId,
    customerId,
  });
  return createAiUsageMiddleware({
    pricing,
    client: longplay,
    modelId: "openai/gpt-4o",
    reasoning: "output",
    context: () => ({ customerId, internal_feature_id: featureId, idempotencyKey: callId }),
    persist: saveUsageRecord,
  });
}
// Pass the result to wrapLanguageModel({ model, middleware }) from the AI SDK.
```

- 每次模型调用使用新的 `idempotencyKey`，并在 `persist` 中保存记录，用于失败后恢复。
- `modelId` 写成 `provider/model`；后端需要能访问 https://models.dev 获取模型价格。

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

## 相关接口

- **权益与商品展示 (4)**:  [checkEntitlement](https://www.longplayai.com/zh-hans/docs/api/check-entitlement.md); [resolveOffering](https://www.longplayai.com/zh-hans/docs/api/resolve-offering.md); [resolvePaywall](https://www.longplayai.com/zh-hans/docs/api/resolve-paywall.md); [readHoldings](https://www.longplayai.com/zh-hans/docs/api/read-holdings.md)
- **余额、用量与账本 (16)**:  [readBalanceSource](https://www.longplayai.com/zh-hans/docs/api/read-balance-source.md); [adjustBalance](https://www.longplayai.com/zh-hans/docs/api/adjust-balance.md); [readUsage](https://www.longplayai.com/zh-hans/docs/api/read-usage.md); [setUsage](https://www.longplayai.com/zh-hans/docs/api/set-usage.md); [manageBalanceGrant](https://www.longplayai.com/zh-hans/docs/api/manage-balance-grant.md); [listBalanceGrants](https://www.longplayai.com/zh-hans/docs/api/list-balance-grants.md); [manageUsageEntity](https://www.longplayai.com/zh-hans/docs/api/manage-usage-entity.md); [readUsageAnalytics](https://www.longplayai.com/zh-hans/docs/api/read-usage-analytics.md); [readCreditAnalytics](https://www.longplayai.com/zh-hans/docs/api/read-credit-analytics.md); [submitUsageBatch](https://www.longplayai.com/zh-hans/docs/api/submit-usage-batch.md); [readUsageBatch](https://www.longplayai.com/zh-hans/docs/api/read-usage-batch.md); [readLedger](https://www.longplayai.com/zh-hans/docs/api/read-ledger.md); [readCreditStatement](https://www.longplayai.com/zh-hans/docs/api/read-credit-statement.md); [quoteBalance](https://www.longplayai.com/zh-hans/docs/api/quote-balance.md); [trackUsage](https://www.longplayai.com/zh-hans/docs/api/track-usage.md); [mutateBalance](https://www.longplayai.com/zh-hans/docs/api/mutate-balance.md)
- **席位 (2)**:  [readSeats](https://www.longplayai.com/zh-hans/docs/api/read-seats.md); [manageSeat](https://www.longplayai.com/zh-hans/docs/api/manage-seat.md)
- **AI 定价 (1)**:  [readAiPricing](https://www.longplayai.com/zh-hans/docs/api/read-ai-pricing.md)

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