快速开始
安装 SDK,创建 Customer,检查权益并上报一次用量。
API v1更新于
开始之前#
- 在生产 Console(console.longplayai.com)选择用于接入验证的 App,并创建 Sandbox Server Key,权限包含
customers:write、entitlements:read、credits:consume。Sandbox 数据也属于生产环境。 - 在 Console 的 Features 中创建一个计量 Feature,复制它的 ID。
- 在 Console 的 商业配置 → 产品与权益 → Products 中配置一个包含该 Feature 的免费默认 Product,新 Customer 会自动获得它。
1LONGPLAY_API_URL=https://api.longplayai.com2LONGPLAY_SERVER_KEY=<SERVER_KEY>3LONGPLAY_PROJECT_ID=<APP_UUID>4LONGPLAY_FEATURE_ID=<FEATURE_UUID>
把配置放在后端已被 Git 忽略的环境文件中。为这个免费 Product 配置至少一次检查和一次消费所需的额度;不要把 Server Key 放进浏览器公开变量。
相关:创建 Server Key
1 安装 SDK#
1npm install --save-exact @tinkerlandai/longplay-sdk@latest
2 创建 Customer、检查权益、上报用量#
把下面的程序保存到你的后端项目并运行。
quickstart.tsTypeScript 1import { createLongplayServer } from "@tinkerlandai/longplay-sdk/server";2 3const longplay = createLongplayServer({4 baseUrl: process.env.LONGPLAY_API_URL!,5 apiKey: process.env.LONGPLAY_SERVER_KEY!,6 scope: { projectId: process.env.LONGPLAY_PROJECT_ID!, environment: "sandbox" },7});8const featureId = process.env.LONGPLAY_FEATURE_ID!;9 10async function main() {11 // 1. Find or create the Customer for your signed-in user.12 const { customer } = await longplay.getOrCreateCustomer({ externalUserId: "user-42" });13 14 // 2. Check access before doing the work.15 const { check } = await longplay.checkEntitlement({16 customerId: customer.id,17 requirement: { internal_feature_id: featureId, quantity: "1", properties: {} },18 });19 if (!check.allowed) return console.log("blocked:", check.reason);20 21 // 3. Report usage after the work succeeds. Use your own event ID in production.22 const { receipts } = await longplay.trackUsage({23 customerId: customer.id,24 command: { internal_feature_id: featureId, quantity: "1", idempotencyKey: crypto.randomUUID() },25 });26 console.log("recorded:", receipts[0]?.accepted);27}28 29main().catch((error) => {30 console.error(error);31 process.exitCode = 1;32});
1node --env-file=.env.local --experimental-strip-types quickstart.ts
上述命令需要 Node.js 22.6+;Python / Go 按项目现有方式载入相同环境变量,再运行 python quickstart.py / go run .。真实应用使用已验证的用户 ID。
3 核对结果#
成功时输出 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 状态码。 |