API Reference
The Sesamy JS API provides methods for managing user entitlements, subscriptions, purchases, and products. These methods wrap the Sesamy SDK with browser-optimized functionality and automatic token handling.
Entitlements
Entitlements represent access rights that users have to content through purchases, subscriptions, or signed links.
entitlements.list()
Fetches all of a user's entitlements.
Parameters:
params.includeSignedLinks(boolean, default:true) - Include signed linksparams.waitForEntitlementAfter(Date, optional) - Wait for entitlement after this date
Returns: Promise<Entitlement[]>
const entitlements = await window.sesamy.entitlements.list({
includeSignedLinks: true,
});entitlements.get()
Get a specific entitlement by ID.
Parameters: entitlementId (string)
Returns: Promise<Entitlement | undefined>
const ent = await window.sesamy.entitlements.get('ent_123');entitlements.hasAccess()
Check if user has access to content. Matches by SKU, purchase option ID, URL, or passes.
Parameters:
itemSrc(string) - Content identifierpasses(string[], optional) - Pass URLs to check
Returns: Promise<Entitlement | undefined>
const entitlement = await window.sesamy.entitlements.hasAccess('https://example.com/article', [
'premium-pass',
]);
if (entitlement) {
// User has access
}entitlements.access()
Get access details for an entitlement.
Parameters: entitlementId (string)
Returns: Promise<Access>
const access = await window.sesamy.entitlements.access('ent_123');
console.log('Access URL:', access.url);entitlements.signedLinks()
Get signed links from the current session.
Returns: SignedLink[]
const links = window.sesamy.entitlements.signedLinks();Subscriptions (Contracts)
Manage user subscription contracts.
contracts.list()
List all user contracts.
Returns: Promise<Contract[]>
const contracts = await window.sesamy.contracts.list();
contracts.forEach((c) => console.log(`${c.id}: ${c.status}`));contracts.get()
Get a specific contract.
Parameters: contractId (string)
Returns: Promise<Contract>
const contract = await window.sesamy.contracts.get('con_123');contracts.cancel()
Cancel a subscription.
Parameters: contractId (string)
Returns: Promise<void>
await window.sesamy.contracts.cancel('con_123');Checkouts
Create and manage checkout sessions for purchases.
checkouts.create()
Create a new checkout session.
Parameters:
{
items: Item[], // Products to purchase
redirectUrl: string, // Post-checkout redirect
redirectLabel?: string, // Label for the button back to redirectUrl on the
// confirmation page and in the order email.
// Defaults to "Go to {vendor}"
// Customer info (optional)
email?: string,
givenName?: string,
familyName?: string,
phoneNumber?: string,
// Gift mode (optional)
giftMode?: boolean,
payerEmail?: string, // When giftMode=true
// Pricing (optional)
price?: number,
currency?: string,
// Discount codes
requestedDiscountCodes?: string[],
// Attribution
attribution?: {
utmSource?: string,
utmMedium?: string,
utmCampaign?: string,
// ...
}
}Returns: Promise<Checkout>
const checkout = await window.sesamy.checkouts.create({
items: [
{
sku: 'premium_monthly',
price: 9.99,
currency: 'USD',
},
],
email: 'user@example.com',
redirectUrl: 'https://yoursite.com/complete',
});
window.location.href = checkout.checkoutUrl;checkouts.get()
Get checkout session by ID.
Parameters: checkoutId (string)
Returns: Promise<Checkout>
const checkout = await window.sesamy.checkouts.get('checkout_123');checkouts.update()
Update a checkout session.
Parameters:
checkoutId(string)params(Partial checkout parameters)
Returns: Promise<Checkout>
const updated = await window.sesamy.checkouts.update('checkout_123', {
email: 'newemail@example.com',
});Products
Retrieve product information.
products.get()
Get product details by SKU.
Parameters: sku (string)
Returns: Promise<Product>
const product = await window.sesamy.products.get('premium_monthly');
console.log('Product:', product.name);
console.log('Price:', product.price);products.list()
List all available products.
Returns: Promise<Product[]>
const products = await window.sesamy.products.list();Bills & Transactions
bills.list()
List user's bills.
Returns: Promise<Bill[]>
const bills = await window.sesamy.bills.list();bills.get()
Get a specific bill.
Parameters: billId (string)
Returns: Promise<Bill>
const bill = await window.sesamy.bills.get('bill_123');Tallies
Manage user tallies (usage counters).
tallies.list()
List all user tallies.
Returns: Promise<Tally[]>
const tallies = await window.sesamy.tallies.list();tallies.get()
Get a specific tally.
Parameters: tallyId (string)
Returns: Promise<Tally>
const tally = await window.sesamy.tallies.get('articles_read');tallies.push()
Push a value to a tally.
Parameters:
tallyId(string)data(Value to push)
Returns: Promise<TallyValue>
const updated = await window.sesamy.tallies.push('articles_read', {
value: ['article_123'],
});Tags
Manage user tags.
tags.list()
List all user tags.
Returns: Promise<string[]>
const tags = await window.sesamy.tags.list();tags.set()
Add a tag to the user.
Parameters: tag (string)
Returns: Promise<void>
await window.sesamy.tags.set('premium_member');tags.delete()
Remove a tag from the user.
Parameters: tag (string)
Returns: Promise<void>
await window.sesamy.tags.delete('premium_member');Paywalls
Manage paywalls and check leaky paywall access.
paywalls.get()
Get paywall details.
Parameters:
paywallIdOrUrl(string): a paywall ID, a strategy ID (st_…), or a URL. A URL whose last path segment is a strategy ID counts as a strategy.options(object, optional):contentId(string), the publisher content ID of the article the paywall is shown on. Only used for strategies.
Returns: Promise<Paywall>
const paywall = await window.sesamy.paywalls.get('paywall_123');
// A strategy returns the paywall it selected for this visitor
const chosen = await window.sesamy.paywalls.get('st_acme', { contentId: 'article-2024-01-15' });
console.log(chosen.id, chosen.strategyId, chosen.decisionId);If the strategy already selected a paywall for this content, or the page has only one decision from it (for example from content.hasAccess() or the Capsule plugin), sesamy-js returns that paywall and does not execute the strategy again. Otherwise it executes the strategy with the stored attribution (UTM tags and referrer).
When checkouts.create() is called with attribution.source: 'PAYWALL' and a sourceId that matches a strategy-selected paywall, sesamy-js adds that paywall's decisionId and strategyId to the attribution. Values you set yourself take precedence, and a strategyId you set is paired only with that strategy's own decision. Decisions are kept per article, and one is added only when exactly one decision on the page matches the paywall (and your strategyId, if set). Otherwise nothing is added. This links the purchase to the strategy decision in conversion stats.
paywalls.checkAccess()
Check whether a user can access content under a leaky paywall. Returns either an "allowed" response with remaining free reads (and optionally a signed link), or a "paywall" response with the paywall configuration when the free limit is reached.
TIP
For most use cases, prefer content.hasAccess() which orchestrates the full access check flow including leaky paywalls automatically. Use paywalls.checkAccess() directly when you need lower-level control.
Parameters:
paywallId(string) — the paywall IDbody(object):publisherContentId(string, required) — unique identifier of the content being accessedurl(string, optional) — URL of the article. When provided, the response includes asignedLinkwith a temporary access token
Returns: Promise<PaywallAccessResult>
const result = await window.sesamy.paywalls.checkAccess('pw_abc123', {
publisherContentId: 'article-2024-01-15',
url: 'https://example.com/articles/my-article',
});
if (result.status === 'allowed') {
console.log('Access granted, remaining:', result.remaining);
console.log('Signed link:', result.signedLink);
} else {
// result.status === 'paywall'
console.log('Free limit reached');
console.log('Paywall config:', result.paywall);
}Response types:
| Field | Allowed | Blocked |
|---|---|---|
status | 'allowed' | 'paywall' |
remaining | Number of free reads left | 0 |
signedLink | Signed URL (when url provided) | — |
paywall | — | Paywall configuration object |
paywalls.executeStrategy()
Deprecated
Use content.hasAccess() for a non-consuming availability check, and content.unlock() for encode access grants and content retrieval. Set the strategy in the content's paywall-url, or pass { paywall: 'st_acme' } as the second argument. The Capsule plugin registers metered access automatically. Direct calls to paywalls.executeStrategy() still work, but log a deprecation warning once per sesamy-js instance.
Evaluate a paywall strategy by ID against the visitor's context and return the resolved paywall plus which rule matched. Attribution (UTM tags + the page referrer) is collected automatically from the stored attribution; the visitor's device, geo and referral are derived server-side from the request. You only need to pass overrides or extra context.
Parameters:
strategyId(string) — the strategy IDparams(object, optional):attribution(object, optional) — overrides for the auto-collected UTM tags (source,medium,campaign,term,content) andreferrer. Any field you pass wins over the auto-collected valuecontent(object, optional) — metadata about the gated content (contentId,title,type,price,currency,publisherId)debug(boolean, optional) — include adebugenvelope (requester object, cache, timing) in the response
Returns: Promise<StrategyExecutionResult>
A rejection means keep the content locked
executeStrategy() never resolves without a paywall. When the strategy cannot be evaluated or the selected paywall cannot render, the promise rejects: a 503 for an upstream failure, or a forwarded request-level 4xx (a 404 for an unknown strategy). Treat a rejection as "keep the gated content locked" and show your default paywall, not as "no paywall applies".
// Attribution (UTM + referrer) is added automatically
const result = await window.sesamy.paywalls.executeStrategy('strategy_123');
console.log('Show this paywall:', result.paywall);
console.log('Matched node:', result.matchedNode); // omitted when the fallback matched
// Override or extend the auto-collected attribution
const result2 = await window.sesamy.paywalls.executeStrategy('strategy_123', {
attribution: { campaign: 'black_friday' },
content: { contentId: 'article-2024-01-15' },
});Response fields:
| Field | Description |
|---|---|
paywallId | The resolved paywall ID |
matchedNode | The flow node that resolved the paywall (id, type, label?); omitted when the fallback was used |
paywall | The resolved paywall configuration |
debug | Present only when debug: true was passed |
Fulfillments
Manage fulfillments.
fulfillments.list()
List all fulfillments.
Returns: Promise<Fulfillment[]>
const fulfillments = await window.sesamy.fulfillments.list();fulfillments.requestDelivery()
Request delivery of a fulfillment.
Parameters:
sku(string)itemId(string)
Returns: Promise<boolean>
const success = await window.sesamy.fulfillments.requestDelivery('ebook_premium', 'item_123');Licenses
Hand out third-party license keys, such as an antivirus code bundled with a subscription, from a publisher-owned key pool. The reader needs an active entitlement for the SKU the pool is linked to, and must be signed in.
licenses.get()
Get the reader's most recent key in a pool. Expired keys are included with status: 'expired' so you can offer a re-claim. Resolves to null when nothing has been claimed yet, or when the reader is not signed in.
Parameters:
poolId(string) - The ID of the key pool
Returns: Promise<LicenseKey | null>
const license = await window.sesamy.licenses.get('pool_acme_secure');
if (!license || license.status === 'expired') {
showClaimButton();
}licenses.claim()
Claim a key from a pool. The call is idempotent: while the reader holds an unexpired key, the same key is returned. After it expires, a new key is assigned.
Parameters:
poolId(string) - The ID of the key pool
Returns: Promise<LicenseKey>
const license = await window.sesamy.licenses.claim('pool_acme_secure');
console.log(`${license.key} is valid until ${license.expiresAt}`);A failed claim rejects with an APIError. Use status to pick the state to show:
| Status | Meaning |
|---|---|
403 | The reader has no active entitlement for the pool's SKU |
404 | The pool does not exist |
409 | The pool has no keys left |
try {
await window.sesamy.licenses.claim('pool_acme_secure');
} catch (error) {
if (error.status === 409) {
showOutOfKeysMessage();
}
}LicenseKey
| Field | Type | Description |
|---|---|---|
key | string | The key to redeem with the external vendor |
poolId | string | The key pool the key was claimed from |
claimedAt | string | (Optional) When the key was claimed. Not returned by claim() |
expiresAt | string | When the key stops being valid. A new key can be claimed after this |
status | 'active' | 'expired' | Whether the key is currently valid |
Transactions
Manage user transactions.
transactions.list()
List all user transactions.
Parameters: query (string, optional)
Returns: Promise<Transaction[]>
const transactions = await window.sesamy.transactions.list();transactions.get()
Get a specific transaction.
Parameters: transactionId (string)
Returns: Promise<Transaction>
const transaction = await window.sesamy.transactions.get('txn_123');User Metadata
Manage custom user metadata.
userMetadata.get()
Get all user metadata.
Returns: Promise<Record<string, UserMetadata>>
const metadata = await window.sesamy.userMetadata.get();userMetadata.set()
Set user metadata.
Parameters:
key(string)value(string)
Returns: Promise<void>
await window.sesamy.userMetadata.set('preferences', 'dark_mode');userMetadata.delete()
Delete user metadata.
Parameters: key (string)
Returns: Promise<void>
await window.sesamy.userMetadata.delete('preferences');Flags
Manage feature flags.
flags.list()
List all feature flags.
Returns: Promise<Record<string, FlagValue>>
const flags = await window.sesamy.flags.list();flags.get()
Get a specific flag value.
Parameters: key (string)
Returns: Promise<FlagValue | undefined>
const isEnabled = await window.sesamy.flags.get('new_feature_enabled');flags.set()
Set a flag value.
Parameters:
key(string)value(boolean | string | number)
Returns: Promise<void>
await window.sesamy.flags.set('my_flag', true);flags.delete()
Delete a flag.
Parameters: key (string)
Returns: Promise<void>
await window.sesamy.flags.delete('my_flag');Payment Issues
getPaymentIssues()
Deprecated: Use
paymentIssues.list()instead. This method is kept for backward compatibility.
List payment issues for the user.
Returns: Promise<PaymentIssue[]>
const issues = await window.sesamy.getPaymentIssues();paymentIssues.list()
List payment issues for the user.
Returns: Promise<PaymentIssue[]>
const issues = await window.sesamy.paymentIssues.list();Generate Link
Generate authenticated links to various Sesamy pages and flows.
generateLink()
Generate a link to different Sesamy pages including account management, checkout, content consumption, and payment method changes. Links can optionally be shortened and include authentication tokens.
Parameters: One of the following link types:
Account Link
{
target: 'account',
contractId?: string, // Optional specific contract
redirectUrl?: string, // Where to redirect after
language?: string, // Language code (e.g., 'en', 'sv')
shorten?: boolean, // Shorten the URL
ttl?: number // Time to live for shortened URL (seconds)
}Checkout Link
{
target: 'checkout',
itemSrc?: string, // Content URL
sku?: string, // Product SKU
episodeId?: string, // Episode ID for podcasts
purchaseOptionId?: string,
publisherContentId?: string,
redirectUrl?: string,
price?: number,
email?: string,
business?: boolean,
currency?: string,
discountCode?: string,
giftMode?: boolean,
payerEmail?: string,
metadata?: Record<string, string>,
attributionItemSrc?: string,
attributionPublisherContentId?: string,
utmSource?: string,
utmMedium?: string,
utmCampaign?: string,
utmTerm?: string,
utmContent?: string,
requireAddress?: boolean,
paymentMethodsFilter?: {
provider?: string,
methods: string[]
}[],
language?: string,
shorten?: boolean,
ttl?: number
}Change Payment Link
{
target: 'change-payment',
contractId: string, // Required contract ID
redirectUrl?: string,
language?: string,
shorten?: boolean,
ttl?: number
}Change Plan Link
{
target: 'change-plan',
contractId: string, // Required contract ID
redirectUrl?: string,
language?: string,
shorten?: boolean,
ttl?: number
}Consume Link
{
target: 'consume',
sku: string, // Required product SKU
episodeId?: string, // Optional episode ID
redirectUrl?: string,
language?: string,
shorten?: boolean,
ttl?: number
}Session transfer
Every link type also accepts sessionTransfer?: boolean. Set it to open the Sesamy page with the reader already logged in, using an AuthHero session transfer token.
The token works once and expires 60 seconds after it is created, so generateLink() does not create it. It returns a link to the /auth/session-transfer route of the Sesamy API proxy on your domain instead. When the reader follows the link, the proxy exchanges their session for a token and redirects to the page with #access_token=…&session_transfer_token=… in the URL fragment. If the exchange fails, the page gets only the access token, and only while the reader's access token is still valid. A reader who is not logged in goes to the page without either.
A page that runs Sesamy JS picks the token up on its own and logs the reader in (see #session_transfer_token).
Setup required
sessionTransfer: true only changes which link you get. The reader arrives logged in only when Sesamy has enabled session transfer for your account: your AuthHero application must be allowed to create transfer tokens, and the page you link to must accept them. Contact Sesamy before you use the option.
sessionTransfer only takes effect with the default cookie-based authentication. It is ignored:
- with the Auth0 plugin, where links keep carrying
#access_token=… - when the reader is not logged in
- together with
shorten, because the browser does not send the session cookie after a redirect from the shortener's domain
Use the link on your own site
Browsers only send the cookie the proxy needs for the exchange when the link is followed from your own site. A link opened from an email or another site still works, but without a transfer token: the page gets the access token if the reader's is still valid, and no token otherwise.
Returns: Promise<string> - The generated URL
Examples:
// Generate account page link
const accountUrl = await window.sesamy.generateLink({
target: 'account',
redirectUrl: 'https://yoursite.com/profile',
});
// Generate checkout link with product
const checkoutUrl = await window.sesamy.generateLink({
target: 'checkout',
sku: 'premium_monthly',
email: 'user@example.com',
redirectUrl: 'https://yoursite.com/success',
shorten: true, // Get a shortened URL
ttl: 7200, // Link expires in 2 hours
});
// Generate checkout link that opens with the reader logged in
const loggedInCheckoutUrl = await window.sesamy.generateLink({
target: 'checkout',
sku: 'sid:acme-plus-monthly',
sessionTransfer: true,
});
// Generate change payment method link
const paymentUrl = await window.sesamy.generateLink({
target: 'change-payment',
contractId: 'con_123',
redirectUrl: 'https://yoursite.com/account',
});
// Generate podcast episode consumption link
const consumeUrl = await window.sesamy.generateLink({
target: 'consume',
sku: 'podcast_123',
episodeId: 'ep_456',
redirectUrl: 'https://yoursite.com/podcast',
});
// Redirect user to generated link
window.location.href = accountUrl;Profile
Manage user profile information.
profile.get()
Get the current user's profile information.
Returns: Promise<Profile | null> - Returns null if user is not authenticated
const profile = await window.sesamy.profile.get();
if (profile) {
console.log('User email:', profile.email);
console.log('Name:', profile.givenName, profile.familyName);
}profile.update()
Update user profile information.
Parameters: profile (Partial profile object)
Returns: Promise<boolean>
const success = await window.sesamy.profile.update({
givenName: 'John',
familyName: 'Doe',
phoneNumber: '+1234567890',
});profile.isSpotifyLinked()
Check if the user's account is linked to Spotify.
Returns: Promise<boolean>
const isLinked = await window.sesamy.profile.isSpotifyLinked();
if (isLinked) {
console.log('Spotify account is linked');
}profile.unlinkSpotify()
Unlink the user's Spotify account.
Returns: Promise<boolean>
const success = await window.sesamy.profile.unlinkSpotify();profile.openHostedAccountPage()
Deprecated: Use
generateLink({ target: 'account' })instead.
Opens the hosted account management page.
Returns: Promise<void>
await window.sesamy.profile.openHostedAccountPage();Products
products.autoOnboard()
Automatically onboard a user to a product (typically used for free trials or promotional access).
Parameters: sku (string)
Returns: Promise<Entitlement[]> - Array of created entitlements
const entitlements = await window.sesamy.products.autoOnboard('trial_premium');
console.log('Created entitlements:', entitlements);products.linkSpotify()
Link user's Spotify account to a specific product.
Parameters: sku (string)
Returns: Promise<void> - Redirects to Spotify authentication
await window.sesamy.products.linkSpotify('podcast_premium');Proxy
Access content through the Sesamy proxy.
proxy.getContent()
Fetch content through the Sesamy proxy using an access token.
Parameters:
accessToken(string) - Access token for authenticationurl(string) - URL of the content to fetchselector(string, optional) - CSS selector to extract specific content
Returns: Promise<string> - The fetched content
const token = await window.sesamy.auth.getTokenSilently();
const content = await window.sesamy.proxy.getContent(
token,
'https://example.com/premium-article',
'.article-content'
);
document.getElementById('content').innerHTML = content;Vendor
Access vendor-specific functionality. The vendor object provides methods specific to your Sesamy vendor account.
Properties: Vendor-specific API methods from the Sesamy SDK
// Access vendor-specific functionality
const vendorData = await window.sesamy.vendor.someMethod();Utility Methods
getVersion()
Get the current version of Sesamy JS.
Returns: string
const version = window.sesamy.getVersion();
console.log('Sesamy JS version:', version);isReady()
Check if Sesamy JS has completed initialization.
Returns: boolean
if (window.sesamy.isReady()) {
// Sesamy is ready to use
const entitlements = await window.sesamy.entitlements.list();
}errors.report()
Report a failure to Sesamy's error reporting, alongside the errors sesamy-js reports itself. Use it from components built on sesamy-js. Reports are sent under the component category and follow the same limits and redaction as sesamy-js's own reports. Nothing is sent when error reporting is turned off.
Parameters:
error(unknown): AnError, or any value describing the failureoptions.details(object, optional): Flat context for the report. Keys are strings; values are strings, numbers, booleans ornull. At most 20 keys are kept, and text values are truncated to 500 characters.
Returns: void
window.sesamy.errors.report(new Error('Access check timed out'), {
details: { component: 'content-container', attempt: 2 },
});clearCache()
Clear the Sesamy SDK cache.
Returns: void
window.sesamy.clearCache();log()
Access Sesamy's logging functionality for debugging.
window.sesamy.log.info('Custom log message');
window.sesamy.log.error('Error message');Attribution
Manage tracking attribution.
attribution.get()
Get current attribution data.
Returns: Promise<Attribution>
const attr = await window.sesamy.attribution.get();attribution.set()
Set attribution data.
Parameters: attribution (Attribution object)
Returns: Promise<void>
await window.sesamy.attribution.set({
utmSource: 'email',
utmMedium: 'newsletter',
utmCampaign: 'black_friday',
});Common Patterns
Check Access & Show Paywall
window.addEventListener('sesamyJsReady', async () => {
const entitlement = await window.sesamy.entitlements.hasAccess(window.location.href);
if (entitlement) {
document.querySelector('.premium-content').style.display = 'block';
} else {
document.querySelector('.paywall').style.display = 'block';
}
});Create Purchase Flow
async function purchaseArticle(sku, price) {
const checkout = await window.sesamy.checkouts.create({
items: [{ sku, price: price.amount, currency: price.currency }],
email: user.email,
redirectUrl: window.location.href,
});
window.location.href = checkout.checkoutUrl;
}Manage Subscriptions
async function displaySubscriptions() {
const contracts = await window.sesamy.contracts.list();
const active = contracts.filter((c) => c.status === 'ACTIVE');
active.forEach((contract) => {
console.log(`Active: ${contract.id}`);
console.log(`Next billing: ${contract.nextBillingDate}`);
});
}Next Steps
- Content Management - Use entitlements with content locking
- Authentication - Manage user sessions
- Analytics - Track user behavior