Skip to content

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 links
  • params.waitForEntitlementAfter (Date, optional) - Wait for entitlement after this date

Returns: Promise<Entitlement[]>

javascript
const entitlements = await window.sesamy.entitlements.list({
  includeSignedLinks: true,
});

entitlements.get() ​

Get a specific entitlement by ID.

Parameters: entitlementId (string)

Returns: Promise<Entitlement | undefined>

javascript
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 identifier
  • passes (string[], optional) - Pass URLs to check

Returns: Promise<Entitlement | undefined>

javascript
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>

javascript
const access = await window.sesamy.entitlements.access('ent_123');
console.log('Access URL:', access.url);

Get signed links from the current session.

Returns: SignedLink[]

javascript
const links = window.sesamy.entitlements.signedLinks();

Subscriptions (Contracts) ​

Manage user subscription contracts.

contracts.list() ​

List all user contracts.

Returns: Promise<Contract[]>

javascript
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>

javascript
const contract = await window.sesamy.contracts.get('con_123');

contracts.cancel() ​

Cancel a subscription.

Parameters: contractId (string)

Returns: Promise<void>

javascript
await window.sesamy.contracts.cancel('con_123');

Checkouts ​

Create and manage checkout sessions for purchases.

checkouts.create() ​

Create a new checkout session.

Parameters:

typescript
{
  items: Item[],              // Products to purchase
  redirectUrl: string,        // Post-checkout redirect

  // 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>

javascript
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>

javascript
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>

javascript
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>

javascript
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[]>

javascript
const products = await window.sesamy.products.list();

Bills & Transactions ​

bills.list() ​

List user's bills.

Returns: Promise<Bill[]>

javascript
const bills = await window.sesamy.bills.list();

bills.get() ​

Get a specific bill.

Parameters: billId (string)

Returns: Promise<Bill>

javascript
const bill = await window.sesamy.bills.get('bill_123');

Tallies ​

Manage user tallies (usage counters).

tallies.list() ​

List all user tallies.

Returns: Promise<Tally[]>

javascript
const tallies = await window.sesamy.tallies.list();

tallies.get() ​

Get a specific tally.

Parameters: tallyId (string)

Returns: Promise<Tally>

javascript
const tally = await window.sesamy.tallies.get('articles_read');

tallies.create() ​

Create a new tally.

Parameters: data (Partial tally object)

Returns: Promise<Tally>

javascript
const tally = await window.sesamy.tallies.create({
  id: 'articles_read',
  value: [0],
});

tallies.update() ​

Update a tally.

Parameters:

  • tallyId (string)
  • data (Partial tally object)

Returns: Promise<Tally>

javascript
const updated = await window.sesamy.tallies.update('articles_read', {
  value: [5],
});

tallies.delete() ​

Delete a tally.

Parameters: tallyId (string)

Returns: Promise<boolean>

javascript
const success = await window.sesamy.tallies.delete('articles_read');

tallies.push() ​

Push a value to a tally.

Parameters:

  • tallyId (string)
  • data (Value to push)

Returns: Promise<TallyValue>

javascript
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[]>

javascript
const tags = await window.sesamy.tags.list();

tags.set() ​

Add a tag to the user.

Parameters: tag (string)

Returns: Promise<void>

javascript
await window.sesamy.tags.set('premium_member');

tags.delete() ​

Remove a tag from the user.

Parameters: tag (string)

Returns: Promise<void>

javascript
await window.sesamy.tags.delete('premium_member');

Paywalls ​

Manage paywalls and check leaky paywall access.

paywalls.get() ​

Get paywall details.

Parameters: paywallIdOrUrl (string)

Returns: Promise<Paywall>

javascript
const paywall = await window.sesamy.paywalls.get('paywall_123');

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 ID
  • body (object):
    • publisherContentId (string, required) — unique identifier of the content being accessed
    • url (string, optional) — URL of the article. When provided, the response includes a signedLink with a temporary access token

Returns: Promise<PaywallAccessResult>

javascript
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:

FieldAllowedBlocked
status'allowed''paywall'
remainingNumber of free reads left0
signedLinkSigned URL (when url provided)—
paywall—Paywall configuration object

paywalls.executeStrategy() ​

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 ID
  • params (object, optional):
    • attribution (object, optional) — overrides for the auto-collected UTM tags (source, medium, campaign, term, content) and referrer. Any field you pass wins over the auto-collected value
    • content (object, optional) — metadata about the gated content (contentId, title, type, price, currency, publisherId)
    • debug (boolean, optional) — include a debug envelope (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".

javascript
// 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:

FieldDescription
paywallIdThe resolved paywall ID
matchedNodeThe flow node that resolved the paywall (id, type, label?); omitted when the fallback was used
paywallThe resolved paywall configuration
debugPresent only when debug: true was passed

Fulfillments ​

Manage fulfillments.

fulfillments.list() ​

List all fulfillments.

Returns: Promise<Fulfillment[]>

javascript
const fulfillments = await window.sesamy.fulfillments.list();

fulfillments.requestDelivery() ​

Request delivery of a fulfillment.

Parameters:

  • sku (string)
  • itemId (string)

Returns: Promise<boolean>

javascript
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>

javascript
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>

javascript
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:

StatusMeaning
403The reader has no active entitlement for the pool's SKU
404The pool does not exist
409The pool has no keys left
javascript
try {
  await window.sesamy.licenses.claim('pool_acme_secure');
} catch (error) {
  if (error.status === 409) {
    showOutOfKeysMessage();
  }
}

LicenseKey ​

FieldTypeDescription
keystringThe key to redeem with the external vendor
poolIdstringThe key pool the key was claimed from
claimedAtstring(Optional) When the key was claimed. Not returned by claim()
expiresAtstringWhen 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[]>

javascript
const transactions = await window.sesamy.transactions.list();

transactions.get() ​

Get a specific transaction.

Parameters: transactionId (string)

Returns: Promise<Transaction>

javascript
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>>

javascript
const metadata = await window.sesamy.userMetadata.get();

userMetadata.set() ​

Set user metadata.

Parameters:

  • key (string)
  • value (string)

Returns: Promise<void>

javascript
await window.sesamy.userMetadata.set('preferences', 'dark_mode');

userMetadata.delete() ​

Delete user metadata.

Parameters: key (string)

Returns: Promise<void>

javascript
await window.sesamy.userMetadata.delete('preferences');

Flags ​

Manage feature flags.

flags.list() ​

List all feature flags.

Returns: Promise<Record<string, FlagValue>>

javascript
const flags = await window.sesamy.flags.list();

flags.get() ​

Get a specific flag value.

Parameters: key (string)

Returns: Promise<FlagValue | undefined>

javascript
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>

javascript
await window.sesamy.flags.set('my_flag', true);

flags.delete() ​

Delete a flag.

Parameters: key (string)

Returns: Promise<void>

javascript
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[]>

javascript
const issues = await window.sesamy.getPaymentIssues();

paymentIssues.list() ​

List payment issues for the user.

Returns: Promise<PaymentIssue[]>

javascript
const issues = await window.sesamy.paymentIssues.list();

Generate authenticated links to various Sesamy pages and flows.

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:

typescript
{
  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)
}
typescript
{
  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
}
typescript
{
  target: 'change-payment',
  contractId: string,       // Required contract ID
  redirectUrl?: string,
  language?: string,
  shorten?: boolean,
  ttl?: number
}
typescript
{
  target: 'change-plan',
  contractId: string,       // Required contract ID
  redirectUrl?: string,
  language?: string,
  shorten?: boolean,
  ttl?: number
}
typescript
{
  target: 'consume',
  sku: string,             // Required product SKU
  episodeId?: string,      // Optional episode ID
  redirectUrl?: string,
  language?: string,
  shorten?: boolean,
  ttl?: number
}

Returns: Promise<string> - The generated URL

Examples:

javascript
// 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 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

javascript
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>

javascript
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>

javascript
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>

javascript
const success = await window.sesamy.profile.unlinkSpotify();

profile.openHostedAccountPage() ​

Deprecated: Use generateLink({ target: 'account' }) instead.

Opens the hosted account management page.

Returns: Promise<void>

javascript
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

javascript
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

javascript
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 authentication
  • url (string) - URL of the content to fetch
  • selector (string, optional) - CSS selector to extract specific content

Returns: Promise<string> - The fetched content

javascript
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

javascript
// Access vendor-specific functionality
const vendorData = await window.sesamy.vendor.someMethod();

Utility Methods ​

getVersion() ​

Get the current version of Sesamy JS.

Returns: string

javascript
const version = window.sesamy.getVersion();
console.log('Sesamy JS version:', version);

isReady() ​

Check if Sesamy JS has completed initialization.

Returns: boolean

javascript
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): An Error, or any value describing the failure
  • options.details (object, optional): Flat context for the report. Keys are strings; values are strings, numbers, booleans or null. At most 20 keys are kept, and text values are truncated to 500 characters.

Returns: void

javascript
window.sesamy.errors.report(new Error('Access check timed out'), {
  details: { component: 'content-container', attempt: 2 },
});

clearCache() ​

Clear the Sesamy SDK cache.

Returns: void

javascript
window.sesamy.clearCache();

log() ​

Access Sesamy's logging functionality for debugging.

javascript
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>

javascript
const attr = await window.sesamy.attribution.get();

attribution.set() ​

Set attribution data.

Parameters: attribution (Attribution object)

Returns: Promise<void>

javascript
await window.sesamy.attribution.set({
  utmSource: 'email',
  utmMedium: 'newsletter',
  utmCampaign: 'black_friday',
});

Common Patterns ​

Check Access & Show Paywall ​

javascript
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 ​

javascript
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 ​

javascript
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 ​

Released under the MIT License.