# Payments, subscriptions and billing

Quote and confirm purchases, Paywalls, subscription changes, trials, refunds, invoices and native purchases.

Last updated: 2026-11-06

[Web version](https://www.longplayai.com/docs/guides/commerce)

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

## Prepare an Offering and Paywall

- Create the required Features and Products in the same App/environment, save their prices and entitlements, and use the returned Product identity and version. Products have no separate publish action.
- Create an Offering from those Products and publish an Offering Version. Publish a Paywall pinned to one published Offering Version, selecting its displayed Products, order and default choice.
- Save the Paywall ID. Publishing a new Offering does not update an existing Paywall's version pin. A Paywall does not require a Funnel.
- Identify the authenticated user as a Customer on your backend and issue a session with a Key holding sessions:create, entitlements:read, billing:read and billing:write. Configure the exact browser Origin. For payments, configure Stripe for that same App/environment and validate in Sandbox first.

- [Connect Stripe: permissions, webhook and activation](https://www.longplayai.com/docs/guides/stripe.md)
- [Customers and sessions](https://www.longplayai.com/docs/guides/customers.md#sessions)
- [CLI resource configuration and publication](https://www.longplayai.com/docs/cli.md)
- [Merchant quote preparation and execution](https://www.longplayai.com/docs/guides/merchant-execution.md#prepared-terms)

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

## Product versions and existing customers

Saving a Product returns its identity and version without an additional publication step. Offerings and Paywalls still publish independent versions. Creating a Product version does not automatically migrate existing customer holdings to it.

Version options belong to the Product update write operation's `query` object. Console exposes only the “Save these changes as a new version” checkbox, which sets `query.force_version`; `disable_version` and `all_versions` can only be set in the write operation's `query` object and have no Console controls.

**Update behavior and affected versions**

| Change | Behavior |
| --- | --- |
| Prices, entitlements, trials or licenses | With the default update options, changed price/entitlement items or trial terms create a new version when the selected version has `active`, `past_due`, `scheduled` or `paused` customer holdings. Supplying `licenses` also creates a new version under these conditions, even if unchanged. Expired-only holdings do not meet this condition. Historical holdings continue to reference their original price and entitlement definitions. |
| Billing-controls-only changes | If only billing controls change and the selected version has customer holdings in the states above, the default update still creates a new version. |
| `force_version` | Creates a new version even when the supplied field values are unchanged, except for an empty update or an update containing only `base_plan_id`. It cannot be combined with `disable_version` or `all_versions`. Product details and metadata still follow the in-place rules below. |
| `disable_version` | Uses the in-place update path and can change the version used by existing customers. |
| `all_versions` | Applies the update's changes in place to historical versions. It cannot be combined with `force_version` or `disable_version` and does not support updating licenses across all versions. |
| Product details and metadata | Changes to details such as name, description, group, default flag, archive status and config apply to the selected version in place, including some updates that also create a new version. Metadata is shared across all versions of the Product identity. |

Default Products are assigned by eligibility when a Customer is created or a Guest is identified; a default can include a no-card trial of a paid recurring Product. Default Products are not reassigned when an existing Customer signs in again. Changing a default flag does not reinitialize Products for existing Customers.

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

## Start a purchase

- Call `previewAttach` to get a quote and an `operationId`; nothing is charged yet.
- Call `attach` to confirm; when it returns a `checkoutUrl`, redirect to the Stripe payment page.
- Save the `operationId` before redirecting. The return is a new page load, so call `identify` again, then `readSubscriptionOperation`; `complete` means paid and active, and `pending` means read again later.

**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"
}
```

- First connect Stripe for the App and environment under Payment connections in Console; Sandbox uses Stripe test mode.
- A browser buys only for the current user; a backend using a Server Key passes `customerId`.
- Save the `requestId` and reuse it on retries; never infer payment from the redirect.
- When the merchant executes payments (`record_only`), Stripe is not needed: the quote returns the merchant-prepared `merchantTerms`; when those terms include `requiredConsents`, confirming `attach`, `update` or `refund` requires the matching `merchantConfirmation`. The merchant takes payment, and the operation completes after you report the result with `recordMerchantEvent`. See the merchant execution specification.

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

## Show a Paywall

After publishing a Paywall in Console, show it by ID. When the user buys, the SDK completes the quote and confirmation.

**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),
  });
}
```

- Provide a real container and call openPaywall(container, customerToken). Keep the returned host handle and clean it up using the SDK lifecycle on unmount or Customer changes.
- After display, verify that the choices come from the pinned Offering Version. Confirm a purchase from the original commercial operation and current entitlements; display, dismissal or a return page is not payment confirmation.

**Integration troubleshooting**

| Problem | Check |
| --- | --- |
| 401 / 403 | Session expiry, Origin, Key permissions and matching App/environment. |
| Paywall missing or unexpected choices | Publication state, Paywall ID, pinned Offering Version and displayed subset. |
| Purchase pending or timed out | Keep the original operationId/requestId and read its result; follow error recovery without creating another purchase. |

- [Product overview: paywalls](https://www.longplayai.com/paywalls)

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

## Change subscriptions, trials and refunds

**Change plan: 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;
}
```

**Refund: 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;
}
```

**Common tasks**

| Task | Methods | Notes |
| --- | --- | --- |
| Upgrade, downgrade or cancel | `previewUpdate` → `update` → `readSubscriptionUpdate` | `timing` applies the change immediately, at renewal or in the store. |
| Save a payment method | `setupPayment` → `readPaymentSetup` | No charge. |
| Start, extend or end a trial | `manageSubscriptionTrial`, `readSubscriptionTrial` | Backend only. |
| Refund | `previewRefund` → `refund` → `readRefund` | Full or partial; optionally revokes access. |
| List subscriptions and purchases | `listSubscriptions`, `listPurchases`, `verifySubscriptions` | Backend only. |
| Resolve subscription conflicts | `listSubscriptionConflicts`, `retrySubscriptionConflict` | Backend only. |

- [Product overview: subscription management](https://www.longplayai.com/subscriptions)

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

## Turn on auto top-up

When the balance falls below `threshold`, Longplay buys more with the user's saved payment method. Show `prepared.terms` to the user and confirm only after they accept.

**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>

## Invoices and usage limits

**Common tasks**

| Task | Methods | Caller |
| --- | --- | --- |
| Create and manage invoices | `previewInvoice`, `createInvoice`, `manageInvoice`, `readInvoiceOperation` | Backend |
| Read invoices | `listInvoiceTemplates`, `listInvoices`, `getInvoice` | Backend |
| Set usage limits and alerts | `manageBillingLimits` | Backend |
| Let users view their invoices | `listBillingInvoices`, `readBillingInvoice`, `readBillingControls` | Browser |
| Let users apply offers to a membership | `setBillingCoupons` | Browser |

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

## Native app purchases

- Call `previewAttach` with `provider` set to `apple` or `google` to get a purchase intent.
- Complete the App Store or Google Play payment in the app.
- Send the Apple `signedTransaction` or Google `purchaseToken` to `restoreNativePurchase`; access is granted after verification.
- To restore purchases, call its `read` branch.

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

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

## Related operations

- **Subscriptions and payments (20)**:  [setupPayment](https://www.longplayai.com/docs/api/setup-payment.md); [readPaymentSetup](https://www.longplayai.com/docs/api/read-payment-setup.md); [verifySubscriptions](https://www.longplayai.com/docs/api/verify-subscriptions.md); [previewAttach](https://www.longplayai.com/docs/api/preview-attach.md); [attach](https://www.longplayai.com/docs/api/attach.md); [readSubscriptionOperation](https://www.longplayai.com/docs/api/read-subscription-operation.md); [previewUpdate](https://www.longplayai.com/docs/api/preview-update.md); [update](https://www.longplayai.com/docs/api/update.md); [readSubscriptionUpdate](https://www.longplayai.com/docs/api/read-subscription-update.md); [listSubscriptions](https://www.longplayai.com/docs/api/list-subscriptions.md); [listPurchases](https://www.longplayai.com/docs/api/list-purchases.md); [listSubscriptionConflicts](https://www.longplayai.com/docs/api/list-subscription-conflicts.md); [retrySubscriptionConflict](https://www.longplayai.com/docs/api/retry-subscription-conflict.md); [manageSubscriptionTrial](https://www.longplayai.com/docs/api/manage-subscription-trial.md); [readSubscriptionTrial](https://www.longplayai.com/docs/api/read-subscription-trial.md); [previewSubscriptionBatch](https://www.longplayai.com/docs/api/preview-subscription-batch.md); [confirmSubscriptionBatch](https://www.longplayai.com/docs/api/confirm-subscription-batch.md); [readSubscriptionBatch](https://www.longplayai.com/docs/api/read-subscription-batch.md); [abandonSubscriptionBatch](https://www.longplayai.com/docs/api/abandon-subscription-batch.md); [recordMerchantEvent](https://www.longplayai.com/docs/api/record-merchant-event.md)
- **Invoices, refunds and billing (20)**:  [listInvoiceTemplates](https://www.longplayai.com/docs/api/list-invoice-templates.md); [previewInvoice](https://www.longplayai.com/docs/api/preview-invoice.md); [createInvoice](https://www.longplayai.com/docs/api/create-invoice.md); [manageInvoice](https://www.longplayai.com/docs/api/manage-invoice.md); [readInvoiceOperation](https://www.longplayai.com/docs/api/read-invoice-operation.md); [listInvoices](https://www.longplayai.com/docs/api/list-invoices.md); [getInvoice](https://www.longplayai.com/docs/api/get-invoice.md); [previewRefund](https://www.longplayai.com/docs/api/preview-refund.md); [refund](https://www.longplayai.com/docs/api/refund.md); [readRefund](https://www.longplayai.com/docs/api/read-refund.md); [readBillingControls](https://www.longplayai.com/docs/api/read-billing-controls.md); [prepareBillingAuthorization](https://www.longplayai.com/docs/api/prepare-billing-authorization.md); [confirmBillingAuthorization](https://www.longplayai.com/docs/api/confirm-billing-authorization.md); [setBillingCoupons](https://www.longplayai.com/docs/api/set-billing-coupons.md); [revokeBillingAuthorization](https://www.longplayai.com/docs/api/revoke-billing-authorization.md); [listBillingInvoices](https://www.longplayai.com/docs/api/list-billing-invoices.md); [manageBillingLimits](https://www.longplayai.com/docs/api/manage-billing-limits.md); [readBillingInvoice](https://www.longplayai.com/docs/api/read-billing-invoice.md); [prepareBillingAdjustment](https://www.longplayai.com/docs/api/prepare-billing-adjustment.md); [confirmBillingAdjustment](https://www.longplayai.com/docs/api/confirm-billing-adjustment.md)
- **Native purchases (1)**:  [restoreNativePurchase](https://www.longplayai.com/docs/api/restore-native-purchase.md)

- [Paths, credentials and scopes in All operations](https://www.longplayai.com/docs/api/operations.md#commerce)
