# 支付、订阅与账单

报价与确认购买、Paywall、订阅变更、试用、退款、发票与原生购买。

更新于 2026-11-06

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

<a id="prepare"></a>

## 准备 Offering 与 Paywall

- 在同一 App/环境创建所需 Feature 和 Product，保存价格与权益，并使用保存后返回的 Product 标识和版本。Product 没有独立的发布动作。
- 从这些 Product 创建 Offering 并发布 Offering Version。Paywall 发布时固定一个已发布 Offering Version，选择需要展示的 Product、顺序和默认项。
- 保存 Paywall ID；新的 Offering 发布不会自动切换已有 Paywall 的固定版本。展示 Paywall 不要求创建 Funnel。
- 后端以已验证用户建立 Customer，使用具有 sessions:create、entitlements:read、billing:read、billing:write 的 Key 签发会话；为浏览器配置准确 Origin。需要支付时，为同一 App/环境配置 Stripe 连接，先在 Sandbox 验证。

- [Stripe 接入：权限、webhook 与激活](https://www.longplayai.com/zh-hans/docs/guides/stripe.md)
- [Customer 与会话](https://www.longplayai.com/zh-hans/docs/guides/customers.md#sessions)
- [CLI 资源配置与发布](https://www.longplayai.com/zh-hans/docs/cli.md)
- [商户准备报价与执行](https://www.longplayai.com/zh-hans/docs/guides/merchant-execution.md#prepared-terms)

<a id="product-versions"></a>

## Product 版本与已有客户

Product 保存后直接返回其标识和版本，没有额外的发布步骤。Offering 与 Paywall 仍各自发布独立版本。新建 Product 版本不会自动将已有客户的持有记录迁移到新版本。

版本选项位于 Product 更新写入操作的 `query` 对象。Console 仅提供“将本次修改保存为新版本”复选框，对应 `query.force_version`；`disable_version` 和 `all_versions` 仅能在写入操作的 `query` 中设置，没有对应的 Console 开关。

**更新方式与影响范围**

| 改动 | 行为 |
| --- | --- |
| 价格、权益、试用或 License | 默认更新时，如果所选版本有 `active`、`past_due`、`scheduled` 或 `paused` 状态的客户持有记录，变化的价格/权益条目或试用配置会创建新版本；在这些条件下，提交 `licenses` 也会创建新版本，即使其内容未变。只有 `expired` 持有记录时不触发这一条件，历史持有记录继续引用原有的价格与权益定义。 |
| 仅计费设置变化 | 只改 billing controls（计费设置）时，只要所选版本有上述状态的客户持有记录、其他比较字段都没变，默认更新也会创建新版本。 |
| `force_version` | 即使提交的字段值未变化，也可强制创建新版本；空更新或仅包含 `base_plan_id` 的更新不会创建新版本。不能与 `disable_version` 或 `all_versions` 同用。Product 信息和 metadata 仍遵守下面的原地更新规则。 |
| `disable_version` | 使用原地更新路径，可能修改已有客户使用的版本。 |
| `all_versions` | 将本次更新产生的变更原地应用到历史版本；不能与 `force_version` 或 `disable_version` 同用，也不支持跨所有版本更新 licenses。 |
| Product 信息与 metadata | 修改名称、描述、分组、默认标记、归档状态和 config 等信息时，会原地改写所选版本，部分同时创建新版本的更新也是如此。metadata 按 Product 标识在所有版本间共享。 |

创建客户或访客被识别为客户时，按资格分配默认 Product；默认 Product 可以包含无需绑卡的付费周期试用。已有客户再次登录不会重新分配。修改默认标记不会为已有客户重新初始化 Product。

<a id="purchase"></a>

## 发起一次购买

- 调用 `previewAttach` 生成报价和 `operationId`，此时不扣款。
- 调用 `attach` 确认；返回 `checkoutUrl` 时跳转到 Stripe 付款页。
- 跳转前保存 `operationId`。用户回来时页面已重新加载，先重新调用 `identify`，再用 `readSubscriptionOperation` 读取结果；`complete` 表示已支付并生效，`pending` 时稍后再读。

**purchase.ts**

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

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

export async function buy(customerToken: string, requestId: string) {
  longplay.identify(customerToken);
  const { quote } = await longplay.previewAttach({
    requestId, // persisted before the first attempt
    plans: [{ productVersionId: "<PRODUCT_VERSION_UUID>" }],
    provider: "stripe",
    currency: "USD",
  });
  const { operation } = await longplay.attach({ operationId: quote.operationId });
  // Checkout leaves this page, so keep the operation ID for the return page.
  sessionStorage.setItem("indiana-operation", operation.operationId);
  if (operation.checkoutUrl) window.location.assign(operation.checkoutUrl);
  return operation.operationId;
}

// The return from checkout is a new page load: identify again before reading.
export async function afterReturn(customerToken: string) {
  const operationId = sessionStorage.getItem("indiana-operation");
  if (!operationId) return null;
  longplay.identify(customerToken);
  const { operation } = await longplay.readSubscriptionOperation({ operationId });
  if (operation.status !== "pending") sessionStorage.removeItem("indiana-operation");
  return operation.status; // "pending" | "complete" | "cancelled" | "failed"
}
```

- 先在 Console 的支付连接中为该 App 和环境连接 Stripe；Sandbox 使用 Stripe 测试模式。
- 浏览器只能为当前用户购买；后端用 Server Key 调用时传入 `customerId`。
- 保存 `requestId`，重试时使用同一个值；不要根据跳转结果判断是否付款成功。
- 商户执行付款（`record_only`）时不需要 Stripe：报价返回商户准备的 `merchantTerms`；条款含 `requiredConsents` 时，确认 `attach`、`update` 或 `refund` 须提交匹配的 `merchantConfirmation`；付款由商户完成，操作在你用 `recordMerchantEvent` 上报结果后完成。见商户执行规范。

<a id="paywall"></a>

## 展示 Paywall

在 Console 发布 Paywall 后，用它的 ID 在页面中展示。用户购买后，SDK 自动完成报价与确认。

**paywall.ts**

```ts
import { createPaywallSession, showPaywall } from "@tinkerlandai/longplay-sdk";

const options = {
  baseUrl: "https://api.longplayai.com",
  scope: { projectId: "<APP_UUID>", environment: "sandbox" as const },
};

export function openPaywall(container: HTMLElement, customerToken: string) {
  return showPaywall(container, {
    start: () =>
      createPaywallSession(options, {
        paywallId: "<PAYWALL_UUID>",
        customerToken,
        commerce: { provider: "stripe", currency: "USD" },
        locale: "en",
      }),
    onCheckoutUrl: (url) => window.location.assign(url),
    onAccessGranted: (check) => console.log("access", check.allowed),
  });
}
```

- 在宿主页面提供真实容器并调用 openPaywall(container, customerToken)。保留返回的宿主句柄，在卸载或切换 Customer 时按 SDK 生命周期清理。
- 展示成功后核对实际选项来自固定的 Offering Version。购买完成需读取原商业操作及当前权益，不能把展示、关闭或返回页面当作付款成功。

**接入排错**

| 问题 | 检查 |
| --- | --- |
| 401 / 403 | 会话有效期、来源、Key 权限及 App/环境是否一致。 |
| Paywall 无法读取或选项不符 | 发布状态、Paywall ID、固定 Offering Version 和显示子集。 |
| 购买 pending 或请求超时 | 保留原 operationId / requestId 并查询原结果；按返回错误恢复，不创建重复购买。 |

- [产品概览：Paywall](https://www.longplayai.com/zh-hans/paywalls)

<a id="subscriptions"></a>

## 变更订阅、试用与退款

**更换套餐: app/change-plan.ts**

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

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

export async function changePlan(customerToken: string, requestId: string, productVersionId: string) {
  longplay.identify(customerToken);
  const { holdings } = await longplay.readHoldings();
  const membership = holdings.memberships[0];
  if (!membership) throw new Error("No membership to change");

  // 1. Quote the change; nothing is charged yet.
  const { quote } = await longplay.previewUpdate({
    requestId, // persisted before the first attempt
    membershipId: membership.id,
    timing: "immediate",
    change: { type: "plan", productVersionId },
  });

  // 2. After the user accepts the quote, confirm it.
  const { operation } = await longplay.update({ operationId: quote.operationId });
  return operation;
}
```

**退款: server/refund.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" },
});

export async function refundInvoice(customerId: string, invoiceId: string, requestId: string) {
  // 1. Quote a full refund that also revokes access; nothing is refunded yet.
  const { quote } = await longplay.previewRefund({
    customerId,
    requestId,
    invoiceId,
    mode: "full",
    entitlementAction: "revoke",
  });

  // 2. Confirm the quoted refund, then read its result.
  await longplay.refund({ customerId, operationId: quote.operationId });
  const { operation } = await longplay.readRefund({ customerId, operationId: quote.operationId });
  return operation;
}
```

**常见任务**

| 任务 | 方法 | 说明 |
| --- | --- | --- |
| 升级、降级或取消 | `previewUpdate` → `update` → `readSubscriptionUpdate` | `timing` 选择立即、续订时或在商店中生效。 |
| 保存付款方式 | `setupPayment` → `readPaymentSetup` | 不扣款。 |
| 开始、延长或结束试用 | `manageSubscriptionTrial`, `readSubscriptionTrial` | 后端调用。 |
| 退款 | `previewRefund` → `refund` → `readRefund` | 全额或部分；可选择是否撤销权益。 |
| 查询订阅与购买 | `listSubscriptions`, `listPurchases`, `verifySubscriptions` | 后端调用。 |
| 处理订阅冲突 | `listSubscriptionConflicts`, `retrySubscriptionConflict` | 后端调用。 |

- [产品概览：订阅管理](https://www.longplayai.com/zh-hans/subscriptions)

<a id="auto-topup"></a>

## 开启自动充值

余额低于 `threshold` 时自动购买，使用用户已保存的付款方式。必须先向用户展示 `prepared.terms`，用户同意后再确认。

**auto-topup.ts**

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

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

type UUID = ReturnType<typeof crypto.randomUUID>;

export async function prepareAutoTopup(customerToken: string, requestId: UUID) {
  longplay.identify(customerToken);
  const { prepared } = await longplay.prepareBillingAuthorization({
    requestId,
    kind: "auto_topup",
    productVersionId: "<CREDIT_PACK_VERSION_UUID>",
    internal_feature_id: "<CREDIT_FEATURE_UUID>",
    currency: "USD",
    threshold: "100",
    quantity: "1",
  });
  return prepared; // show prepared.terms to the Customer
}

// Call only after the Customer explicitly accepts the displayed terms.
export async function acceptAutoTopup(authorizationId: string) {
  return longplay.confirmBillingAuthorization({ authorizationId, accepted: true });
}
```

<a id="invoices"></a>

## 发票与用量上限

**常见任务**

| 任务 | 方法 | 调用方 |
| --- | --- | --- |
| 创建与管理发票 | `previewInvoice`, `createInvoice`, `manageInvoice`, `readInvoiceOperation` | 后端 |
| 查询发票 | `listInvoiceTemplates`, `listInvoices`, `getInvoice` | 后端 |
| 设置用量上限与提醒 | `manageBillingLimits` | 后端 |
| 用户查看自己的账单 | `listBillingInvoices`, `readBillingInvoice`, `readBillingControls` | 浏览器 |
| 用户为会员选择优惠 | `setBillingCoupons` | 浏览器 |

<a id="native"></a>

## 原生 App 购买

- 调用 `previewAttach`（`provider` 为 `apple` 或 `google`）取得购买意图。
- 在 App 中完成 App Store 或 Google Play 支付。
- 把 Apple `signedTransaction` 或 Google `purchaseToken` 提交给 `restoreNativePurchase`，验证后权益生效。
- 恢复购买时调用同一接口的 `read` 分支。

- [iOS 与 Android](https://www.longplayai.com/zh-hans/docs/sdk/native.md)

<a id="operations"></a>

## 相关接口

- **订阅与支付 (20)**:  [setupPayment](https://www.longplayai.com/zh-hans/docs/api/setup-payment.md); [readPaymentSetup](https://www.longplayai.com/zh-hans/docs/api/read-payment-setup.md); [verifySubscriptions](https://www.longplayai.com/zh-hans/docs/api/verify-subscriptions.md); [previewAttach](https://www.longplayai.com/zh-hans/docs/api/preview-attach.md); [attach](https://www.longplayai.com/zh-hans/docs/api/attach.md); [readSubscriptionOperation](https://www.longplayai.com/zh-hans/docs/api/read-subscription-operation.md); [previewUpdate](https://www.longplayai.com/zh-hans/docs/api/preview-update.md); [update](https://www.longplayai.com/zh-hans/docs/api/update.md); [readSubscriptionUpdate](https://www.longplayai.com/zh-hans/docs/api/read-subscription-update.md); [listSubscriptions](https://www.longplayai.com/zh-hans/docs/api/list-subscriptions.md); [listPurchases](https://www.longplayai.com/zh-hans/docs/api/list-purchases.md); [listSubscriptionConflicts](https://www.longplayai.com/zh-hans/docs/api/list-subscription-conflicts.md); [retrySubscriptionConflict](https://www.longplayai.com/zh-hans/docs/api/retry-subscription-conflict.md); [manageSubscriptionTrial](https://www.longplayai.com/zh-hans/docs/api/manage-subscription-trial.md); [readSubscriptionTrial](https://www.longplayai.com/zh-hans/docs/api/read-subscription-trial.md); [previewSubscriptionBatch](https://www.longplayai.com/zh-hans/docs/api/preview-subscription-batch.md); [confirmSubscriptionBatch](https://www.longplayai.com/zh-hans/docs/api/confirm-subscription-batch.md); [readSubscriptionBatch](https://www.longplayai.com/zh-hans/docs/api/read-subscription-batch.md); [abandonSubscriptionBatch](https://www.longplayai.com/zh-hans/docs/api/abandon-subscription-batch.md); [recordMerchantEvent](https://www.longplayai.com/zh-hans/docs/api/record-merchant-event.md)
- **发票、退款与计费 (20)**:  [listInvoiceTemplates](https://www.longplayai.com/zh-hans/docs/api/list-invoice-templates.md); [previewInvoice](https://www.longplayai.com/zh-hans/docs/api/preview-invoice.md); [createInvoice](https://www.longplayai.com/zh-hans/docs/api/create-invoice.md); [manageInvoice](https://www.longplayai.com/zh-hans/docs/api/manage-invoice.md); [readInvoiceOperation](https://www.longplayai.com/zh-hans/docs/api/read-invoice-operation.md); [listInvoices](https://www.longplayai.com/zh-hans/docs/api/list-invoices.md); [getInvoice](https://www.longplayai.com/zh-hans/docs/api/get-invoice.md); [previewRefund](https://www.longplayai.com/zh-hans/docs/api/preview-refund.md); [refund](https://www.longplayai.com/zh-hans/docs/api/refund.md); [readRefund](https://www.longplayai.com/zh-hans/docs/api/read-refund.md); [readBillingControls](https://www.longplayai.com/zh-hans/docs/api/read-billing-controls.md); [prepareBillingAuthorization](https://www.longplayai.com/zh-hans/docs/api/prepare-billing-authorization.md); [confirmBillingAuthorization](https://www.longplayai.com/zh-hans/docs/api/confirm-billing-authorization.md); [setBillingCoupons](https://www.longplayai.com/zh-hans/docs/api/set-billing-coupons.md); [revokeBillingAuthorization](https://www.longplayai.com/zh-hans/docs/api/revoke-billing-authorization.md); [listBillingInvoices](https://www.longplayai.com/zh-hans/docs/api/list-billing-invoices.md); [manageBillingLimits](https://www.longplayai.com/zh-hans/docs/api/manage-billing-limits.md); [readBillingInvoice](https://www.longplayai.com/zh-hans/docs/api/read-billing-invoice.md); [prepareBillingAdjustment](https://www.longplayai.com/zh-hans/docs/api/prepare-billing-adjustment.md); [confirmBillingAdjustment](https://www.longplayai.com/zh-hans/docs/api/confirm-billing-adjustment.md)
- **原生购买 (1)**:  [restoreNativePurchase](https://www.longplayai.com/zh-hans/docs/api/restore-native-purchase.md)

- [路径、凭据与权限见全部接口](https://www.longplayai.com/zh-hans/docs/api/operations.md#commerce)
