跳到正文
Indiana
控制台
开发文档
章节目录 / JavaScript / TypeScript

JavaScript / TypeScript

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

API v1更新于

安装

terminalShell
npm install --save-exact @tinkerlandai/indiana-sdk@0.6.2

一个包同时支持 Node.js 22+ 后端和浏览器,并内置 TypeScript 类型。所有客户端默认请求 https://api.tinker.cash;测试服务需显式设置 baseUrl。各入口见安装页。

相关:安装 SDK 与 CLI

服务端客户端

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

indiana.server.tsTypeScript
import { createIndianaServer, IndianaError } from "@tinkerlandai/indiana-sdk/server"; const indiana = createIndianaServer({  baseUrl: process.env.INDIANA_API_URL!,  apiKey: process.env.INDIANA_API_KEY!,  scope: { projectId: process.env.INDIANA_PROJECT_ID!, environment: "sandbox" },}); export async function generateImage(verifiedUserId: string, eventId: string) {  const { customer } = await indiana.getOrCreateCustomer({    externalUserId: verifiedUserId,  });  const { check } = await indiana.checkEntitlement({    customerId: customer.id,    requirement: {      internal_feature_id: process.env.INDIANA_FEATURE_ID!,      quantity: "1",      properties: {},    },  });  if (!check.allowed) return { allowed: false as const };   try {    const { receipts } = await indiana.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 IndianaError) console.error(error.code, error.recovery, error.requestId);    throw error;  }}
按领域划分的服务端方法
领域方法
Customer、访客与会话getOrCreateCustomer, getCustomer, listCustomers, updateCustomer, createCustomerSession, renewCustomerSession, 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
发票、退款与计费listInvoiceTemplates, previewInvoice, createInvoice, manageInvoice, readInvoiceOperation, listInvoices, getInvoice, previewRefund, refund, readRefund, manageBillingLimits, readBillingInvoice
优惠券、奖励与推荐grantOffer, recordCouponRedemption
Feature、求值与事件getFeatures, evaluateFeatures, trackEvents
原生购买restoreNativePurchase
AI 定价readAiPricing

按领域划分的服务端方法

  • Customer、访客与会话

    方法
    getOrCreateCustomer, getCustomer, listCustomers, updateCustomer, createCustomerSession, renewCustomerSession, 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
  • 发票、退款与计费

    方法
    listInvoiceTemplates, previewInvoice, createInvoice, manageInvoice, readInvoiceOperation, listInvoices, getInvoice, previewRefund, refund, readRefund, manageBillingLimits, readBillingInvoice
  • 优惠券、奖励与推荐

    方法
    grantOffer, recordCouponRedemption
  • Feature、求值与事件

    方法
    getFeatures, evaluateFeatures, trackEvents
  • 原生购买

    方法
    restoreNativePurchase
  • AI 定价

    方法
    readAiPricing
客户端选项
选项说明
apiKeyServer Key(gg_sk_),保存在后端密钥系统。
scope{ projectId, environment }:App UUID 与 sandbox 或 live,必须与 Key 一致。
baseUrlAPI origin,默认 https://api.tinker.cash;不带 /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.tinker.cash;不带 /api/v1。
  • timeoutMs

    说明
    单次请求超时,默认 10000,最大 120000。
  • fetch

    说明
    注入自定义 fetch,用于代理或离线测试。

浏览器客户端

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

server/session.tsTypeScript
import { createIndianaServer } from "@tinkerlandai/indiana-sdk/server"; const indiana = createIndianaServer({  baseUrl: process.env.INDIANA_API_URL!,  apiKey: process.env.INDIANA_API_KEY!,  scope: { projectId: process.env.INDIANA_PROJECT_ID!, environment: "sandbox" },}); // Call only after your own login check succeeds.export async function issueCustomerToken(verifiedUserId: string) {  const { customer } = await indiana.getOrCreateCustomer({    externalUserId: verifiedUserId,  });  const { customerToken, expiresAt } = await indiana.createCustomerSession(customer.id);  return { customerToken, expiresAt };}
按领域划分的浏览器方法
领域方法
权益与商品展示checkEntitlement, resolveOffering, resolvePaywall, readHoldings
余额、用量与账本readLedger, readCreditStatement, quoteBalance
订阅与支付setupPayment, readPaymentSetup, previewAttach, attach, readSubscriptionOperation, previewUpdate, update, readSubscriptionUpdate
发票、退款与计费readBillingControls, prepareBillingAuthorization, confirmBillingAuthorization, setBillingCoupons, revokeBillingAuthorization, listBillingInvoices, readBillingInvoice
优惠券、奖励与推荐redeemCoupon, listOffers, claimCoupon, redeemReward, createReferralCode
Feature、求值与事件features, track, flush
原生购买restoreNativePurchase

按领域划分的浏览器方法

  • 权益与商品展示

    方法
    checkEntitlement, resolveOffering, resolvePaywall, readHoldings
  • 余额、用量与账本

    方法
    readLedger, readCreditStatement, quoteBalance
  • 订阅与支付

    方法
    setupPayment, readPaymentSetup, previewAttach, attach, readSubscriptionOperation, previewUpdate, update, readSubscriptionUpdate
  • 发票、退款与计费

    方法
    readBillingControls, prepareBillingAuthorization, confirmBillingAuthorization, setBillingCoupons, revokeBillingAuthorization, listBillingInvoices, readBillingInvoice
  • 优惠券、奖励与推荐

    方法
    redeemCoupon, listOffers, claimCoupon, redeemReward, createReferralCode
  • Feature、求值与事件

    方法
    features, track, flush
  • 原生购买

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

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, indiana.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, indiana.features()

    入口
    主入口
    用途
    Feature 求值与订阅
  • createPageExperiments

    入口
    /page
    用途
    URL 跳转实验
  • createVisualExperiments

    入口
    /visual
    用途
    可视化实验
  • createNativeReceiptClient

    入口
    /server
    用途
    后端提交原生商店凭证
  • createAiUsageMiddleware, createAiPricing

    入口
    /server
    用途
    AI SDK 用量计费中间件与定价
  • createOpenRouterUsageClient, trackOpenRouterUsage

    入口
    /openrouter
    用途
    OpenRouter 用量计费

相关:运行 Funnel·支付、订阅与账单·Feature、实验与事件

错误与重试

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

相关:错误码与恢复