Skip to main content

CommerceKitModule

Class

The main entry point for integrating commerce functionalities into a Lens.

  • Snapchat: not supported
  • SPECS: fully supported
  • Camera Kit Web: not supported
  • Camera Kit Mobile: not supported
  • SnapchatNot supported — Available on SPECS only
  • SPECSFully supported
  • Camera Kit WebNot supported — Available on SPECS only
  • Camera Kit MobileNot supported — Available on SPECS only

Platform details

  • Snapchat — Not supported — Available on SPECS only.

  • SPECS — Fully supported.

  • Camera Kit Web — Not supported — Available on SPECS only.

  • Camera Kit Mobile — Not supported — Available on SPECS only.

The main entry point for integrating commerce functionalities into a Lens. It is typically added as an Asset in a Lens Studio project. This module provides access to the primary method for configuring and creating a Client object, which is used for all in-Lens purchase and product management needs. This module allows a Lens to interact with the commerce system, enabling features like displaying products, initiating purchases, and managing user entitlements.

Index

Example

let module: CommerceKitModule = require("LensStudio:CommerceKitModule");

// Declare client variable and purchase status cache
let client: Commerce.Client;
let purchaseStatusCache: Map<string, Commerce.PurchaseState> = new Map();

// Helper function to print important product fields manually
function printProductDetails(product: any) {
print(` ID: ${product.id}, Name: ${product.displayName}, Price: ${product.price?.displayPrice || product.price?.price}`);
}

// Function to update the purchase status cache from purchase history
async function updatePurchaseStatusCache(productIds: string[]) {
try {
const purchaseHistory = await client.queryPurchaseHistory();

productIds.forEach(productId => {
const purchase = purchaseHistory.find((p: any) => p.productId === productId);
if (purchase) {
purchaseStatusCache.set(productId, purchase.purchaseState);
print("Purchase state of " + productId + ", purchased:" + (purchase.purchaseState === Commerce.PurchaseState.Purchased));
} else {
purchaseStatusCache.set(productId, Commerce.PurchaseState.Unset);
print("No purchase record found for product ID: " + productId);
}
});
} catch (error) {
print('Error updating purchase status cache: ' + error);
}
}

// Function to handle processing of a successful purchase.
function processPurchase(purchase: Commerce.Purchase) {
print(`Processing purchase for product: ${purchase.productId}, state: ${purchase.purchaseState}`);

// Only acknowledge purchases that are in Purchased state
if (purchase.purchaseState === Commerce.PurchaseState.Purchased || purchase.purchaseState === Commerce.PurchaseState.Pending) {
client.acknowledgePurchase(purchase.token).then(() => {
print(`Purchase for ${purchase.productId} acknowledged.`);
}).catch(error => {
print('Failed to acknowledge purchase: ' + error);
});
} else {
print(`Purchase for ${purchase.productId} is not in Purchased state, skipping acknowledgment.`);
}
}

// Function to handle purchase status updates.
const onPurchasesUpdated = (result: Commerce.PurchaseResult, purchases: Commerce.Purchase[]) => {
if (result.responseCode === Commerce.ResponseCode.Success && purchases.length > 0) {
purchases.forEach(purchase => {
print(`Successfully purchased: ${purchase.productId}`);
processPurchase(purchase);
});
} else if (result.responseCode === Commerce.ResponseCode.UserCanceled) {
print('Purchase was cancelled.');
} else {
print('Purchase failed or was not acknowledged.');
}

// Update the status cache after processing purchases
const productIds = ['com.snap.product1', 'com.snap.product2', 'com.snap.product3', 'com.snap.newProduct1'];
updatePurchaseStatusCache(productIds);
};

// Scenario: Query available product details.
async function demoQueryProducts() {
try {
const productIds = ['com.snap.product1', 'com.snap.product2', 'com.snap.product3'];
const products = await client.queryProductDetails(productIds);

if (products && products.length > 0) {
print('Available products:');
products.forEach((product: any) => {
printProductDetails(product);
});
} else {
print('No products found');
}
} catch (error) {
print('Error during product query: ' + error);
}
}

// Scenario: Check purchase status for a specific product (using cache).
function demoCheckPurchaseStatus(productId: string) {
const purchaseState = purchaseStatusCache.get(productId);

if (purchaseState === undefined) {
print(`Product '${productId}' not found in cache. Initialize cache first.`);
return;
}

switch (purchaseState) {
case Commerce.PurchaseState.Purchased:
print(`Product '${productId}' has been purchased.`);
break;
case Commerce.PurchaseState.Unset:
print(`Product '${productId}' has not been purchased.`);
break;
default:
print(`Product '${productId}' purchase state: ${purchaseState}`);
}
}

// Scenario: Launch purchase flow for a product.
async function demoLaunchPurchaseFlow(productId: string) {
try {
const purchaseResult = await client.launchPurchaseFlow(productId);
print(`Purchase flow completed with response code: ${purchaseResult.responseCode}`);

if (purchaseResult.responseCode === Commerce.ResponseCode.Success) {
print('Purchase flow was launched successfully.');
}
} catch (error) {
print('Error in purchase process: ' + error);
}
}

// Example invocation of the various scenarios
async function example() {
try {
// Initialize the commerce client
print('Initializing commerce client...');
const clientOptions = new Commerce.ClientOptions(onPurchasesUpdated);
client = module.createClient(clientOptions);

await client.startConnection();
print('Connected to commerce service.');

const productIds = ['com.snap.product1', 'com.snap.product2', 'com.snap.product3', 'com.snap.newProduct1'];
await updatePurchaseStatusCache(productIds);

await demoQueryProducts();
demoCheckPurchaseStatus('com.snap.product1'); // Check from cache (no query needed)
await demoLaunchPurchaseFlow('com.snap.newProduct1'); // Launch purchase flow
demoCheckPurchaseStatus('com.snap.newProduct1'); // Check from cache (automatically updated via callback)
} catch (error) {
print('Error in commerce operations: ' + error);
} finally {
if (client) {
client.endConnection();
print('Commerce client connection closed.');
}
}
}

example();

Extends

Properties

name

name: string

The name of the Asset in Lens Studio.

Default Value

""

Inherited from

Asset.name


uniqueIdentifier

readonly uniqueIdentifier: string

Since

Lens Scripting Version 176

Inherited from

Asset.uniqueIdentifier

Methods

createClient()

createClient(options): Client

SPECS

Allows for creating a fully configured commerce client. ClientOptions can be provided to customize its behavior, such as setting up a listener for purchase updates. The returned client is the primary tool for all commerce interactions, including displaying products, managing purchases, and checking purchase history.

Parameters

ParameterType
optionsClientOptions

Returns

Client


getTypeName()

static getTypeName(): TypeName<CommerceKitModule>

SPECS

Returns the fully-qualified JavaScript type name for this class (for example, "Component.Camera"). This is a static accessor (no instance required) and returns the same value as the instance getTypeName().

Returns

TypeName<CommerceKitModule>

Overrides

Asset.getTypeName


getTypeName()

getTypeName(): string

Returns the name of this object's type.

Returns

string

Inherited from

Asset.getTypeName


isOfType()

isOfType(type): boolean

Returns true if the object matches or derives from the passed in type.

Parameters

ParameterType
typestring

Returns

boolean

Inherited from

Asset.isOfType


isSame()

isSame(other): boolean

Returns true if this object is the same as other. Useful for checking if two references point to the same thing.

Parameters

ParameterType
otherScriptObject

Returns

boolean

Inherited from

Asset.isSame