# 快速开始

安装 SDK，创建 Customer，检查权益并上报一次用量。

更新于 2026-11-06

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

<a id="before"></a>

## 开始之前

- 在生产 Console（console.longplayai.com）选择用于接入验证的 App，并创建 Sandbox Server Key，权限包含 `customers:write`、`entitlements:read`、`credits:consume`。Sandbox 数据也属于生产环境。
- 在 Console 的 Features 中创建一个计量 Feature，复制它的 ID。
- 在 Console 的 商业配置 → 产品与权益 → Products 中配置一个包含该 Feature 的免费默认 Product，新 Customer 会自动获得它。

**.env.local**

```bash
LONGPLAY_API_URL=https://api.longplayai.com
LONGPLAY_SERVER_KEY=<SERVER_KEY>
LONGPLAY_PROJECT_ID=<APP_UUID>
LONGPLAY_FEATURE_ID=<FEATURE_UUID>
```

把配置放在后端已被 Git 忽略的环境文件中。为这个免费 Product 配置至少一次检查和一次消费所需的额度；不要把 Server Key 放进浏览器公开变量。

- [创建 Server Key](https://www.longplayai.com/zh-hans/docs/guides/server-auth.md)

<a id="install"></a>

## 安装 SDK

**TypeScript: npm**

```bash
npm install --save-exact @tinkerlandai/longplay-sdk@latest
```

**Python: pip**

```bash
SDK_VERSION="$(curl -fsS 'https://cdn.longplayai.com/sdk/longplay/stable?package=python')" &&
python -m pip install "https://cdn.longplayai.com/downloads/python/tinkerlandai_longplay_sdk-$SDK_VERSION-py3-none-any.whl" &&
python -m pip freeze > requirements.lock
```

**Go: go**

```bash
SDK_VERSION="$(curl -fsS 'https://cdn.longplayai.com/sdk/longplay/stable?package=go')" &&
go get longplayai.com/sdk/go@v"$SDK_VERSION"
```

<a id="run"></a>

## 创建 Customer、检查权益、上报用量

把下面的程序保存到你的后端项目并运行。

**TypeScript: quickstart.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: quickstart.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)
}
```

**terminal**

```bash
node --env-file=.env.local --experimental-strip-types quickstart.ts
```

上述命令需要 Node.js 22.6+；Python / Go 按项目现有方式载入相同环境变量，再运行 python quickstart.py / go run .。真实应用使用已验证的用户 ID。

<a id="result"></a>

## 核对结果

成功时输出 `recorded: true`。再次运行会返回同一个 Customer，并再记录一次用量。

同时核对返回的 Customer ID、App / Sandbox scope、check.allowed 和消费 receipt。示例每次运行都会创建新的用量 ID；恢复同一笔业务时保存并复用原幂等键，不能通过重新运行产生新扣减。

**常见问题**

| 现象 | 处理 |
| --- | --- |
| `blocked: insufficient_balance` | Customer 没有这个 Feature 的可用余额：检查默认 Product 的配置、是否包含该 Feature，以及是否已分配给该 Customer；已有 Customer 再次登录不会重新分配默认 Product。 |
| 401 `UNAUTHENTICATED` | Key 不完整、过期或已撤销。 |
| 403 `FORBIDDEN` | Key 缺少上面列出的权限。 |
| 403 `SCOPE_MISMATCH` | `LONGPLAY_PROJECT_ID` 或 `environment` 与 Key 所属的 App 和环境不一致。 |
| 请求发出前就报错 | SDK 在本地校验输入：例如 `LONGPLAY_FEATURE_ID` 不是 UUID 时，TypeScript 抛出校验错误（ZodError），Python 和 Go 返回本地 `INVALID_REQUEST`，没有 HTTP 状态码。 |

<a id="next"></a>

## 下一步

- [让浏览器直接调用](https://www.longplayai.com/zh-hans/docs/guides/customers.md#sessions)
- [支付、订阅与账单](https://www.longplayai.com/zh-hans/docs/guides/commerce.md)
- [商户通知与 Webhook](https://www.longplayai.com/zh-hans/docs/guides/notifications.md)
