跳到正文
Longplay
开发文档
章节目录 / JavaScript / TypeScript

JavaScript / TypeScript

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

Markdown
API v1更新于

安装#

terminalShell
npm install --save-exact @tinkerlandai/longplay-sdk@latest

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

相关:安装 SDK 与 CLI

通过 script 接入#

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

terminalShell
SDK_MODULE_URL="$(curl -fsS https://cdn.longplayai.com/sdk/module)" &&printf 'export * from "%s";\n' "$SDK_MODULE_URL" > longplay-sdk.js
index.htmlHTML
<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.htmlHTML
<link rel="preconnect" href="https://api.longplayai.com" crossorigin><link rel="preconnect" href="https://cdn.longplayai.com" crossorigin>

IAM 与视觉实验绑定#

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

相关:IAM 完整接入指南

服务端客户端#

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

longplay.server.tsTypeScript
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 与 CIresolveContent

按领域划分的服务端方法

  • 客户消息与设备

    方法
    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
客户端选项
选项说明
apiKeyServer Key(gg_sk_),保存在后端密钥系统。
scope{ projectId, environment }:App UUID 与 sandbox 或 live,必须与 Key 一致。
baseUrlAPI origin,默认 https://api.longplayai.com;本页设置为 https://api.longplayai.com,不带 /api/v1。
timeoutMs单次请求超时,默认 10000,最大 120000。
fetch注入自定义 fetch,用于代理或离线测试。

客户端选项

  • 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,用于代理或离线测试。

浏览器客户端#

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

server/session.tsTypeScript
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);}
按领域划分的浏览器方法
领域方法
客户消息与设备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 与 CIresolveContent

按领域划分的浏览器方法

  • 客户消息与设备

    方法
    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 解析和购买报价。

独立 Page、Popup 与 Banner#

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

content.tsTypeScript
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。展示和点击不授予商业权限,业务后端仍负责鉴权与执行。

Funnel、Paywall 与实验#

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

其他导出

  • 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·支付、订阅与账单·Feature、实验与事件

错误与重试#

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

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

相关:错误码与恢复