20 min read

Stripe Client Library Reference

Complete reference for the iaptic-js client library — the IapticStripe adapter that drives Stripe Checkout, purchase lookup and subscription management from a web application.

This page documents [email protected]. For the REST endpoints behind these calls, see the API reference.

Upgrading from 1.0.x to 2.0.0 — 2.0.0 makes the type declarations match what the server sends, so code that cast paymentMode, product.type or renewalIntent to compare against the server's values no longer needs to. The calls and what they send to the server are unchanged.

  • New values: PricingPhase.paymentMode adds 'UpFront' and 'FreeTrial'; Offer.offerType adds 'Introductory' (other Iaptic platforms use these three; the Stripe endpoint does not send them); ProductType adds 'non consumable', 'non renewing subscription', 'application' and 'product'; Purchase.renewalIntent adds 'Lapse'.
  • Deprecated: 'PayUpFront' and 'Cancel' are never sent by the server. They still compile and will be removed in the next major version. Compare against the new values instead.
  • 'non_consumable' is deprecated too, but it can still arrive. Iaptic never produces it, but a Stripe product whose metadata sets product_type: 'non_consumable' is passed through as-is. Fix the metadata, as the product metadata page explains.
  • Now optional: PricingPhase.currency, billingPeriod, recurrenceMode; Purchase.purchaseDate, lastRenewalDate, expirationDate, renewalIntent, isTrialPeriod, amountMicros, currency; PlanChange.purchaseId. With strictNullChecks on (implied by strict), code that reads them as always present gets a compile error: check them before use (a one-time purchase has no expirationDate).
  • Exhaustive switch statements: paymentMode, offerType and product.type have more values, and renewalIntent is now optional, so a switch that covered every 1.0.x value no longer covers them all. With strictNullChecks on, a function with an explicit return type that returns from every case now fails with TS2366: Function lacks ending return statement. Add a default branch.
  • Bundlers: package.json now declares "sideEffects": false. If you import the package only to get the IapticJS global (import 'iaptic-js'), a bundler may drop that import, and the global is never set. Import IapticJS by name instead. The <script> tag is not affected.
  • Node.js 20 or later to build the library from source (engines.node >= 20). Apps that use the published package or the CDN bundle are not affected.

Installation

npm

npm install --save [email protected]
import { IapticJS } from 'iaptic-js';

CDN

<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/iaptic-js.js"></script>

The UMD bundle exposes the IapticJS global. An ES module build is published alongside it:

<script type="module">
  import { IapticJS } from 'https://cdn.jsdelivr.net/npm/[email protected]/dist/iaptic-js.esm.js';
</script>

Stripe.js is not required: order() and redirectToCustomerPortal() redirect the browser to a Stripe-hosted page.

Initialization

const iaptic = IapticJS.createAdapter({
  type: 'stripe',
  appName: 'com.example.app',
  apiKey: 'your_iaptic_public_key'
});
Field Type Description
type 'stripe' Adapter to instantiate. 'stripe' is the only supported value.
appName string Your application name, as configured on iaptic.com.
apiKey string Your Iaptic public API key, from your settings.

createAdapter() throws an Error when appName or apiKey is missing, or when type is not 'stripe'.

The IapticJS object

Member Description
IapticJS.createAdapter(config) Creates an IapticStripe instance.
IapticJS.IapticStripe The adapter class, for instanceof checks or direct construction.
IapticJS.Utils Utility functions (see Utilities).
IapticJS.version Version of the loaded library (e.g. '2.0.0').

Products

getProducts()

getProducts(): Promise<Product[]>

Returns the products and prices configured in Stripe. The result is cached in local storage; call refreshProducts() to re-fetch from the server.

const products = await iaptic.getProducts();

for (const product of products) {
  for (const offer of product.offers) {
    console.log(product.title, offer.id, offer.pricingPhases);
  }
}

refreshProducts()

refreshProducts(): Promise<Product[]>

Re-fetches the product list from the server and updates the cache. Responses cached less than one minute ago are reused regardless.

Product

interface Product {
  type: 'subscription' | 'consumable' | 'non consumable' | 'paid subscription'
      | 'non renewing subscription' | 'application' | 'product'
      | 'non_consumable';             // deprecated, see below
  id: string;                        // "prod_xyz" (raw Stripe id, unlike Offer.id and Purchase.productId)
  title: string;
  description?: string;
  offers: Offer[];
  metadata?: Record<string, any>;
  platform?: string;
}

Note the spelling of 'non consumable', with a space. 'non_consumable' is deprecated, still compiles, and will be removed in the next major version. Iaptic never produces it, but the server passes a Stripe product's product_type metadata through as-is, so a product whose metadata says 'non_consumable' arrives with that type. Fix the metadata, as the product metadata page explains.

Offer

interface Offer {
  id: string;                        // "stripe:prod_xyz#price_xyz"
  platform: string;                  // 'stripe'
  offerType: 'Subscription' | 'Default' | 'Introductory';
  pricingPhases: PricingPhase[];
}

The Stripe server sends 'Subscription' for a recurring price and 'Default' for a one-time price. 'Introductory' comes from other Iaptic platforms and is not sent by the Stripe endpoint.

PricingPhase

interface PricingPhase {
  priceMicros: number;               // 1/1,000,000 of the currency unit
  currency?: string;                 // ISO 4217, e.g. 'USD'
  billingPeriod?: string;            // ISO 8601 duration, e.g. 'P1M', 'P1Y', 'P7D'; absent for one-time purchases
  recurrenceMode?: 'INFINITE_RECURRING' | 'NON_RECURRING' | 'FINITE_RECURRING';
  paymentMode: 'PayAsYouGo' | 'UpFront' | 'FreeTrial'
      | 'PayUpFront';                // deprecated, never sent
}

The Stripe server sends 'PayAsYouGo'. 'UpFront' and 'FreeTrial' are in the library's type because other Iaptic platforms use them, but the Stripe endpoint does not send them. 'PayUpFront' is deprecated: it still compiles and will be removed in the next major version.

Checkout

order(params)

order(params: Order): Promise<void>

Creates a Stripe Checkout session and redirects the browser to it (window.location.href). The promise resolves once the redirect has been initiated — it does not resolve a purchase; read the resulting purchase with getPurchases() after the customer returns to successUrl.

await iaptic.order({
  offerId: 'stripe:prod_xyz#price_xyz',
  applicationUsername: 'user123',
  successUrl: 'https://example.com/#success',
  cancelUrl: 'https://example.com/#cancel'
});

The access token returned by the checkout session is stored automatically, so the purchase can be read on the success page without passing it explicitly.

Order

interface Order {
  offerId: string;                   // "stripe:prod_xyz#price_xyz"
  applicationUsername: string;       // Your user identifier
  successUrl: string;
  cancelUrl: string;
  accessToken?: string;              // Reuse an existing Stripe customer, if known
}

Subscription Management

getPurchases(accessToken?)

getPurchases(accessToken?: string): Promise<Purchase[]>

Returns the customer's verified purchases. When the access token is omitted, the stored token is used.

const purchases = await iaptic.getPurchases();

const active = purchases.filter(
  (p) => p.renewalIntent === 'Renew'
);

Two details worth knowing:

  • Without a token, this resolves to an empty array rather than throwing. A visitor who never purchased simply has no purchases.
  • Expiring purchases are re-verified automatically, each time this method runs. The package's RefreshScheduler class (a named export, not a member of the IapticJS global) schedules a refresh shortly before and after every expirationDate it sees, so a purchase stays current across a renewal or cancellation on the next page load. A refresh more than ~24 days out is skipped rather than armed, which is why the schedule is rebuilt on each call: a purchase expiring next month is picked up by a later getPurchases(), not by the checkout that created it.

redirectToCustomerPortal(params)

redirectToCustomerPortal(params: {
  returnUrl?: string;
  accessToken?: string;
}): Promise<void>

Creates a Stripe Customer Portal session and redirects the browser to it. returnUrl defaults to the current page; accessToken defaults to the stored token. Throws No access token available when neither is present.

await iaptic.redirectToCustomerPortal({
  returnUrl: 'https://example.com/account'
});

changePlan(planChange)

changePlan(planChange: PlanChange): Promise<Purchase>

Switches a subscription to a different offer (upgrade, downgrade or interval change) without going through the Customer Portal, and resolves the updated purchase. When purchaseId is omitted, the server picks the customer's active or trialing subscription, then an incomplete one, then the most recent one. If the subscription it picks has ended (canceled, unpaid or expired), a new subscription is created on the requested offer. accessToken defaults to the stored token; throws No access token available when neither is present.

const purchase = await iaptic.changePlan({
  purchaseId: 'stripe:sub_xyz',
  offerId: 'stripe:prod_xyz#price_xyz'
});

console.log(purchase.expirationDate);

PlanChange

interface PlanChange {
  purchaseId?: string;               // "stripe:sub_xyz"; when omitted, see changePlan() above
  offerId: string;                   // "stripe:prod_xyz#price_xyz"
  accessToken?: string;
}

Purchase

interface Purchase {
  purchaseId: string;                // "stripe:sub_xyz"
  transactionId: string;             // e.g. "stripe:pi_xyz"
  productId: string;                 // "stripe:prod_xyz"
  platform: 'stripe';
  purchaseDate?: string;             // ISO 8601
  lastRenewalDate?: string;          // ISO 8601
  expirationDate?: string;           // ISO 8601; absent for one-time purchases
  renewalIntent?: 'Lapse' | 'Renew'
      | 'Cancel';                    // deprecated, never sent
  isTrialPeriod?: boolean;
  amountMicros?: number;
  currency?: string;
}

These values come from the API, not from the library: renewalIntent is 'Lapse' when the subscription is set to cancel at the end of the current period and 'Renew' otherwise, and transactionId names the Stripe object behind the latest renewal — stripe:pi_… for a paid invoice, stripe:in_… when no payment intent is attached, or stripe:sub_… when the subscription carries neither. The optional fields can be absent, so check them before use. 'Cancel' is deprecated: it still compiles and will be removed in the next major version. Use 'Lapse'.

Access Tokens

Access tokens identify the customer, and are what the library passes to the API on their behalf. They are stored in localStorage under iaptic_access_token. A token is generated during checkout and re-issued by the server while reading purchases, when the stored receipt needs refreshing.

getAccessToken()

getAccessToken(): string | undefined

Returns the stored access token, or undefined when the visitor has none.

const accessToken = iaptic.getAccessToken();

if (!accessToken) {
  // Show the pricing page: this visitor has never checked out
}

onAccessTokenChange(callback)

onAccessTokenChange(callback: (accessToken: string) => void): void

Registers a callback invoked whenever a token is issued or rotated, so your own backend can be kept in sync.

iaptic.onAccessTokenChange((accessToken) => {
  // Persist the new token alongside the signed-in user
});

Tokens can also be passed explicitly to getPurchases(), redirectToCustomerPortal() and changePlan().

Clearing Stored Data

clearStoredData()

clearStoredData(): void

Removes the stored access token and the cached product list, and drops the list of scheduled purchase refreshes. Call it on sign-out.

Timers already armed for a purchase still fire; with the token gone they find nothing to verify.

Utilities

The formatting helpers are static members of IapticJS.Utils, not methods on the adapter instance.

Utils.formatCurrency(amountMicros, currency)

Utils.formatCurrency(amountMicros: number, currency: string): string

Utils.formatCurrency(1990000, 'USD');  // "$1.99"
Utils.formatCurrency(1000000, 'EUR');  // "€1"

Formats an amount expressed in micros (1/1,000,000 of the currency unit) using the browser's locale, falling back to a built-in symbol table for common currencies.

Purchase.amountMicros, Purchase.currency and PricingPhase.billingPeriod are optional, so with strictNullChecks on, passing them straight to these helpers fails with TS2345. Check them first:

if (purchase.amountMicros !== undefined && purchase.currency) {
  label = Utils.formatCurrency(purchase.amountMicros, purchase.currency);
}

Utils.formatBillingPeriodEN(period)

Utils.formatBillingPeriodEN(period: string): string

Utils.formatBillingPeriodEN('P1M');  // "Monthly"
Utils.formatBillingPeriodEN('P3M');  // "Every 3 months"
Utils.formatBillingPeriodEN('P1Y');  // "Yearly"

Turns an ISO 8601 duration into a plain-English billing period.

It reads date components only — the first P<n> followed by a unit of Y, M, W or D. Counts are not normalised, so P12M gives "Every 12 months", not "Yearly"; P1W gives "Weekly" and P7D gives "Every 7 days".

A duration the pattern does not match is returned unchanged, so a time-only duration such as PT24H comes back as "PT24H". A time part after the date part is ignored: P1MT2H formats as "Monthly".

Error Handling

Failed calls reject with a plain Error. There is no typed error class and no error-code constant on the client; branch on the call you made, not on a code.

Where the message comes from depends on the method:

  • getPurchases(), redirectToCustomerPortal() and changePlan() propagate the API's message when the response is not OK — the same {status, code, message} envelope documented in the error codes reference — and fall back to their own text when the API sent none.
  • order(), getProducts() and refreshProducts() never read the error body. They reject with a fixed message: Failed to create checkout session or Invalid checkout session response for order(), Failed to fetch prices from Iaptic or Invalid response from Iaptic for the product calls. A 403 Invalid access key from the API therefore surfaces here as Failed to create checkout session.
  • redirectToCustomerPortal() and changePlan() also throw No access token available before issuing any request when the visitor is not identified.
try {
  await iaptic.order({
    offerId: 'stripe:prod_xyz#price_xyz',
    applicationUsername: 'user123',
    successUrl: 'https://example.com/#success',
    cancelUrl: 'https://example.com/#cancel'
  });
} catch (error) {
  console.error('Checkout failed:', error);
  // error.message is one of the library's own fixed strings here, not the
  // API's message: 'Failed to create checkout session' when the request
  // failed, 'Invalid checkout session response' when the payload was unusable.
}