Skip to content
Longplay
Docs
Browse docs / Payments, subscriptions and billing

Payments, subscriptions and billing

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

Markdown
API v1Updated

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.

Related: Connect Stripe: permissions, webhook and activation·Customers and sessions·CLI resource configuration and publication·Merchant quote preparation and execution

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
ChangeBehavior
Prices, entitlements, trials or licensesWith 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 changesIf only billing controls change and the selected version has customer holdings in the states above, the default update still creates a new version.
force_versionCreates 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_versionUses the in-place update path and can change the version used by existing customers.
all_versionsApplies 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 metadataChanges 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.

Update behavior and affected versions

  • Prices, entitlements, trials or licenses

    Behavior
    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

    Behavior
    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

    Behavior
    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

    Behavior
    Uses the in-place update path and can change the version used by existing customers.
  • all_versions

    Behavior
    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

    Behavior
    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.

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.tsTypeScript
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.

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.tsTypeScript
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
ProblemCheck
401 / 403Session expiry, Origin, Key permissions and matching App/environment.
Paywall missing or unexpected choicesPublication state, Paywall ID, pinned Offering Version and displayed subset.
Purchase pending or timed outKeep the original operationId/requestId and read its result; follow error recovery without creating another purchase.

Integration troubleshooting

  • 401 / 403

    Check
    Session expiry, Origin, Key permissions and matching App/environment.
  • Paywall missing or unexpected choices

    Check
    Publication state, Paywall ID, pinned Offering Version and displayed subset.
  • Purchase pending or timed out

    Check
    Keep the original operationId/requestId and read its result; follow error recovery without creating another purchase.

Related: Product overview: paywalls

Change subscriptions, trials and refunds#

app/change-plan.tsTypeScript
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;}
Common tasks
TaskMethodsNotes
Upgrade, downgrade or cancelpreviewUpdate → update → readSubscriptionUpdatetiming applies the change immediately, at renewal or in the store.
Save a payment methodsetupPayment → readPaymentSetupNo charge.
Start, extend or end a trialmanageSubscriptionTrial, readSubscriptionTrialBackend only.
RefundpreviewRefund → refund → readRefundFull or partial; optionally revokes access.
List subscriptions and purchaseslistSubscriptions, listPurchases, verifySubscriptionsBackend only.
Resolve subscription conflictslistSubscriptionConflicts, retrySubscriptionConflictBackend only.

Common tasks

  • Upgrade, downgrade or cancel

    Methods
    previewUpdate → update → readSubscriptionUpdate
    Notes
    timing applies the change immediately, at renewal or in the store.
  • Save a payment method

    Methods
    setupPayment → readPaymentSetup
    Notes
    No charge.
  • Start, extend or end a trial

    Methods
    manageSubscriptionTrial, readSubscriptionTrial
    Notes
    Backend only.
  • Refund

    Methods
    previewRefund → refund → readRefund
    Notes
    Full or partial; optionally revokes access.
  • List subscriptions and purchases

    Methods
    listSubscriptions, listPurchases, verifySubscriptions
    Notes
    Backend only.
  • Resolve subscription conflicts

    Methods
    listSubscriptionConflicts, retrySubscriptionConflict
    Notes
    Backend only.

Related: Product overview: subscription management

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.tsTypeScript
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 });}

Invoices and usage limits#

Common tasks
TaskMethodsCaller
Create and manage invoicespreviewInvoice, createInvoice, manageInvoice, readInvoiceOperationBackend
Read invoiceslistInvoiceTemplates, listInvoices, getInvoiceBackend
Set usage limits and alertsmanageBillingLimitsBackend
Let users view their invoiceslistBillingInvoices, readBillingInvoice, readBillingControlsBrowser
Let users apply offers to a membershipsetBillingCouponsBrowser

Common tasks

  • Create and manage invoices

    Methods
    previewInvoice, createInvoice, manageInvoice, readInvoiceOperation
    Caller
    Backend
  • Read invoices

    Methods
    listInvoiceTemplates, listInvoices, getInvoice
    Caller
    Backend
  • Set usage limits and alerts

    Methods
    manageBillingLimits
    Caller
    Backend
  • Let users view their invoices

    Methods
    listBillingInvoices, readBillingInvoice, readBillingControls
    Caller
    Browser
  • Let users apply offers to a membership

    Methods
    setBillingCoupons
    Caller
    Browser

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.

Related: iOS and Android

Related operations#