API Reference
Commerce Kit singleton methods, PurchaseOutcome, consumable delivery, errors, and subscription helpers.
- Snapchat: not supported
- SPECS: fully supported
- Camera Kit Web: not supported
- Camera Kit Mobile: not supported
- SnapchatNot supported
- SPECSFully supported
- Camera Kit WebNot supported
- Camera Kit MobileNot supported
All methods are on the singleton returned by CommerceKit.getInstance(). Methods that need the commerce service connect on first use, so calling initialize() first is optional, but it is the best place to handle connection errors. Errors are CommerceKitError instances; see Errors.
At a Glance
| Member | Since | Purpose | Native Commerce.Client calls |
|---|---|---|---|
CommerceKit.getInstance() | 3.x | The shared instance. | None until first use. |
initialize() | New | Connect, restore purchases, finalize pending ones. | CommerceKitModule.createClient(), startConnection(), queryPurchase() per product type, acknowledgePurchase() |
getProductInfo(productId) | 3.x | Details of one product. | queryProductDetails(), once per product |
purchaseProduct(productId, offerId?) | 3.x; offerId is new | Buy a product and finalize the purchase. | launchPurchaseFlow(), the onPurchasesUpdated callback, queryPurchase(), acknowledgePurchase() |
registerConsumable(productId, deliver) | New | Deliver consumables before they are consumed. | None: it decides when CommerceKit calls acknowledgePurchase() |
isProductOwned(productId) | 3.x | Owned non-consumable or active subscription. | None: reads the last sync |
getPurchase(productId) | New | The purchase record: state, token, renewal. | None: reads the last sync |
checkPurchaseStatus(productId) | 3.x | Sync, then the purchase state. | Like refresh() |
refresh() | New | Sync and finalize pending purchases. | queryPurchase() per product type, acknowledgePurchase() |
onPurchasesChanged | New | Event fired when purchases change. | None |
client() | 3.x | The underlying client, for everything else. | Returns it |
initializeCatalog(productCatalog) | 3.x, deprecated | Same as initialize(); the products are ignored. | Like initialize() |
CommerceKit.getInstance(): CommerceKit
Returns the shared instance. Do not create commerce clients with CommerceKitModule.createClient() alongside it: a Lens can hold only one connection to the commerce service.
initialize(): Promise<void>
Connects to the commerce service, restores the user's purchases and finalizes purchases left pending by an earlier session. Safe to call many times and from many scripts: concurrent calls share one attempt, and after a failure the next call tries again.
- Resolves when purchases are restored and pending non-consumables and subscriptions are acknowledged. Recovered consumables are delivered in the background, as soon as their handler is registered.
- Errors:
NetworkError,ServiceUnavailable,ServiceDisconnectedorErrorwhen the service cannot be reached. - Native calls:
CommerceKitModule.createClient(new Commerce.ClientOptions(onPurchasesUpdated))once,startConnection(),queryPurchase()for each product type, andacknowledgePurchase()for each pending purchase.
try {
await commerceKit.initialize();
} catch (error) {
storeText.text = "Store unavailable, try again later";
}
getProductInfo(productId: string): Promise<CommerceProduct>
Fetches the details of one product defined on the developer portal. Results are cached for the session.
- Resolves with a
CommerceProduct: the CommerceKit 3.x fields, mapped from the Lens API product, and that product itself asnativeProduct:
| Field | Type | Meaning |
|---|---|---|
id | string | Product ID. |
type | string | "NonConsumable", "Consumable", "Subscription" or "Unknown". |
displayName, description | string | Shown to users. |
price.price | number | Amount in major units, for example 1.99 (as in 3.x). |
price.currency | string | ISO 4217 code, for example "USD". |
iconUri, extras | string | Icon URI and custom metadata, or empty strings. |
nativeProduct | Commerce.Product | New: the product as returned by the Lens API, with everything it provides: price.displayPrice (the price formatted for the user, for example "$1.99"; use it to show prices), price.price in the smallest currency unit, type as a Commerce.ProductType, and for subscriptions subscriptionOfferDetails, the offers that can be bought. |
- Errors:
ItemUnavailablewhen the Lens has no product with this ID (or it is not published), or a connection error. - Native calls:
queryProductDetails([productId]), once per product per session.
purchaseProduct(productId: string, offerId?: string | null): Promise<PurchaseOutcome>
Buys a product: opens the system checkout and resolves once the purchase is complete and finalized. Calling it again for the same product while a purchase is in progress returns the same promise; the second call's offerId is ignored.
| Parameter | Type | Meaning |
|---|---|---|
productId | string | Product ID from the developer portal. |
offerId | string | null (optional) | Subscriptions only: offerId of one of product.nativeProduct.subscriptionOfferDetails. Omit it to buy the default offer. Ignored, with a warning, for other product types. |
Resolves with a PurchaseOutcome:
| Field | Type | Meaning |
|---|---|---|
status | "purchased" | "alreadyOwned" | "cancelled" | "pending" | purchased: completed and delivered or activated. alreadyOwned: the user already owns the non-consumable or has an active subscription; nothing was charged. cancelled: the user closed the checkout. pending: paid, but not finalized yet; finalized automatically later (see Purchase Lifecycle). |
success | boolean | true for purchased and alreadyOwned. |
cancelled | boolean | true for cancelled. |
purchase | Commerce.Purchase | null | The purchase record, when one is involved: token, productId, purchaseState, isAcknowledged, isAutoRenewing, expiryTime. Always null for consumables: their purchase only goes to the registerConsumable handler, before it is acknowledged. |
Errors (in every case but the last, nothing was charged):
ItemUnavailable: unknown product or offer, or a product without a valid type on the developer portal.Error: a consumable without aregisterConsumablehandler. This is checked before checkout opens.- The code reported when checkout fails: usually
Error, or for examplePaymentUnavailableorNetworkError. ServiceDisconnected: the commerce session was lost while starting the checkout. CommerceKit does not retry the launch, because the first attempt may have reached the service; the next call reconnects.Errorafter 10 minutes without a checkout result (see Purchase Lifecycle). This is the only case where the user may have paid; the purchase is finalized if it shows up later.
Cancelling is not an error; check outcome.cancelled.
Native calls: launchPurchaseFlow(productId, offerId); once the result arrives through the onPurchasesUpdated callback, queryPurchase() and acknowledgePurchase(token). The product's details are loaded first with queryProductDetails() if they are not cached.
try {
const outcome = await commerceKit.purchaseProduct("glow_up_hoodie");
switch (outcome.status) {
case "purchased":
case "alreadyOwned":
unlockHoodie(true);
break;
case "pending":
statusText.text = "Payment received, finishing up...";
break;
case "cancelled":
break;
}
} catch (error) {
statusText.text = `Purchase failed: ${error.message}`;
}
registerConsumable(productId: string, deliver: ConsumableDeliveryHandler): () => void
Registers how a consumable is delivered. Required before the consumable can be sold.
deliver:(purchase: Commerce.Purchase) => boolean | void | Promise<boolean | void>. Processes the purchase, for example by granting the item or having your server redeempurchase.token. CommerceKit calls it for every completed purchase, including purchases recovered after the Lens closed mid-purchase, and acknowledges (consumes) the purchase only after it completes. Returnfalseto leave the purchase pending for next time; throwing or rejecting does the same and logs a warning. It must eventually settle, and must not callpurchaseProduct().- Returns a function that removes the handler. Registering again replaces the handler.
- Errors: throws
CommerceKitError(Error) when the product ID is empty ordeliveris not a function. - Native calls: none. The native API consumes a consumable when it is acknowledged; the handler decides when CommerceKit calls
acknowledgePurchase(token).
isProductOwned(productId: string): boolean
Whether the user currently owns a non-consumable or has an active subscription. Consumables are never owned. Reads the state of the last sync without network access; false until initialize() completes.
getPurchase(productId: string): Commerce.Purchase | null
The user's most relevant purchase record of a product, from the last sync, or null. Reads it without network access.
| Field | Meaning |
|---|---|
purchaseState | Pending (paid, not finalized yet), Purchased (owned, or subscription active), Expired (subscription ended) or Invalidated (refunded or revoked). Consumed consumables have no record. |
token | Identifies the purchase, for example for native calls through client(). |
isAutoRenewing | Subscriptions: false once cancelled. |
expiryTime | Subscriptions: end of the current billing period, in milliseconds since the Unix epoch. |
purchaseTime | Not reported by the commerce service yet: always 0. |
When a cancelled subscription's paid period ends, isProductOwned() becomes false right away, while the record keeps saying Purchased until a sync reports Expired.
checkPurchaseStatus(productId: string): Promise<Commerce.PurchaseState>
Syncs with the commerce service, then returns the state of the user's most relevant purchase of the product:
| State | Meaning |
|---|---|
Purchased | Owned, or subscription active. |
Pending | Paid but not finalized yet. |
Expired | The subscription ended without renewing. |
Invalidated | Refunded or revoked. |
Unset | Never bought, or a consumable that was already consumed. |
- Errors: connection errors.
- Native calls: like
refresh().
refresh(): Promise<void>
Syncs purchases with the commerce service, for example after the Lens resumes or after a change made through client(), and finalizes any pending ones. Like initialize(), it waits for non-consumables and subscriptions to be acknowledged and delivers consumables in the background. Calls initialize() when needed.
- Errors: connection errors.
- Native calls:
queryPurchase()for each product type, andacknowledgePurchase()for each pending purchase.
onPurchasesChanged
Event fired whenever the known purchases change: purchases restored, a purchase completed or finalized, or a sync that finds a change such as an expired or cancelled subscription or a refunded purchase. Read the new state with isProductOwned() or getPurchase(). A listener that throws is logged and does not affect the others.
const unsubscribe = commerceKit.onPurchasesChanged.add(() => this.updateStoreUI());
// later, for example in OnDestroyEvent:
unsubscribe();
client(): Promise<Commerce.Client>
The underlying commerce client, for less common operations that CommerceKit does not wrap, such as cancelling a subscription (see Subscriptions). It resolves once CommerceKit is initialized, and is the same client CommerceKit uses, so:
- Purchase updates still flow through CommerceKit, which finalizes them (consumables through their registered handler).
- CommerceKit does not see changes you make directly through the client until it syncs. Call
refresh()afterwards. - Do not call
startConnection(),endConnection()oracknowledgePurchase()yourself: CommerceKit manages the connection and acknowledges purchases.
In Lens Studio Preview it is the simulated client (see Testing in Lens Studio Preview).
const client = await commerceKit.client();
const history = await client.queryPurchaseHistory();
initializeCatalog(productCatalog: readonly unknown[]): Promise<void> (deprecated)
Kept so CommerceKit 3.x code keeps working. It calls initialize() and, as in 3.x, never rejects: failures are logged. Products are no longer defined in the Lens, so productCatalog is ignored, with a warning when it is not empty. New code should call initialize().
Errors
Every failure is a CommerceKitError (exported from CommerceKit.lspkg/CommerceKit):
| Field | Type | Meaning |
|---|---|---|
code | Commerce.ResponseCode | What went wrong. |
message | string | Developer-facing description. |
debugMessage | string | Raw detail from the commerce service, when available. |
Common codes: ItemUnavailable (no such product or offer), PaymentUnavailable (payment failed), NetworkError (offline), ServiceUnavailable (commerce service down; try again later), ServiceDisconnected (the session was lost and reconnecting failed; try again later), and Error (anything else, including most failed checkouts).
import { CommerceKitError } from "CommerceKit.lspkg/CommerceKit";
try {
await commerceKit.purchaseProduct("coins_100");
} catch (error) {
if (error instanceof CommerceKitError && error.code === Commerce.ResponseCode.NetworkError) {
statusText.text = "You're offline";
}
}
Subscription Helpers
CommerceKit.lspkg/Helper/SubscriptionOffers turns offers into English labels:
| Function | Returns |
|---|---|
describeOffer(offer) | All pricing phases in order, with the service's displayPrice: "Free for 1 week, then $4.99 / month", "$4.99 / month for 3 months, then $9.99 / month". |
getFreeTrialPhase(offer) | The offer's free trial phase, or null. |