1.36.2 • Published 28 days ago

@sesamy/sesamy-js v1.36.2

Weekly downloads
-
License
-
Repository
-
Last release
28 days ago

sesamy-js

The Sesamy browser javascript API

The project handles analytics, authentication and communication with the Sesamy API

Analytics

The analytics module is used to track events and page views. It is using the GetAnalytics library to send events to the Sesamy interaction endpoint.

The following events are tracked:

  • Page views, with events triggered on router updates
  • Scroll events, with events triggered on scroll at 25%, 50%, 75%, and 100%
  • Active and idle duration

API

The following methods are available on the sesamy object:

  • amendments
    • create: create an amendment to a contract
    • confirm: confirms a created amendment for a contract
  • analytics
    • track: tracks an event with optional properties
  • attribution
    • get: get the attributions for a user
    • set: set the attributions for a user
  • auth
    • getUser: fetches the user's profile
    • isAuthenticated: checks if the user is authenticated
    • loginWithRedirect: redirects the user to the login page
    • logout: logs the user out
    • setToken: stores a token in session storage
  • bills
    • get: get a bill by id
    • list: lists all the user's bills
  • browser
    • detectAdblock: detects if an ad blocker is enabled
    • isInAppBrowser: detects if the browser is an in-app browser
    • isIncognito: detects if the browser is in incognito mode
  • checkouts
    • create: creates a checkout session
    • get: gets a checkout session by id
    • update: updates a checkout session
  • clearCache: clears the cache for the sesamy-js library
  • content
    • list: get all articles based on the configured selectors
    • get: get an article based on an element or a selector
    • getLanguage: get the current language
    • unlock: retrieves the locked content using an element or a css selector
    • getPropertyFromHTML: extracts a property from HTML content
  • contracts
    • cancel: cancel a contract by id
    • get: get a contract by id
    • list: lists all the user's contracts
  • entitlements
    • access: fetches the user's access URL for an entitlement
    • get: gets a single entitlement by id
    • hasAccess: checks if the user has access to a specific item
    • list: lists the user's entitlements
    • signedLinks: lists signed links registered in the current session
  • flags
    • get: gets a feature flag value
    • set: sets a feature flag value
    • list: lists all feature flags
    • delete: deletes a feature flag
  • fulfillments
    • list: list the user's fulfillments for a SKU
    • requestDelivery: requests delivery for a fulfillment by SKU and delivery method
  • generateLink: creates a link to a Sesamy hosted service such as account, change-payment, consume, or checkout. If the user is authenticated, the link will be signed so that the user can access the service without logging in again.
  • getPaymentIssues: returns a list of failed payments and cards that will expire
  • getVersion: returns the version of the sesamy-js library
  • init: Initializes the sesamy-js library
  • isReady: returns a boolean indicating whether the initialization process has completed
  • log: logs a message to the console (only when debug mode is enabled)
  • paywalls
    • get: get a paywall by id
  • products
    • autoOnboard: trigger the auto-onboarding process for a product by SKU
    • get: get a product by SKU
    • linkSpotify: links a Spotify account to a product
  • profile
    • get: fetches the user's profile
    • isSpotifyLinked: returns true if the user has linked their Spotify account
    • openHostedAccountPage: opens the hosted account page
    • unlinkSpotify: unlinks the user's Spotify account
    • update: updates the user's profile
  • proxy
    • getContent: retrieves locked content using an access token and URL.
  • subscriptions (deprecated, use contracts instead)
    • list: lists all the user's subscriptions
  • tags
    • delete: deletes a tag for the user
    • get: fetches the user's tags
    • set: sets a tag for the user
  • tallies
    • delete: delete a tally by id
    • get: get a tally for a user by id
    • list: list all tallies for a user
    • push: push an item to a tally
  • transactions
    • get: get a transaction by id
    • list: lists all the user's transactions
  • userMetadata
    • delete: deletes the user's metadata by id
    • get: get the user's metadata by id
    • list: list all the user's metadata
    • set: sets the user's metadata
  • vendors
    • get: get the settings for the current vendor
    • list: list all publishers connected to the user. This is not available for publisher tokens

Events

The following events are emitted by the sesamy-js library:

  • sesamyJsReady - Emitted when the sesamy-js library is ready to be used
  • sesamyJsAuthenticated - Emitted when the user is authenticated
  • sesamyJsClearCache - Emitted when the cache is cleared
  • sesamyJsLogout - Emitted when the user logs out
  • sesamyJsPurchase - Emitted after a purchase is completed and passes an itemSrc property with the source of the purchase

Url triggers

Query parameters

The library can trigger actions based on query parameters. The following query parameters are supported:

  • sesamy-refresh. If present, the library will clear the cache and emit a sesamyJsClearCache event.
  • sesamy-user. If present, the library will validate that the user is authenticated with the correct email. If not, the user will be logged out and a new login with be initiated.
  • sesamy-login. If present, the library will validate that the user is authenticated. If not, the user will be logged out and a new login with be initiated.
  • sesamy-purchase. Triggers a sesamyJsPurchase event.
  • sesamy-token. If present, the library parse the token and add any content permissions that the token grants.

Hash triggers

The library can read the access token from the hash. It is not the preferred way of logging in a user but can be used when redirecting the user across domains where a cookie-based solution is not possible. The hash is not sent to the server so the is no risk of leaking the token. The token hash is passed like this: #access_token=<token>

Usage

The script can either be initiated with a JSON object in a script tag or by calling the init method.

The script will look for a script tag with the id sesamy-js, and if it isn't found it will wait for a call to the init function before initializing. The only required part is the clientId attribute.

<script type="application/json" id="sesamy-js">
  {
    "clientId": "demo"
  }
</script>

These are the available configuration options, with their default values:

{
  clientId: null,
  organization: null,
  api: {
    namespace: 'sesamy',
    endpoint: 'https://api2.sesamy.com'
  },
  analytics: {
    enabled: true,
    endpoint: 'https://logs.sesamy.com/events'
  },
  auth: {
    clientId: null,
    organization: null,
    enabled: true,
    endpoint: 'https://auth.sesamy.com',
    redirectUri: window.location.origin
  },
  content: {
    article: {
      article: { selector: 'article' },
      image: { selector: 'img', attribute: 'src' },
      title: { selector: 'h1', attribute: 'textContent' },
      excerpt: { selector: 'p', attribute: 'textContent' },
      price: { selector: 'article', attribute: 'data-price' },
      currency: { selector: 'article', attribute: 'data-currency' },
      url: { selector: 'link', attribute: 'href' },
      id: { selector: 'article', attribute: 'data-id' },
      pass: { selector: 'article', attribute: 'data-pass' },
    }
  },
  tranforms: {
    enabled: false,
    rules: []
  }
}

Custom HTML Attributes

Visibility

Overview

The sesamy-visibility attribute allows dynamic visibility control of HTML elements based on the authentication state of a user.

Usage

This attribute can be added to HTML elements to automatically show or hide them based on authentication status.

Example

<div sesamy-visibility="logged-in">Welcome, User!</div>
<div sesamy-visibility="not-logged-in">Please log in.</div>

Links

Overview

The sesamy-link attribute attaches a click handler to an element that redirects the user.

Usage

This attribute can be added to HTML elements to redirect the user to the following targets: login, logout and account.

Example

<div sesamy-link="login">Login</div>
<div sesamy-link="logout">Logout</div>
<div sesamy-link="account">Account</div>

Core API

isReady()

Checks if the initialization process of the Sesamy library has completed. This function allows you to determine when it's safe to use the library's features that depend on initialization being complete.

Returns

  • boolean: Returns true if initialization has completed, otherwise it returns false.

Example

// Check if the Sesamy library is ready
if (window.sesamy.isReady()) {
  // Safe to use Sesamy APIs that require initialization
  console.log('Sesamy is ready to use');
} else {
  console.log('Sesamy is still initializing');
}

You can also use it with an event listener to perform actions when the library is ready:

// Alternative approach using the ready event
window.addEventListener('sesamyJsReady', () => {
  // This will be true at this point
  console.log('Sesamy initialized status:', window.sesamy.isReady());
  // Perform actions that require Sesamy to be initialized
});

log(message: string)

Logs a message to the console, but only when debug mode is enabled. This is useful for debugging purposes without cluttering the console for end users.

Parameters

  • message (string): The message to log to the console.

Example

// Log a debug message
window.sesamy.log('Testing the checkout process');

Note

The log function only outputs messages when debug mode is enabled. Debug mode can be enabled by:

  1. Adding ?sesamy-debug=true to the URL
  2. Setting localStorage.debug = true

Auth API

isAuthenticated()

Checks if the user is currently authenticated. This function verifies the existence of a valid session by checking both the local storage for an access token and the state of the Auth0 client.

Returns

  • boolean: Returns true if the user is authenticated either via local storage tokens or the Auth0 client; otherwise, it returns false.

Example

The following example demonstrates how to check if a user is currently authenticated:

import { isAuthenticated } from '@sesamy/sesamy-js';

isAuthenticated()
  .then(isAuth => {
    if (isAuth) {
      console.log('User is authenticated.');
    } else {
      console.log('User is not authenticated.');
    }
  })
  .catch(error => {
    console.error('Error checking authentication status:', error);
  });

loginWithRedirect(options?: LoginWithRedirectOptions)

Initiates a login flow that redirects the user to an Auth0 hosted login page. Once the user authenticates, they will be redirected back to the specified redirect_uri within your application.

Parameters

  • options (optional): An object containing customization options for the login flow.
    • appState: (optional, object) Used to store state before doing the redirect.
    • authorizationParams: (optional, object) Additional parameters to include in the authorization request.
      • audience: (optional, string) The audience to request access to.
      • scope: (optional, string) The scope of the access request.
      • login_hint: (optional, string) A hint to pre-fill the username on the login page.
      • organization: (optional, string) The organization to authenticate with.
      • redirect_uri: (optional, string) The URL to redirect the user to after login.

Returns

This function returns a Promise that resolves when the redirect is successfully initiated.

Example

The following example demonstrates how to use loginWithRedirect to initiate a login flow with an email address pre-filled:

import { loginWithRedirect } from '@sesamy/sesamy-js';

// Optionally pass the user's email to pre-fill on the login form
const loginOptions = {
  authorizationParams: {
    login_hint: 'user@example.com',
  },
};

// Redirect the user to the login page
loginWithRedirect(loginOptions);

logout(options?: LogoutOptions)

Terminates the user's session and optionally redirects the user to a specified URL after logout. This function clears any local session tokens and interacts with the Auth0 API to end the session.

Parameters

  • options (optional): An object containing customization options for the logout process.
    • returnTo: (optional, string) The URL to redirect users to after logging out. Defaults to the current page URL if not provided.

Returns

This function does not return a value. It causes a redirect to the specified returnTo URL or performs a page refresh if no URL is provided.

Example

The following example demonstrates how to log out a user and redirect them to the homepage:

import { logout } from '@sesamy/sesamy-js';

// Specify the URL to redirect to after logout
const logoutOptions = {
  returnTo: 'https://www.yourdomain.com',
};
// Redirects the user to the auth server to log out
logout(logoutOptions);

setToken(accessToken: string, expiresIn?: number)

Stores the provided access token in local storage and optionally sets an expiration time for it. Additionally, this function parses the access token to extract user information and triggers an authentication event.

Parameters

  • accessToken (string): The access token to store and use for session management.
  • expiresIn (optional, number): The time in seconds from now when the token should expire.

Returns

This function does not return a value but triggers an event indicating that a user has been authenticated with the new token.

Example

The following example demonstrates how to store an access token and set an expiration time:

import { setToken } from '@sesamy/sesamy-js';

// Example access token and expiration period
const accessToken = 'your.access.token';
const expiresIn = 3600; // 1 hour in seconds

setToken(accessToken, expiresIn)
  .then(() => {
    console.log('Token set successfully and user authenticated.');
  })
  .catch(error => {
    console.error('Failed to set token:', error);
  });

Entitlements API

entitlements.get(entitlementId: string)

Fetches a specific entitlement by its ID.

Parameters

  • entitlementId (string): The ID of the entitlement to retrieve.

Returns

  • Promise<Entitlement | undefined>: The entitlement object if found, otherwise undefined.

Example

// Fetch a specific entitlement by its ID
window.sesamy.entitlements
  .get('entitlement-id')
  .then(entitlement => {
    if (entitlement) {
      console.log('Entitlement:', entitlement);
    } else {
      console.log('Entitlement not found');
    }
  })
  .catch(error => {
    console.error('Error fetching entitlement:', error);
  });

entitlements.list(params: GetEntitlementsOptions)

Fetches the list of entitlements, with optional filters and inclusion of signed links.

Parameters

  • params (GetEntitlementsOptions): Optional parameters for fetching entitlements.
    • includeSignedLinks (boolean, optional): Whether to include signed links. Default is true.
    • waitForEntitlementAfter (Date, optional): If provided, waits for an entitlement that is available after the given date.

Returns

  • Promise<Entitlement[]>: An array of entitlements.

Example

// Fetch all entitlements, including signed links
window.sesamy.entitlements
  .list({ includeSignedLinks: true })
  .then(entitlements => {
    console.log('Entitlements:', entitlements);
  })
  .catch(error => {
    console.error('Error fetching entitlements:', error);
  });

entitlements.access(entitlementId: string)

Fetches the access details for a specific entitlement by its ID.

Parameters

  • entitlementId (string): The ID of the entitlement to access.

Returns

  • Promise<Access>: The access details for the given entitlement.

Example

// Fetch access details for a specific entitlement
window.sesamy.entitlements
  .access('entitlement-id')
  .then(access => {
    console.log('Access details:', access);
  })
  .catch(error => {
    console.error('Error fetching entitlement access:', error);
  });

entitlements.signedLinks()

Fetches signed links for the current session's entitlements.

Parameters

None.

Returns

  • SignedLink[]: An array of signed links for the current entitlements.

Example

// Fetch signed links for the current entitlements
const signedLinks = window.sesamy.entitlements.signedLinks();
console.log('Signed links:', signedLinks);

Types

  • GetEntitlementsOptions: An object containing optional parameters for fetching entitlements.

    • includeSignedLinks (boolean, optional): Whether to include signed links. Defaults to true.
    • waitForEntitlementAfter (Date, optional): A date to filter entitlements that are available after the given date.
  • Entitlement: Represents an entitlement object.

  • Access: Represents the access details for an entitlement.

  • SignedLink: Represents a signed link for accessing an entitlement.

Services

getProfile()

Fetches the user's profile information from the Sesamy-hosted service. If the user is authenticated, the profile data will be retrieved.

Returns

Promise<Profile | null>: A promise that resolves to the user's profile information if the user is authenticated, otherwise it resolves to null.

Example

The following example demonstrates how to fetch the user's profile information:

import { getProfile } from '@sesamy/sesamy-js';

// Fetch the user's profile information
getProfile()
  .then(profile => {
    if (profile) {
      console.log('User profile:', profile);
    } else {
      console.log('User is not authenticated');
    }
  })
  .catch(error => {
    console.error('Error fetching profile:', error);
  });

Profile Type

export type Profile = {
  userId: string;
  firstName?: string;
  lastName?: string;
  emailVerified: boolean;
  email: string;
  name?: string;
  locale?: string;
  picture?: string;
  createdAt: string;
  updatedAt: string;
  mobilePhone?: string;
  tags: string[];
  user_metadata?: { [id: string]: string | number };
  billingAddress?: Address;
  deliveryAddress?: Address;
};

Address Type

export type Address = {
  street: string;
  co?: string;
  city: string;
  state: string;
  postalCode: string;
  country: string;
};

updateProfile(profile: Partial<Profile>)

Updates the user's profile information on the Sesamy-hosted service. After updating, the cache is cleared to ensure that the latest profile information is available.

Parameters

  • profile (Partial): An object containing the profile fields to be updated. Only the provided fields will be updated.

Returns

Promise<boolean>: A promise that resolves to true if the profile update is successful, otherwise false.

Example

The following example demonstrates how to update the user's profile information:

import { updateProfile } from '@sesamy/sesamy-js';

// Define the profile fields to be updated
const updatedProfile = {
  firstName: 'John',
  lastName: 'Doe',
  locale: 'en-US',
  mobilePhone: '+1234567890',
};

// Update the user's profile information
updateProfile(updatedProfile)
  .then(success => {
    if (success) {
      console.log('Profile updated successfully');
    } else {
      console.log('Profile update failed');
    }
  })
  .catch(error => {
    console.error('Error updating profile:', error);
  });

Profile Type

export type Profile = {
  userId: string;
  firstName?: string;
  lastName?: string;
  emailVerified: boolean;
  email: string;
  name?: string;
  locale?: string;
  picture?: string;
  createdAt: string;
  updatedAt: string;
  mobilePhone?: string;
  tags: string[];
  user_metadata?: { [id: string]: string | number };
  billingAddress?: Address;
  deliveryAddress?: Address;
};

Address Type

export type Address = {
  street: string;
  co?: string;
  city: string;
  state: string;
  postalCode: string;
  country: string;
};

generateLink(params: GenerateAccountLink | GenerateChangePaymentLink | GenerateConsumeLink | GenerateCheckoutLink | GenerateChangePlanLink)

Generates a link to a Sesamy-hosted service such as account or consume. If the user is authenticated, the link will be signed so that the user can access the service without logging in again.

Parameters

  • params (GenerateAccountLink | GenerateConsumeLink):

    • The parameters for generating the link. attribute. Common parameters:

      • target (string, required): The target service. Valid values:
        • 'account': Generate link to account page
        • 'change-payment': Generate link to payment change page
        • 'change-plan': Generate link to payment plan page
        • 'consume': Generate link to consume content
        • 'checkout': Generate link to checkout page
      • shorten (boolean, optional): If true, the link will be shortened
      • ttl (number, optional): The time-to-live for the shortened link in seconds
      • redirectUrl (string, optional): The URL to redirect to after the link is accessed
      • language (string, optional): The language for the link. Defaults to HTML element's lang attribute
    • Target-specific parameters: For target='consume':

      • sku (string, required): The SKU of the product to consume
      • episodeId (string, optional): The ID of the episode to consume
    • For target='change-payment|change-plan':

      • contractId (string, required): The ID of the contract to change payment or plan for

Returns

string: The generated link URL. If shorten is true, the shortened URL is returned.

Example

The following example demonstrates how to generate a link to the Sesamy account page:

import { generateLink } from '@sesamy/sesamy-js';

// Generate a link to the account page
const linkParams = {
  target: 'account',
  shorten: true,
  ttl: 3600, // 1 hour in seconds
  redirectUrl: 'https://www.yourdomain.com/account',
};

generateLink(linkParams)
  .then(link => {
    console.log('Generated link:', link);
  })
  .catch(error => {
    console.error('Error generating link:', error);
  });

And here is an example for generating a link to consume a specific product:

import { generateLink } from '@sesamy/sesamy-js';

// Generate a link to consume a product
const linkParams = {
  target: 'consume',
  sku: 'sid:eUv45QXTrcGNhMJpaCQNe',
  episodeId: 'episode-id',
  shorten: true,
  ttl: 3600, // 1 hour in seconds
  redirectUrl: 'https://www.yourdomain.com/consume',
};

generateLink(linkParams)
  .then(link => {
    console.log('Generated link:', link);
  })
  .catch(error => {
    console.error('Error generating link:', error);
  });

checkouts.create(params: CreateCheckoutParams)

Creates a checkout session with Sesamy. This function initializes a checkout process by sending the necessary parameters to the Sesamy API.

Parameters

  • params (CreateCheckoutParams): The parameters for creating the checkout session.
    • items (Array of objects): An array of items to be included in the checkout.
      • sku (string): The SKU of the product to be purchased.
      • purchaseOptionsId (string, optional): The ID of the purchase options for the product.
    • language (string, optional): The language for the checkout session. If not set, it will be automatically fetched from the HTML element's lang attribute.
    • redirectUrl (string, optional): The URL to redirect to after the checkout process is completed.
    • address (Address, optional): The address for the checkout session.
      • givenName: (string): The given name.
      • familyName: (string): The family name.
      • street (string): The street address.
      • city (string): The city.
      • zip (string): The postal code.
      • country (string): The country.
      • phoneNumber (string, optional): The phone number.
      • email (string, optional): The email address.
    • isBusiness (boolean, optional): Indicates if the checkout is for a business.
    • paymentMethodsFilter (Array of objects, optional): The payment methods to be available in the checkout. The payment methods are an object with a provider and a method property, where the method is an optional array.

Returns

Promise\<CheckoutResponse>: A promise that resolves to the response JSON object from the Sesamy API, which contains details about the created checkout session.

CheckoutResponse Schema

  • id (string): The unique identifier of the checkout session.
  • checkoutUrl (string): The URL for the checkout session.
  • status (enum): The status of the checkout session, can be 'PENDING' or 'PAID'.
  • createdAt (string): The creation timestamp of the checkout session.
  • modifiedAt (string): The last modified timestamp of the checkout session.
  • type (enum): The type of checkout session, currently only 'RECURRING' is supported.
  • currency (string): The currency used for the checkout session.
  • country (string): The country associated with the checkout session.
  • redirectUrl (string, optional): The URL to redirect to after the checkout process is completed.
  • email (string, optional): The email address for the checkout session.
  • language (string): The language used for the checkout session.
  • items (Array of objects): The items included in the checkout session.
    • sku (string): The SKU of the product.
    • purchaseOptionId (string, optional): The ID of the purchase option for the product.
    • title (string): The title of the product.
    • cover (string): The cover image URL of the product.
  • itemsOwned (Array of strings): The SKUs of the items already owned by the user.
  • discountCodes (Array of strings): The discount codes applied to the checkout session.
  • paymentOptions (Array of objects): The available payment options.
    • provider (string): The payment provider.
    • methods (Array of strings): The payment methods supported by the provider.

Example

The following example demonstrates how to create a checkout session with Sesamy:

import { createCheckout } from '@sesamy/sesamy-js';

// Create a checkout session with one item
const checkoutParams = {
  items: [
    {
      sku: 'sid:eUv45QXTrcGNhMJpaCQNe',
      purchaseOptionsId: 'option-id', // optional
    },
  ],
  language: 'en', // optional
};

createCheckout(checkoutParams)
  .then(response => {
    console.log('Checkout session created:', response);
  })
  .catch(error => {
    console.error('Error creating checkout session:', error);
  });

In this example, a checkout session is created with a single item specified by its SKU and an optional purchase options ID. The language is set to English ('en'), but if not provided, it will default to the language specified in the HTML lang attribute.

Additional Notes

  • The language parameter is optional. If it is not provided, the language will be determined using the getLanguage function, which fetches the language from the lang attribute of the HTML document element.
  • The items array must contain at least one item with a valid sku.

By using the createCheckout function, you can easily initialize a checkout process and handle the response from the Sesamy API to complete the transaction.

checkouts.update(id: string, params: Partial<CreateCheckoutParams>)

Updates a checkout session with Sesamy.

Parameters

  • params (Partial): The updated parameters for the checkout session.
    • items (Array of objects): An array of items to be included in the checkout.
      • sku (string): The SKU of the product to be purchased.
      • purchaseOptionsId (string, optional): The ID of the purchase options for the product.
    • language (string, optional): The language for the checkout session.
    • redirectUrl (string, optional): The URL to redirect to after the checkout process is completed.
    • email (string, optional): The email address for the checkout session.
    • address (Address, optional): The address for the checkout session.
      • givenName: (string): The given name.
      • familyName: (string): The family name.
      • street (string): The street address.
      • city (string): The city.
      • zip (string): The postal code.
      • country (string): The country.
      • phoneNumber (string, optional): The phone number.
      • email (string, optional): The email address.
    • isBusiness (boolean, optional): Indicates if the checkout is for a business.

Returns

Promise\<CheckoutResponse>: A promise that resolves to the response JSON object from the Sesamy API, which contains details about the updated checkout session.

CheckoutResponse Schema

  • id (string): The unique identifier of the checkout session.
  • checkoutUrl (string): The URL for the checkout session.
  • status (enum): The status of the checkout session, can be 'PENDING' or 'PAID'.
  • createdAt (string): The creation timestamp of the checkout session.
  • modifiedAt (string): The last modified timestamp of the checkout session.
  • type (enum): The type of checkout session, currently only 'RECURRING' is supported.
  • currency (string): The currency used for the checkout session.
  • country (string): The country associated with the checkout session.
  • language (string): The language used for the checkout session.
  • items (Array of objects): The items included in the checkout session.
    • sku (string): The SKU of the product.
    • purchaseOptionId (string, optional): The ID of the purchase option for the product.
    • title (string): The title of the product.
    • cover (string): The cover image URL of the product.
  • itemsOwned (Array of strings): The SKUs of the items already owned by the user.
  • discountCodes (Array of strings): The discount codes applied to the checkout session.
  • paymentOptions (Array of objects): The available payment options.
    • provider (string): The payment provider.
    • methods (Array of strings): The payment methods supported by the provider.

Example

The following example demonstrates how to create a checkout session with Sesamy:

import { updateCheckout } from '@sesamy/sesamy-js';

// Create a checkout session with one item
const checkoutParams = {
  email: 'test@example.com',
};

updateCheckout('checkoutId', checkoutParams)
  .then(response => {
    console.log('Checkout session updated:', response);
  })
  .catch(error => {
    console.error('Error updating checkout session:', error);
  });

In this example, a checkout session is created with a single item specified by its SKU and an optional purchase options ID. The language is set to English ('en'), but if not provided, it will default to the language specified in the HTML lang attribute.

Additional Notes

  • The language parameter is optional. If it is not provided, the language will be determined using the getLanguage function, which fetches the language from the lang attribute of the HTML document element.
  • The items array must contain at least one item with a valid sku.

By using the createCheckout function, you can easily initialize a checkout process and handle the response from the Sesamy API to complete the transaction.

checkouts.get(id: string)

Retrieves the details of a specific checkout session from Sesamy. This function fetches the checkout session information based on the provided checkout session ID.

Parameters

  • id (string): The unique identifier of the checkout session to retrieve.

Returns

Promise\<CheckoutResponse>: A promise that resolves to the response JSON object from the Sesamy API, which contains details about the requested checkout session.

CheckoutResponse Schema

  • id (string): The unique identifier of the checkout session.
  • checkoutUrl (string): The URL for the checkout session.
  • status (enum): The status of the checkout session, can be 'PENDING' or 'PAID'.
  • createdAt (string): The creation timestamp of the checkout session.
  • modifiedAt (string): The last modified timestamp of the checkout session.
  • type (enum): The type of checkout session, currently only 'RECURRING' is supported.
  • currency (string): The currency used for the checkout session.
  • country (string): The country associated with the checkout session.
  • language (string): The language used for the checkout session.
  • items (Array of objects): The items included in the checkout session.
    • sku (string): The SKU of the product.
    • purchaseOptionId (string, optional): The ID of the purchase option for the product.
    • title (string): The title of the product.
    • cover (string): The cover image URL of the product.
  • itemsOwned (Array of strings): The SKUs of the items already owned by the user.
  • discountCodes (Array of strings): The discount codes applied to the checkout session.
  • paymentOptions (Array of objects): The available payment options.
    • provider (string): The payment provider.
    • methods (Array of strings): The payment methods supported by the provider.

Example

The following example demonstrates how to retrieve the details of a specific checkout session with Sesamy:

import { getCheckout } from '@sesamy/sesamy-js';

// Retrieve the details of a checkout session by ID
const checkoutId = 'checkout-session-id';

getCheckout(checkoutId)
  .then(response => {
    console.log('Checkout session details:', response);
  })
  .catch(error => {
    console.error('Error retrieving checkout session:', error);
  });

In this example, the details of a specific checkout session are retrieved using its unique ID. The function returns a promise that resolves to the details of the checkout session.

Additional Notes

  • The id parameter is required and must be a valid checkout session identifier.

By using the getCheckout function, you can easily fetch the details of a specific checkout session from the Sesamy API to view or process the transaction information.

Browser API

detectAdblock()

Detects the presence of an ad blocker in the browser by dynamically creating and checking the visibility of several ad-related HTML elements.

Parameters

None

Returns

Promise: A promise that resolves to a boolean value indicating whether an ad blocker is enabled (true) or not (false).

Example

The following example demonstrates how to use the detectAdblock function to detect if an ad blocker is enabled:

import { detectAdblock } from '@sesamy/sesamy-js';

// Detect if an ad blocker is enabled
detectAdblock()
  .then(isAdblockEnabled => {
    if (isAdblockEnabled) {
      console.log('Adblocker is enabled');
    } else {
      console.log('Adblocker is not enabled');
    }
  })
  .catch(error => {
    console.error('Error detecting adblock:', error);
  });

Details

  • The function creates a set of HTML <div> elements with IDs typically used by ad containers (e.g., 'AdHeader', 'AdContainer', etc.).
  • These elements are appended to the body of the document and their visibility is checked after a short delay (100 milliseconds).

isIncognito()

Detects if the browser is running in incognito mode.

Parameters

None

Returns

Promise: A promise that resolves to a boolean value indicating whether the browser is running in incognito mode (true) or not (false).

Example

The following example demonstrates how to use the isIncognito function:

import { isIncognito } from '@sesamy/sesamy-js';

// Detect if browser is running in incognito mode
isIncognito().then(isIncognitoEnabled => {
  if (isIncognitoEnabled) {
    console.log('Incognito mode is enabled');
  } else {
    console.log('Incognito mode is not enabled');
  }
});

isInAppBrowser()

Detects if the current browsing context is an in-app browser and identifies the browser name if applicable.

Parameters

None

Returns

Object: An object containing two properties:

  • isInAppBrowser (boolean): Indicates whether the current browsing context is an in-app browser (true) or not (false).
  • browserName (string | null): The name of the in-app browser if detected, or null if not detected.

Example

The following example demonstrates how to use the isInAppBrowser function to check if the current context is an in-app browser and log the browser name if applicable:

import { isInAppBrowser } from '@sesamy/sesamy-js';

// Detect if the current context is an in-app browser
const result = isInAppBrowser();

if (result.isInAppBrowser) {
  console.log(`Running inside an in-app browser: ${result.browserName}`);
} else {
  console.log('Not running inside an in-app browser');
}

Details

  • A predefined list of common in-app browsers (e.g., Facebook, Instagram, LinkedIn, etc.) is checked against the user agent.
  • If a match is found, the function returns isInAppBrowser: true and the corresponding browserName.
  • If no known in-app browser signatures are detected, the function returns isInAppBrowser: false and browserName: null.

Transforms

The transform module allows for dynamic content manipulation based on specified rules. This can include inserting, replacing, or removing elements on a webpage.

Configuration

The transform configuration is defined within the Config interface. The following properties are available:

  • enabled (boolean, optional): Enables or disables the transform module.
  • rules (array): An array of rule objects that define the transformations to apply.

Each rule object contains the following properties:

  • selector (string): A CSS selector to target elements on the page.
  • transform (string): The type of transformation to apply. Valid values are 'insert', 'replace', 'remove', 'gradient', and 'wrap'.
  • content (string, optional): The content to insert or replace. Required for 'insert' and 'replace' transforms.
  • 'insertPosition' (string, optional): The position to insert the content. Valid values are 'before', 'after' and 'insider'.
  • contentType (string, optional): Specifies the type of content. Valid values are 'html', 'selector', and 'url'.
  • path (string, optional): A regular expression to match the URL path. If provided, the rule will only apply when the path matches the current URL.
  • entitlement (string, optional): Specifies an entitlement required for the rule to apply.
  • authenticated (boolean, optional): Specifies if the rule should only apply to authenticated users.

Example Configuration

Below is an example configuration for the transform module:

{
  "transform": {
    "enabled": true,
    "rules": [
      {
        "selector": "#example",
        "transform": "replace",
        "content": "<p>New content</p>",
        "contentType": "html"
      },
      {
        "selector": ".ad-banner",
        "transform": "remove"
      },
      {
        "selector": ".insert-content",
        "transform": "insert",
        "content": "#source-element",
        "contentType": "selector"
      },
      {
        "selector": ".load-from-url",
        "transform": "insert",
        "content": "https://example.com/content",
        "contentType": "url"
      }
    ]
  }
}

Usage

To use the transform module, include the configuration in your initialization script:

<script type="application/json" id="sesamy-js">
  {
    "clientId": "demo",
    "transform": {
      "enabled": true,
      "rules": [
        {
          "selector": "#example",
          "transform": "replace",
          "content": "<p>New content</p>",
          "contentType": "html"
        },
        {
          "selector": ".ad-banner",
          "transform": "remove"
        },
        {
          "selector": ".insert-content",
          "transform": "insert",
          "content": "#source-element",
          "contentType": "selector"
        },
        {
          "selector": ".load-from-url",
          "transform": "insert",
          "content": "https://example.com/content",
          "contentType": "url"
        }
      ]
    }
  }
</script>

This configuration will replace the content of the element with the ID example, remove elements with the class ad-banner, insert the content of the element with the ID source-element into elements with the class insert-content, and load content from a URL into elements with the class load-from-url.

Content

The content module allows you to extract dynamic article data from a webpage based on specific selectors. This can include elements like the title, image, excerpt, price, and more.

content.getPropertyFromHTML(options: { publisherContentId?: string, key: string, defaultValue?: string })

Searches for a specified property in the HTML content, following a specific lookup hierarchy:

  1. First, it looks for a <sesamy-content-data> element with the given publisherContentId and checks for the property as an attribute.
  2. If not found, it checks for meta tags in the document head with the formats sesamy:{key}, og:{key}, or just {key}.
  3. If still not found, it returns the provided default value (empty string if no default specified).

Parameters

  • options (object): Options for retrieving the property.
    • publisherContentId (string, optional): The ID of the content to search for.
    • key (string): The name of the property to retrieve.
    • defaultValue (string, optional): The default value to return if the property is not found. Defaults to an empty string.

Returns

  • string: The value of the property if found, or the default value.

Example

// Get the title from HTML content
const title = window.sesamy.content.getPropertyFromHTML({
  publisherContentId: 'article-123',
  key: 'title',
  defaultValue: 'Untitled Article',
});

console.log('Article title:', title);

Configuration

The content configuration is defined within the Config json. The following properties are available:

  • article (object): Defines the selector for the article element itself.
  • image (object): Specifies the selector and attribute for extracting article images.
  • title (object): Specifies the selector and attribute for extracting the article title.
  • excerpt (object): Specifies the selector and attribute for extracting the article excerpt.
  • price (object): Specifies the selector and attribute for extracting the article price.
  • currency (object): Specifies the selector and attribute for extracting the article currency.
  • url (object): Specifies the selector and attribute for extracting the article URL.
  • id (object): Specifies the selector and attribute for extracting the article ID.

Each field object contains the following properties:

  • selector (string): A CSS selector to target elements on the page.
  • attribute (string, optional): The attribute to retrieve from the selected element. If not specified, the text content of the element is used.

Example Configuration

Below is an example configuration for the content module:

{
  "content": {
    "article": {
      "selector": "article"
    },
    "image": {
      "selector": "img",
      "attribute": "src"
    },
    "title": {
      "selector": "h1",
      "attribute": "textContent"
    },
    "excerpt": {
      "selector": "p",
      "attribute": "textContent"
    },
    "price": {
      "selector": "article",
      "attribute": "data-price"
    },
    "currency": {
      "selector": "article",
      "attribute": "data-currency"
    },
    "url": {
      "selector": "link",
      "attribute": "href"
    },
    "id": {
      "selector": "article",
      "attribute": "data-id"
    }
  }
}

Usage

To use the content module, initialize it with the appropriate configuration:

import { init } from '@sesamy/sesamy-js';

init({
  content: {
    article: { selector: 'article' },
    image: { selector: 'img', attribute: 'src' },
    title: { selector: 'h1', attribute: 'textContent' },
    excerpt: { selector: 'p', attribute: 'textContent' },
    price: { selector: 'article', attribute: 'data-price' },
    currency: { selector: 'article', attribute: 'data-currency' },
    url: { selector: 'link', attribute: 'href' },
    id: { selector: 'article', attribute: 'data-id' },
  },
});

Methods

list()

Returns an array of article objects containing the extracted data for each article on the page.

Each article object contains the following properties:

  • title (string, optional): The title of the article.
  • excerpt (string, optional): The article's excerpt.
  • image (string, optional): The source URL of the article's image.s
  • price (number, optional): The price of the article.
  • currency (string, optional): The currency of the article price.
  • url (string, optional): The URL of the article.
  • id (string, optional): The article's unique ID.
  • element (Element): The original DOM element for the article.

Example Usage

import { init } from '@sesamy/sesamy-js';

const sesamyjs = await init({ ...config });

// Extract and log all content
const articles = sesamy.content.list();
console.log(articles);

In this example, content.list() will return an array of articles extracted from the page based on the configured selectors. Each article object contains fields such as title, excerpt, image, price, currency, URL, and ID.

Flags API

The Flags API allows for client-side feature flag management. These flags are stored in the browser's localStorage and can be used to enable or disable features for specific users.

flags.get(key: string)

Retrieves the value of a specific feature flag.

Parameters

  • key (string): The name of the flag to retrieve.

Returns

  • Promise<boolean | string | number | undefined>: A promise that resolves to the flag's value if found, or undefined if the flag doesn't exist.

Example

// Check if a specific feature flag is enabled
window.sesamy.flags.get('my-feature-flag').then(value => {
  if (value === true) {
    console.log('Feature is enabled');
  } else {
    console.log('Feature is disabled or not set');
  }
});

flags.set(key: string, value: boolean | string | number)

Sets the value of a specific feature flag.

Parameters

  • key (string): The name of the flag to set.
  • value (boolean | string | number): The value to assign to the flag.

Returns

  • Promise<void>: A promise that resolves when the flag has been set.

Example

// Enable a feature flag
window.sesamy.flags.set('my-feature-flag', true).then(() => {
  console.log('Feature flag has been enabled');
});

// Set a numeric flag value
window.sesamy.flags.set('max-items', 5).then(() => {
  console.log('Max items value has been set');
});

flags.list()

Retrieves all feature flags.

Returns

  • Promise<Record<string, boolean | string | number>>: A promise that resolves to an object containing all flag key-value pairs.

Example

// List all feature flags
window.sesamy.flags.list().then(flags => {
  console.log('All feature flags:', flags);
});

flags.delete(key: string)

Deletes a specific feature flag.

Parameters

  • key (string): The name of the flag to delete.

Returns

  • Promise<void>: A promise that resolves when the flag has been deleted.

Example

// Delete a feature flag
window.sesamy.flags.delete('my-feature-flag').then(() => {
  console.log('Feature flag has been deleted');
});

Amendments API

The Amendments API allows for managing contract amendments, such as adding discounts to existing contracts.

amendments.create(params: { contractId: string; discountCode: string; amendmentType: 'DISCOUNT' })

Creates an amendment for a contract, such as applying a discount code.

Parameters

  • params (object): The parameters for creating the amendment.
    • contractId (string): The ID of the contract to amend.
    • discountCode (string): The discount code to apply.
    • amendmentType (string): The type of amendment, currently only 'DISCOUNT' is supported.

Returns

  • Promise<object>: A promise that resolves to the created amendment object.

Example

// Apply a discount code to a contract
window.sesamy.amendments
  .create({
    contractId: 'contract-123',
    discountCode: 'SUMMER2023',
    amendmentType: 'DISCOUNT',
  })
  .then(amendment => {
    console.log('Amendment created:', amendment);
  })
  .catch(error => {
    console.error('Error creating amendment:', error);
  });

amendments.confirm(amendmentId: string)

Confirms a previously created amendment.

Parameters

  • amendmentId (string): The ID of the amendment to confirm.

Returns

  • Promise<boolean>: A promise that resolves to true if the amendment was successfully confirmed.

Example

// Confirm an amendment
window.sesamy.amendments
  .confirm('amendment-123')
  .then(success => {
    if (success) {
      console.log('Amendment confirmed successfully');
    }
  })
  .catch(error => {
    console.error('Error confirming amendment:', error);
  });

Products API

The Products API provides methods for working with Sesamy products, including retrieving product information and linking accounts.

products.get(sku: string)

Retrieves detailed information about a product by its SKU.

Parameters

  • sku (string): The Stock Keeping Unit (SKU) identifier for the product.

Returns

  • Promise<Product>: A promise that resolves to the product object.

Example

// Get product information by SKU
window.sesamy.products
  .get('sid:eUv45QXTrcGNhMJpaCQNe')
  .then(product => {
    console.log('Product details:', product);
    console.log('Product name:', product.name);
    console.log('Product price:', product.price);
  })
  .catch(error => {
    console.error('Error fetching product:', error);
  });

products.autoOnboard(sku: string)

Triggers the auto-onboarding process for a product by SKU, which helps users get started with a product they've purchased.

Parameters

  • sku (string): The Stock Keeping Unit (SKU) identifier for the product.

Returns

  • Promise<boolean>: A promise that resolves to true if the auto-onboarding process was successfully initiated.

Example

// Trigger auto-onboarding for a product
window.sesamy.products
  .autoOnboard('sid:eUv45QXTrcGNhMJpaCQNe')
  .then(success => {
    if (success) {
      console.log('Auto-onboarding process initiated successfully');
    }
  })
  .catch(error => {
    console.error('Error triggering auto-onboarding:', error);
  });

products.linkSpotify()

Links a user's Spotify account to enable Sesamy products that integrate with Spotify.

Returns

  • Promise<boolean>: A promise that resolves to true if the Spotify account was successfully linked.

Example

// Link the user's Spotify account
window.sesamy.products
  .linkSpotify()
  .then(success => {
    if (success) {
      console.log('Spotify account linked successfully');
    }
  })
  .catch(error => {
    console.error('Error linking Spotify account:', error);
  });

Tags API

The Tags API allows for managing user tags, which can be used for user segmentation and personalization.

tags.list()

Fetches all tags associated with the current user.

Returns

  • Promise<string[]>: A promise that resolves to an array of tag strings.

Example

// Get all tags for the current user
window.sesamy.tags
  .list()
  .then(tags => {
    console.log('User tags:', tags);
  })
  .catch(error => {
    console.error('Error fetching tags:', error);
  });

tags.set(tag: string)

Sets a tag for the current user. If the tag already exists, it won't create a duplicate.

Parameters

  • tag (string): The tag to associate with the user.

Returns

  • Promise<boolean>: A promise that resolves to true if the tag was successfully set.

Example

// Set a tag for the current user
window.sesamy.tags
  .set('premium-subscriber')
  .then(success => {
    if (success) {
      console.log('Tag set successfully');
    }
  })
  .catch(error => {
    console.error('Error setting tag:', error);
  });

tags.delete(tag: string)

Deletes a specific tag from the current user.

Parameters

  • tag (string): The tag to remove from the user.

Returns

  • Promise<boolean>: A promise that resolves to true if the tag was successfully deleted.

Example

// Delete a tag from the current user
window.sesamy.tags
  .delete('trial-user')
  .then(success => {
    if (success) {
      console.log('Tag deleted successfully');
    }
  })
  .catch(error => {
    console.error('Error deleting tag:', error);
  });

Tallies API

The Tallies API allows for tracking counts of various user activities or metrics.

tallies.list()

Lists all tallies for the current user.

Returns

  • Promise<Tally[]>: A promise that resolves to an array of tally objects.

Example

// List all tallies for the current user
window.sesamy.tallies
  .list()
  .then(tallies => {
    console.log('User tallies:', tallies);
  })
  .catch(error => {
    console.error('Error listing tallies:', error);
  });

tallies.get(id: string)

Retrieves a specific tally by its ID.

Parameters

  • id (string): The ID of the tally to retrieve.

Returns

  • Promise<Tally>: A promise that resolves to the tally object.

Example

// Get a specific tally by ID
window.sesamy.tallies
  .get('article-views')
  .then(tally => {
    console.log('Tally:', tally);
    console.log('Current count:', tally.count);
  })
  .catch(error => {
    console.error('Error getting tally:', error);
  });

tallies.push(id: string, item: any)

Adds an item to a specific tally, incrementing its count.

Parameters

  • id (string): The ID of the tally to update.
  • item (any): The item to add to the tally.

Returns

  • Promise<Tally>: A promise that resolves to the updated tally object.

Example

// Increment an article view tally
window.sesamy.tallies
  .push('article-views', { articleId: 'sid:eUv45QXTrcGNhMJpaCQNe', timestamp: new Date() })
  .then(updatedTally => {
    console.log('Updated tally:', updatedTally);
    console.log('New count:', updatedTally.count);
  })
  .catch(error => {
    console.error('Error updating tally:', error);
  });

tallies.delete(id: string)

Deletes a specific tally by its ID.

Parameters

  • id (string): The ID of the tally to delete.

Returns

  • Promise<boolean>: A promise that resolves to true if the tally was successfully deleted.

Example

// Delete a specific tally
window.sesamy.tallies
  .delete('article-views')
  .then(success => {
    if (success) {
      console.log('Tally deleted successfully');
    }
  })
  .catch(error => {
    console.error('Error deleting tally:', error);
  });

User Metadata API

The User Metadata API allows for storing and retrieving custom metadata associated with users.

userMetadata.list()

Lists all metadata items for the current user.

Returns

  • Promise<Record<string, any>>: A promise that resolves to an object containing all metadata key-value pairs.

Example

// List all user metadata
window.sesamy.userMetadata
  .list()
  .then(metadata => {
    console.log('User metadata:', metadata);
  })
  .catch(error => {
    console.error('Error listing user metadata:', error);
  });

userMetadata.get(id: string)

Retrieves a specific metadata item by its ID.

Parameters

  • id (string): The ID of the metadata item to retrieve.

Returns

  • Promise<any>: A promise that resolves to the value of the metadata item.

Example

// Get a specific metadata item
window.sesamy.userMetadata
  .get('preferences')
  .then(value => {
    console.log('User preferences:', value);
  })
  .catch(error => {
    console.error('Error getting metadata:', error);
  });

userMetadata.set(id: string, value: any)

Sets a metadata item for the current user.

Parameters

  • id (string): The ID of the metadata item to set.
  • value (any): The value to assign to the metadata item.

Returns

  • Promise<boolean>: A promise that resolves to true if the metadata item was successfully set.

Example

// Set a user preference metadata item
window.sesamy.userMetadata
  .set('preferences', { theme: 'dark', fontSize: 'large' })
  .then(success => {
    if (success) {
      console.log('User preferences saved successfully');
    }
  })
  .catch(error => {
    console.error('Error setting metadata:', error);
  });

userMetadata.delete(id: string)

Deletes a specific metadata item by its ID.

Parameters

  • id (string): The ID of the metadata item to delete.

Returns

  • Promise<boolean>: A promise that resolves to true if the metadata item was successfully deleted.

Example

// Delete a metadata item
window.sesamy.userMetadata
  .delete('temporary-setting')
  .then(success => {
    if (success) {
      console.log('Metadata item deleted successfully');
    }
  })
  .catch(error => {
    console.error('Error deleting metadata:', error);
  });

Vendors API

The Vendors API provides methods for retrieving information about vendors (publishers) connected to a user.

vendors.get()

Fetches settings for the current vendor based on the authenticated user context.

Returns

  • Promise<VendorSettings>: A promise that resolves to the vendor settings object.

Example

// Get current vendor settings
window.sesamy.vendors
  .get()
  .then(settings => {
    console.log('Vendor settings:', settings);
    console.log('Vendor name:', settings.name);
    console.log('Vendor currency:', settings.currency);
  })
  .catch(error => {
    console.error('Error fetching vendor settings:', error);
  });

vendors.list()

Lists all publishers connected to the user. This method is not available for publisher tokens.

Returns

  • Promise<Vendor[]>: A promise that resolves to an array of vendor objects.

Example

// List all vendors connected to the user
window.sesamy.vendors
  .list()
  .then(vendors => {
    console.log('Connected vendors:', vendors);
    vendors.forEach(vendor => {
      console.log('Vendor name:', vendor.name);
      console.log('Vendor ID:', vendor.id);
    });
  })
  .catch(error => {
    console.error('Error listing vendors:', error);
  });

Contracts API

The Contracts API provides methods for managing user contracts, including subscription services.

contracts.list()

Lists all contracts associated with the current user.

Returns

  • Promise<Contract[]>: A promise that resolves to an array of contract objects.

Example

// List all user contracts
window.sesamy.contracts
  .list()
  .then(contracts => {
    console.log('User contracts:', contracts);
    contracts.forEach(contract => {
      console.log('Contract ID:', contract.id);
      console.log('Contract status:', contract.status);
      console.log('Contract start date:', contract.startDate);
    });
  })
  .catch(error => {
    console.error('Error listing contracts:', error);
  });

contracts.get(id: string)

Retrieves a specific contract by its ID.

Parameters

  • id (string): The ID of the contract to retrieve.

Returns

  • Promise<Contract>: A promise that resolves to the contract object.

Example

// Get a specific contract by ID
window.sesamy.contracts
  .get('contract-123')
  .then(contract => {
    console.log('Contract details:', contract);
    console.log('Contract status:', contract.status);
    console.log('Contract type:', contract.type);
  })
  .catch(error => {
    console.error('Error fetching contract:', error);
  });

contracts.cancel(id: string)

Cancels a specific contract by its ID.

Parameters

  • id (string): The ID of the contract to cancel.

Returns

  • Promise<Contract>: A promise that resolves to the updated contract object with its status set to canceling or canceled.

Example

// Cancel a contract
window.sesamy.contracts
  .cancel('contract-123')
  .then(contract => {
    console.log('Contract canceled successfully');
    console.log('Updated contract status:', contract.status);
  })
  .catch(error => {
    console.error('Error canceling contract:', error);
  });

Bills API

The Bills API allows for retrieving information about user bills.

bills.list()

Lists all bills associated with the current user.

Returns

  • Promise<Bill[]>: A promise that resolves to an array of bill objects.

Example

// List all user bills
window.sesamy.bills
  .list()
  .then(bills => {
    console.log('User bills:', bills);
    bills.forEach(bill => {
      console.log('Bill ID:', bill.id);
      console.log('Amount:', bill.amount);
      console.log('Due date:', bill.dueDate);
      console.log('Status:', bill.status);
    });
  })
  .catch(error => {
    console.error('Error listing bills:', error);
  });

bills.get(id: string)

Retrieves a specific bill by its ID.

Parameters

  • id (string): The ID of the bill to retrieve.

Returns

  • Promise<Bill>: A promise that resolves to the bill object.

Example

// Get a specific bill by ID
window.sesamy.bills
  .get('bill-123')
  .then(bill => {
    console.log('Bill details:', bill);
    console.log('Amount:', bill.amount);
    console.log('Status:', bill.status);
    console.log('Due date:', bill.dueDate);
  })
  .catch(error => {
    console.error('Error fetching bill:', error);
  });

Transactions API

The Transactions API allows for retrieving information about user transactions.

transactions.list()

Lists all transactions associated with the current user.

Returns

  • Promise<Transaction[]>: A promise that resolves to an array of transaction objects.

Example

// List all user transactions
window.sesamy.transactions
  .list()
  .then(transactions => {
    console.log('User transactions:', transactions);
    transactions.forEach(transaction => {
      console.log('Transaction ID:', transaction.id);
      console.log('Amount:', transaction.amount);
      console.log('Date:', transaction.createdAt);
      console.log('Status:', transaction.status);
    });
  })
  .catch(error => {
    console.error('Error listing transactions:', error);
  });

transactions.get(id: string)

Retrieves a specific transaction by its ID.

Parameters

  • id (string): The ID of the transaction to retrieve.

Returns

  • Promise<Transaction>: A promise that resolves to the transaction object.

Example

// Get a specific transaction by ID
window.sesamy.transactions
  .get('transaction-123')
  .then(transaction => {
    console.log('Transaction details:', transaction);
    console.log('Amount:', transaction.amount);
    console.log('Status:', transaction.status);
    console.log('Date:', transaction.createdAt);
  })
  .catch(error => {
    console.error('Error fetching transaction:', error);
  });

Polyfills

The library polyfills the following methods for compatibility with older browsers:

  • URL
  • URLSearchParams
  • fetch

Notes

  • The content property is required for 'insert' and 'replace' transforms.
  • The contentType property specifies how to interpret the content property: as raw HTML, a CSS selector, or a URL to fetch content from.
  • The path property can be used to apply rules conditionally based on the current URL.
  • The authenticated property ensures that rules only apply to authenticated users if set to true.

Attribution

The library tracks the following data for attribution purposes and pass it on to the checkout when initiating a purchase:

  • utm_source: The source of the traffic.
  • utm_medium: The medium of the traffic.
  • utm_campaign: The campaign associated with the traffic.
  • utm_term: The term associated with the traffic.
  • utm_content: The content associated with the traffic.
  • ref: The referrer passed in the querystring.
  • referrer: The referrer URL of the initial page load.
  • item-src: The url of the last locked article viewed.

Events API

The Events API allows for emitting custom events that can be listened to and optionally canceled by other scripts on the page.

events.emit(eventName: string, data?: Record<string, any>, cancelable?: boolean)

Emits a custom event that can optionally be canceled by event listeners.

Parameters

  • eventName (string): The name of the event to emit.
  • data (Record<string, any>, optional): Additional data to include with the event.
  • cancelable (boolean, optional): Whether the event can be canceled by listeners. Defaults to false.

Returns

  • { canceled: boolean, message?: string }: An object indicating if the event was canceled and any cancellation message.

Example

// Emit a non-cancelable event
window.sesamy.events.emit('article-viewe
1.33.3

5 months ago

1.33.4

5 months ago

1.33.1

5 months ago

1.33.2

5 months ago

1.29.0

8 months ago

1.32.0

7 months ago

1.32.1

7 months ago

1.34.2

4 months ago

1.34.3

4 months ago

1.34.0

5 months ago

1.34.1

4 months ago

1.34.6

3 months ago

1.34.7

3 months ago

1.34.4

4 months ago

1.34.5

4 months ago

1.33.0

6 months ago

1.35.1

3 months ago

1.35.2

3 months ago

1.35.0

3 months ago

1.35.5

3 months ago

1.35.6

2 months ago

1.35.3

3 months ago

1.35.4

3 months ago

1.35.9

2 months ago

1.35.7

2 months ago

1.35.8

2 months ago

1.35.10

2 months ago

1.27.0

8 months ago

1.30.0

7 months ago

1.30.1

7 months ago

1.36.0

1 month ago

1.32.4

7 months ago

1.36.1

1 month ago

1.32.5

6 months ago

1.32.2

7 months ago

1.32.3

7 months ago

1.36.2

28 days ago

1.32.6

6 months ago

1.28.1

8 months ago

1.28.2

8 months ago

1.28.0

8 months ago

1.28.3

8 months ago

1.31.1

7 months ago

1.31.0

7 months ago

1.25.0

8 months ago

1.25.1

8 months ago

1.25.2

8 months ago

1.26.0

8 months ago

1.26.1

8 months ago

1.24.1

8 months ago

1.24.0

8 months ago

1.23.0

8 months ago

1.23.1

8 months ago

1.22.7

9 months ago

1.22.8

9 months ago

1.22.9

9 months ago

1.22.0

9 months ago

1.22.3

9 months ago

1.22.4

9 months ago

1.22.1

9 months ago

1.22.2

9 months ago

1.22.5

9 months ago

1.22.6

9 months ago

1.21.8

9 months ago

1.21.9

9 months ago

1.14.0

1 year ago

1.18.1

12 months ago

1.18.0

12 months ago

1.16.0

12 months ago

1.19.10

11 months ago

1.18.3

11 months ago

1.19.11

11 months ago

1.18.2

11 months ago

1.21.0

10 months ago

1.21.1

10 months ago

1.21.4

10 months ago

1.21.5

9 months ago

1.21.2

10 months ago

1.21.3

10 months ago

1.21.6

9 months ago

1.21.7

9 months ago

1.15.0

1 year ago

1.19.0

11 months ago

1.13.6

1 year ago

1.13.5

1 year ago

1.17.0

12 months ago

1.13.4

1 year ago

1.15.1

1 year ago

1.13.3

1 year ago

1.19.4

11 months ago

1.19.3

11 months ago

1.19.2

11 months ago

1.19.1

11 months ago

1.13.7

1 year ago

1.19.8

11 months ago

1.19.7

11 months ago

1.19.6

11 months ago

1.19.5

11 months ago

1.19.9

11 months ago

1.20.1

10 months ago

1.20.2

10 months ago

1.20.0

10 months ago

1.13.2

1 year ago

1.13.1

1 year ago

1.13.0

1 year ago

1.12.1

1 year ago

1.12.0

1 year ago

1.11.0

1 year ago

1.10.4

1 year ago

1.10.3

1 year ago

1.10.2

1 year ago

1.10.1

1 year ago

1.10.0

1 year ago

1.9.0

1 year ago

1.8.1

1 year ago

1.7.2

1 year ago

1.8.0

1 year ago

1.7.1

1 year ago

1.7.0

1 year ago

1.6.2

1 year ago

1.6.1

1 year ago

1.6.0

1 year ago

1.5.1

1 year ago

1.5.0

1 year ago

1.4.3

1 year ago

1.4.2

1 year ago

1.4.1

1 year ago

1.4.0

1 year ago

1.3.15

1 year ago

1.3.14

1 year ago

1.3.7

1 year ago

1.3.10

1 year ago

1.3.9

1 year ago

1.3.8

1 year ago

1.3.13

1 year ago

1.3.11

1 year ago

1.3.12

1 year ago

1.2.0

1 year ago

1.3.6

1 year ago

1.3.5

1 year ago

1.3.4

1 year ago

1.3.3

1 year ago

1.3.2

1 year ago

1.3.1

1 year ago

1.3.0

1 year ago

1.1.0

1 year ago

1.0.4

1 year ago

1.0.3

1 year ago

1.0.2

1 year ago

1.0.1

1 year ago

1.0.0

1 year ago