# JavaScript / TypeScript

服务端与浏览器客户端、全部方法、Funnel／Paywall／实验入口与错误处理。

更新于 2026-11-06

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

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

## 安装

**terminal**

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

一个包同时支持 Node.js 22+ 后端和浏览器，并内置 TypeScript 类型。本页使用生产 API https://api.longplayai.com 和该部署的 Sandbox 凭据。各入口及环境要求见安装页。

- [安装 SDK 与 CLI](https://www.longplayai.com/zh-hans/docs/install.md#javascript)

<a id="script"></a>

## 通过 script 接入

普通 HTML 网站无需 npm 或打包工具。首次安装解析最新 Web 发布的不可变模块地址，保存为 longplay-sdk.js 并提交；页面从该文件导入。升级时主动重新解析地址。下面使用生产 API 的 Sandbox 凭据。

**terminal**

```bash
SDK_MODULE_URL="$(curl -fsS https://cdn.longplayai.com/sdk/module)" &&
printf 'export * from "%s";\n' "$SDK_MODULE_URL" > longplay-sdk.js
```

**index.html**

```html
<script type="module">
  import { createLongplay } from "./longplay-sdk.js";
  // This endpoint must verify your existing signed-in user before issuing credentials.
  const response = await fetch("/api/longplay-session", {
    credentials: "same-origin", cache: "no-store",
  });
  if (!response.ok) throw new Error("Customer session unavailable");
  const session = await response.json();
  const client = createLongplay({
    baseUrl: "https://api.longplayai.com",
    scope: { projectId: "<APP_UUID>", environment: "sandbox" },
  });
  client.identify(session);
  console.log(await client.readHoldings());
  client.track("page_viewed", { page: location.pathname });
  await client.flush();
  // Call client.reset() on logout/account change, and destroy any open UI hosts.
</script>
```

longplay-sdk.js 导出 npm 根入口的全部浏览器 API，以及 `createPageExperiments` / `createVisualExperiments`。将各指南的 npm import 改为从 longplay-sdk.js 导入同名函数：权益和事件使用 `createLongplay`，Paywall 使用 `createPaywallSession` / `showPaywall`，Funnel 使用 `createFunnelRunController` / `showFunnelRun`，独立内容使用 `mountContent`。

加载不自动创建会话、发送事件或启动实验。Customer Token 由验证登录后的商家后端签发；Server Key 留在后端。Funnel 沿用后端启动及 Run 恢复流程。加载失败会拒绝模块导入。UI 按需加载，旧版本模块随归档保留。CSP 需允许脚本来源和目标 API。现有经典脚本 /sdk.js 仍提供 Longplay.ready，并随 Web 发布更新。页面实验也通过统一入口显式创建客户端并调用 `start()`。

展示 Funnel 或 Paywall 的页面可以提前建立连接。把下面两行放进页面的 head。`crossorigin` 必须带上：SDK 发请求时不带凭据，缺了它打开的连接 SDK 用不上。

**index.html**

```html
<link rel="preconnect" href="https://api.longplayai.com" crossorigin>
<link rel="preconnect" href="https://cdn.longplayai.com" crossorigin>
```

<a id="iam"></a>

## IAM 与视觉实验绑定

页面目录由独立的 IAM 构建包生成。将描述文件的摘要传入 createVisualExperiments 的 appManifestRelease，再显式调用 start；构建、上传和发布实验分别完成。

- [IAM 完整接入指南](https://www.longplayai.com/zh-hans/docs/iam.md)

<a id="server"></a>

## 服务端客户端

`createLongplayServer` 使用 Server Key，只能在可信后端创建；在浏览器中调用会抛出 `SERVER_ONLY`。每个方法对应一个 HTTP 操作，请求与响应都按公开契约校验。

**longplay.server.ts**

```ts
import { createLongplayServer, LongplayError } 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 generateImage(verifiedUserId: string, eventId: string) {
  const { customer } = await longplay.getOrCreateCustomer({
    externalUserId: verifiedUserId,
  });
  const { check } = await longplay.checkEntitlement({
    customerId: customer.id,
    requirement: {
      internal_feature_id: process.env.LONGPLAY_FEATURE_ID!,
      quantity: "1",
      properties: {},
    },
  });
  if (!check.allowed) return { allowed: false as const };

  try {
    const { receipts } = await longplay.trackUsage({
      customerId: customer.id,
      // eventId is persisted before the call and reused on every retry.
      command: { eventName: "image_generated", quantity: "1", idempotencyKey: eventId },
    });
    for (const receipt of receipts)
      if (!receipt.accepted) console.warn("usage refused", receipt.reason);
    return { allowed: true as const, receipts };
  } catch (error) {
    if (error instanceof LongplayError) console.error(error.code, error.recovery, error.requestId);
    throw error;
  }
}
```

**按领域划分的服务端方法**

| 领域 | 方法 |
| --- | --- |
| 客户消息与设备 | `sendMessage`, `readMessage` |
| Customer、访客与会话 | `getOrCreateCustomer`, `getCustomer`, `listCustomers`, `updateCustomer`, `createCustomerSession`, `revokeCustomerSessions`, `createGuestCustomer`, `resumeGuestSession`, `claimGuestCustomer` |
| 权益与商品展示 | `checkEntitlement`, `resolveOffering`, `resolvePaywall`, `readHoldings` |
| 余额、用量与账本 | `readBalanceSource`, `adjustBalance`, `readUsage`, `setUsage`, `manageBalanceGrant`, `listBalanceGrants`, `manageUsageEntity`, `readUsageAnalytics`, `readCreditAnalytics`, `submitUsageBatch`, `readUsageBatch`, `readLedger`, `readCreditStatement`, `quoteBalance`, `trackUsage`, `mutateBalance` |
| 席位 | `readSeats`, `manageSeat` |
| 订阅与支付 | `setupPayment`, `readPaymentSetup`, `verifySubscriptions`, `previewAttach`, `attach`, `readSubscriptionOperation`, `previewUpdate`, `update`, `readSubscriptionUpdate`, `listSubscriptions`, `listPurchases`, `listSubscriptionConflicts`, `retrySubscriptionConflict`, `manageSubscriptionTrial`, `readSubscriptionTrial`, `previewSubscriptionBatch`, `confirmSubscriptionBatch`, `readSubscriptionBatch`, `abandonSubscriptionBatch`, `recordMerchantEvent` |
| 发票、退款与计费 | `listInvoiceTemplates`, `previewInvoice`, `createInvoice`, `manageInvoice`, `readInvoiceOperation`, `listInvoices`, `getInvoice`, `previewRefund`, `refund`, `readRefund`, `manageBillingLimits`, `readBillingInvoice`, `prepareBillingAdjustment` |
| 优惠券、奖励与推荐 | `grantOffer`, `grantModelBenefit`, `readModelBenefit` |
| 功能开关、求值与事件 | `getFeatures`, `evaluateFeatures`, `trackEvents` |
| 原生购买 | `restoreNativePurchase` |
| AI 定价 | `readAiPricing` |
| CLI 与 CI | `resolveContent` |

**客户端选项**

| 选项 | 说明 |
| --- | --- |
| `apiKey` | Server Key（`gg_sk_`），保存在后端密钥系统。 |
| `scope` | `{ projectId, environment }`：App UUID 与 `sandbox` 或 `live`，必须与 Key 一致。 |
| `baseUrl` | API origin，默认 https://api.longplayai.com；本页设置为 https://api.longplayai.com，不带 /api/v1。 |
| `timeoutMs` | 单次请求超时，默认 10000，最大 120000。 |
| `fetch` | 注入自定义 fetch，用于代理或离线测试。 |

<a id="browser"></a>

## 浏览器客户端

浏览器不持有 Server Key。后端验证用户登录后签发 Customer Token，浏览器用 `identify(token)` 建立身份；Customer 身份由 Token 决定，浏览器不能指定其他 customerId。退出或切换账号时调用 `reset()`。

**后端签发: server/session.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" },
});

// Call only after your own login check succeeds.
export async function issueCustomerSession(verifiedUserId: string) {
  const { customer } = await longplay.getOrCreateCustomer({
    externalUserId: verifiedUserId,
  });
  return longplay.createCustomerSession(customer.id);
}
```

**浏览器: app/longplay.ts**

```ts
import { createLongplay, type CustomerSession } from "@tinkerlandai/longplay-sdk";

const longplay = createLongplay({
  baseUrl: "https://api.longplayai.com",
  scope: { projectId: "<APP_UUID>", environment: "sandbox" },
});

export async function signIn(session: CustomerSession) {
  longplay.identify(session);
  const { holdings } = await longplay.readHoldings();
  return holdings;
}

export function signOut() {
  longplay.reset();
}
```

**按领域划分的浏览器方法**

| 领域 | 方法 |
| --- | --- |
| 客户消息与设备 | `push.sync`, `push.read`, `messaging.preference`, `messaging.setPreference` |
| Customer、访客与会话 | `session.refresh` |
| 权益与商品展示 | `checkEntitlement`, `resolveOffering`, `resolvePaywall`, `readHoldings` |
| 余额、用量与账本 | `readLedger`, `readCreditStatement`, `quoteBalance` |
| 订阅与支付 | `setupPayment`, `readPaymentSetup`, `previewAttach`, `attach`, `readSubscriptionOperation`, `previewUpdate`, `update`, `readSubscriptionUpdate` |
| 发票、退款与计费 | `readBillingControls`, `prepareBillingAuthorization`, `confirmBillingAuthorization`, `setBillingCoupons`, `revokeBillingAuthorization`, `listBillingInvoices`, `readBillingInvoice`, `confirmBillingAdjustment` |
| 优惠券、奖励与推荐 | `redeemCoupon`, `listOffers`, `claimCoupon`, `redeemReward`, `createReferralCode`, `claimRewardProduct` |
| 功能开关、求值与事件 | `features`, `track`, `flush` |
| 原生购买 | `restoreNativePurchase` |
| CLI 与 CI | `resolveContent` |

- 在 Console 的 接入 → 网站来源 登记网站来源（每行一个完整 origin，最多 20 个）。Sandbox 允许 localhost、127.0.0.1、[::1] 的 HTTP 开发地址；Live 只接受 HTTPS。
- 签发会话的 Key 需要 `sessions:create`，以及浏览器要调用的权限（如 `entitlements:read`、`billing:write`、`offers:resolve`）。
- `longplay.forFunnel({ funnelId, versionId })` 返回绑定该 Funnel 的资源客户端，用于领券、Offering／Paywall 解析和购买报价。

<a id="content"></a>

## 独立 Page、Popup 与 Banner

先发布一个没有必填输入、声明 continue 动作的 Banner。Customer Token 需要 content:read 权限。resolveContent 读取固定发布版本，mountContent 显式挂载；Page 和 Popup 使用相应 kind。

**content.ts**

```ts
import {
  createLongplay,
  mountContent,
  type ContentActionIntent,
} from "@tinkerlandai/longplay-sdk";

export async function showBanner(
  container: HTMLElement,
  customerToken: string,
  contentId: string,
  onContinue: (intent: ContentActionIntent) => Promise<void>,
) {
  const longplay = createLongplay({
    baseUrl: "https://api.longplayai.com",
    scope: { projectId: "<TEST_APP_UUID>", environment: "sandbox" },
  });
  longplay.identify(customerToken);
  const { content } = await longplay.resolveContent({
    kind: "banner",
    selector: { type: "resource", id: contentId },
  });
  const host = await mountContent(container, {
    content,
    actions: { continue: onContinue },
    onError: console.error,
  });
  return {
    retryAction: host.retryAction,
    destroy() {
      host.destroy();
      longplay.reset();
    },
  };
}
```

每个声明动作都要提供同名 handler；onContinue 用 intent.requestId 作为后端操作的幂等键。失败后调用返回的 retryAction 保留原意图，卸载、退出或换号时调用 destroy。展示和点击不授予商业权限，业务后端仍负责鉴权与执行。

<a id="helpers"></a>

## Funnel、Paywall 与实验

**其他导出**

| 函数 | 入口 | 用途 |
| --- | --- | --- |
| `createFunnelStartClient` | `/server` | 后端启动 Funnel Run，返回 Run Token |
| `createFunnelRunController`, `showFunnelRun` | 主入口 | 在浏览器中展示并推进 Run |
| `createFunnelClient` | 主入口 | 持有 Customer Token 的客户端自行启动 Run |
| `createLocalFunnelClient`, `createConfigurationSync` | 主入口 / `/server` | Local 模式 Funnel 与共享公开配置 |
| `createFunnelDecisionClient`, `createFunnelCampaignClient` | `/server` | 服务端决策、Campaign 启动与采纳回执 |
| `createFunnelOrchestrationClient`, `renewFunnelRun` | `/server` | 向 Run 发送信号、读取结果、轮换 Run Token |
| `createPaywallStartClient`, `createPaywallSession`, `showPaywall` | `/server` / 主入口 | 独立 Paywall 会话与展示 |
| `createFeatureClient`, `longplay.features()` | 主入口 | Feature 求值与订阅 |
| `createPageExperiments` | `/page` | URL 跳转实验 |
| `createVisualExperiments` | `/visual` | 可视化实验 |
| `createNativeReceiptClient` | `/server` | 后端提交原生商店凭证 |
| `createAiUsageMiddleware`, `createAiPricing` | `/server` | AI SDK 用量计费中间件与定价 |
| `createOpenRouterUsageClient`, `trackOpenRouterUsage` | `/openrouter` | OpenRouter 用量计费 |

- [运行 Funnel](https://www.longplayai.com/zh-hans/docs/guides/funnels.md)
- [支付、订阅与账单](https://www.longplayai.com/zh-hans/docs/guides/commerce.md)
- [Feature、实验与事件](https://www.longplayai.com/zh-hans/docs/guides/features.md)

<a id="errors"></a>

## 错误与重试

请求失败时抛出 `LongplayError`，包含 `code`、`status`、`requestId`、`retryable`、`recovery`，以及可选的 `reason` 和 `retryAfterSeconds`。SDK 不会自动重试写操作：在发送前持久保存 requestId、eventId 或 idempotencyKey，结果未知时用原值和原输入重放，或读取原操作。

> 输入不符合接口格式时，SDK 在发送前就抛错，不会发出请求。少数方法（如 `getOrCreateCustomer`、`grantOffer`）抛出 `LongplayError`（`INVALID_REQUEST`），大多数方法抛出 ZodError（`error.name === "ZodError"`），它不是 `LongplayError`。在调用前校验输入，或者两种错误都处理。

- [错误码与恢复](https://www.longplayai.com/zh-hans/docs/api/errors.md)
