### Open Freemius Checkout Popup (JavaScript) Source: https://context7.com/freemius/freemius-checkout-js/llms.txt Shows how to trigger the Freemius checkout popup. Includes examples for a simple checkout, opening with specific plan and license configurations, and a comprehensive example with user prefill data, callbacks for purchase completion, success, cancellation, tracking, and lifecycle events. Supports async/await for better control. ```javascript // Simple checkout open handler.open(); // Open with specific plan configuration handler.open({ plan_id: 9999, licenses: 5, billing_cycle: 'annual', coupon: 'LAUNCH50', }); // Complete example with user prefill and callbacks handler.open({ name: 'My Awesome Plugin', plan_id: 1234, licenses: 1, billing_cycle: 'monthly', user_email: 'customer@example.com', user_firstname: 'John', user_lastname: 'Doe', trial: true, currency: 'usd', hide_coupon: false, purchaseCompleted: (response) => { console.log('Purchase completed:', response); if (response.purchase) { console.log('License Key:', response.purchase.license_id); console.log('Amount:', response.purchase.initial_amount); } console.log('User Email:', response.user.email); }, success: (response) => { console.log('User clicked "Got It" button:', response); // Redirect to success page window.location.href = '/thank-you'; }, cancel: () => { console.log('User closed the checkout'); }, track: (event, data) => { console.log('Tracking event:', event, data); // Send to analytics if (typeof gtag !== 'undefined') { gtag('event', event, data); } }, afterOpen: () => { console.log('Checkout popup opened'); }, afterClose: () => { console.log('Checkout popup closed'); }, onExitIntent: () => { console.log('User attempted to exit'); }, }); // Async/await pattern for timing control async function openCheckout() { await handler.open({ plan_id: 9999, licenses: 1, }); console.log('Checkout popup is now fully open'); } ``` -------------------------------- ### Install Freemius Checkout SDK using npm or yarn Source: https://github.com/freemius/freemius-checkout-js/blob/main/README.md Installs the Freemius Checkout SDK package using either npm or yarn. This is the first step to using the SDK in a bundled JavaScript application. ```bash npm i @freemius/checkout # If using yarn yarn add @freemius/checkout ``` -------------------------------- ### Include Freemius Checkout CDN Script with Event Listeners Source: https://github.com/freemius/freemius-checkout-js/blob/main/README.md An example of how to embed the Freemius Checkout CDN script in an HTML file, including the necessary setup for `paymentMethodUpdateEvents`. ```html ``` -------------------------------- ### Utility Functions for Checkout Operations Source: https://context7.com/freemius/freemius-checkout-js/llms.txt Collection of helper functions for common checkout tasks including GUID generation, query parameter conversion, boolean parsing, browser detection, and exit attempt detection. These utilities facilitate checkout option serialization, query string building, and user interaction tracking. ```javascript import { generateGuid, convertCheckoutOptionsToQueryParams, buildFreemiusQueryFromOptions, getBoolFromQueryParam, isQueryItemInvalid, getIsFlashingBrowser, isExitAttempt, MAX_ZINDEX, } from '@freemius/checkout'; // Generate unique identifier const guid = generateGuid(); console.log('GUID:', guid); // "a1b2-c3d4-e5f6-..." // Convert options to query parameters const params = convertCheckoutOptionsToQueryParams({ plan_id: 1234, licenses: 5, trial: true, sandbox: { ctx: '123', token: 'abc' }, }); console.log(params); // { plan_id: '1234', licenses: '5', trial: '1', s_ctx_ts: '123', sandbox: 'abc' } // Build query string const queryString = buildFreemiusQueryFromOptions({ plan_id: 1234, licenses: 5, billing_cycle: 'annual', }); console.log(queryString); // "plan_id=1234&licenses=5&billing_cycle=annual" // Parse boolean from query parameter const isTrial = getBoolFromQueryParam('1'); // true const isNotTrial = getBoolFromQueryParam('false'); // false // Detect flashing browsers (IE, Safari) if (getIsFlashingBrowser()) { console.log('Browser may have flash issues'); } // Detect exit attempt from mouse event document.addEventListener('mousemove', (event) => { if (isExitAttempt(event)) { console.log('User attempting to exit'); } }); // Maximum z-index value console.log('Max z-index:', MAX_ZINDEX); // 2147483647 ``` -------------------------------- ### Open Freemius Checkout with Event Listener (JavaScript) Source: https://github.com/freemius/freemius-checkout-js/blob/main/README.md Example of attaching an event listener to a purchase button to open the Freemius checkout handler. Includes callback functions for `purchaseCompleted` and `success` events. The `preventDefault()` call is important to stop the default form submission. ```javascript document.querySelector('#purchase').addEventListener('click', (e) => { handler.open({ name: 'My Awesome Plugin', licenses: getSelectedLicenses(), // You can consume the response for after purchase logic. purchaseCompleted: function (response) { // The logic here will be executed immediately after the purchase confirmation. // alert(response.user.email); }, success: function (response) { // The logic here will be executed after the customer closes the checkout, after a successful purchase. // alert(response.user.email); }, }); e.preventDefault(); }); ``` -------------------------------- ### Close Freemius Checkout Popup Programmatically (JavaScript) Source: https://context7.com/freemius/freemius-checkout-js/llms.txt Provides code examples for closing the Freemius checkout popup from your application's JavaScript code. It demonstrates a direct call to the `close()` method and an example using `setTimeout` to automatically close the checkout after a specified delay. ```javascript // Close the checkout handler.close(); // Example: Auto-close after timeout handler.open({ plan_id: 1234 }); setTimeout(() => { handler.close(); console.log('Checkout closed after timeout'); }, 30000); // 30 seconds ``` -------------------------------- ### Freemius Checkout SDK with Async/Defer and Load Event Source: https://github.com/freemius/freemius-checkout-js/blob/main/README.md Demonstrates loading the Freemius Checkout SDK via CDN using `async` and `defer` attributes, and initializing the checkout handler within a `window.addEventListener('load', ...)` callback to ensure the script has finished loading. ```html ``` -------------------------------- ### Advanced Checkout Configuration with Multiple Options Source: https://context7.com/freemius/freemius-checkout-js/llms.txt Demonstrates multiple checkout scenarios including trial checkout, license renewal, payment method updates, bundle configurations, readonly user flows, and advanced customization options. The Checkout handler accepts a configuration object with product_id and public_key, then opens checkout with scenario-specific parameters. ```javascript import { Checkout } from '@freemius/checkout'; const handler = new Checkout({ product_id: '1234', public_key: 'pk_xxxx', }); // Trial checkout handler.open({ plan_id: 5678, trial: 'paid', // or true, 'free' licenses: 1, billing_cycle: 'monthly', }); // License renewal flow handler.open({ license_key: 'abc123-def456-ghi789', billing_cycle: 'annual', }); // Payment method update handler.open({ license_key: 'abc123-def456-ghi789', is_payment_method_update: true, }); // Bundle with custom UI handler.open({ plan_id: 9000, licenses: 5, billing_cycle: 'lifetime', bundle_discount: 'maximize', is_bundle_collapsed: false, show_reviews: true, show_refund_badge: true, layout: 'horizontal', form_position: 'right', }); // Readonly user with user token handler.open({ user_token: 'usr_abc123xyz', readonly_user: true, user_email: 'locked@example.com', user_firstname: 'John', user_lastname: 'Doe', }); // Advanced customization handler.open({ id: 'custom-checkout-instance', title: 'Upgrade to Pro', modal_title: 'Secure Checkout', currency: 'eur', locale: 'de_DE', billing_cycle_selector: 'dropdown', show_upsells: true, annual_discount: true, multisite_discount: 'auto', always_show_renewals_amount: true, fullscreen: false, }); ``` -------------------------------- ### Initialize Checkout with CDN Global Script Source: https://context7.com/freemius/freemius-checkout-js/llms.txt Loads the Freemius checkout SDK from CDN without build tools, making the global FS.Checkout class available. Creates a new checkout handler with product configuration, attaches click handlers to purchase buttons, and defines purchase completion callbacks. The handler opens a modal with plan, license, and billing cycle options. ```html Checkout Example ``` -------------------------------- ### Basic JavaScript Checkout Implementation Source: https://github.com/freemius/freemius-checkout-js/blob/main/README.md Demonstrates a basic implementation of the Freemius Checkout SDK in JavaScript. It initializes the checkout handler with product and public keys, and opens the checkout modal when a button is clicked, including callbacks for purchase completion and success. ```javascript import { Checkout } from '@freemius/checkout'; function getSelectedLicenses() { return document.querySelector('#licenses').value; } const handler = new Checkout({ product_id: '311', public_key: 'pk_a42d2ee6de0b31c389d5d11e36211', }); document.querySelector('#purchase').addEventListener('click', (e) => { e.preventDefault(); handler.open({ name: 'My Awesome Plugin', licenses: getSelectedLicenses(), purchaseCompleted: (response) => { console.log('Purchase completed:', response); }, success: (response) => { console.log('Checkout closed after successful purchase:', response); }, }); }); ``` -------------------------------- ### Instantiate Freemius Checkout Class (npm) Source: https://github.com/freemius/freemius-checkout-js/blob/main/README.md Shows how to import and instantiate the Checkout class from the 'freemius-checkout-js' npm package. The `product_id` and `public_key` are required parameters for instantiation. ```javascript import { Checkout } from 'freemius-checkout-js'; // instantiate const handler = new Checkout({ product_id: '0001', public_key: 'pk_xxxx', }); ``` -------------------------------- ### Initialize Freemius Checkout Handler with Configuration Source: https://github.com/freemius/freemius-checkout-js/blob/main/WebsiteDoc.md Initializes the Freemius Checkout handler with product credentials and configuration. Requires plugin_id, plan_id, public_key, and optional image URL. The handler manages the checkout flow for the specified product plan. ```javascript ``` -------------------------------- ### Instantiate Freemius Checkout Handler (JavaScript) Source: https://context7.com/freemius/freemius-checkout-js/llms.txt Demonstrates how to create an instance of the Checkout class, which acts as a handler for the Freemius checkout process. It shows basic instantiation with product credentials and advanced options like custom images, titles, locales, and sandbox mode for testing. Requires product_id and public_key. ```javascript import { Checkout } from '@freemius/checkout'; // Basic instantiation with required parameters const handler = new Checkout({ product_id: '311', public_key: 'pk_a42d2ee6de0b31c389d5d11e36211', }); // Advanced instantiation with additional options const advancedHandler = new Checkout({ product_id: '1234', public_key: 'pk_ccca7be7fa43aec791448b43c6266', image: 'https://yoursite.com/logo-100x100.png', title: 'My Premium Plugin', locale: 'auto', loadingImageUrl: 'https://yoursite.com/custom-loader.svg', loadingImageAlt: 'Loading checkout...', }); // Sandbox mode for testing (requires server-side token generation) const sandboxHandler = new Checkout({ product_id: '1234', public_key: 'pk_xxxx', sandbox: { ctx: '1634567890', // timestamp from server token: 'a1b2c3d4e5f6...', // MD5 hash from server }, }); ``` -------------------------------- ### Initialize New Freemius Checkout Instance (JavaScript) Source: https://github.com/freemius/freemius-checkout-js/blob/main/README.md Migrate from the legacy `FS.Checkout.configure` method to instantiating `new FS.Checkout()`. This change is necessary for the new checkout flow. The `plugin_id` can optionally be replaced with `product_id`. ```javascript // Legacy checkout code // const handler = FS.Checkout.configure({ // plugin_id: '1234', // plan_id: '5678', // public_key: 'pk_ccca7be7fa43aec791448b43c6266', // image: 'https://your-plugin-site.com/logo-100x100.png', // }); // New checkout code const handler = new FS.Checkout({ plugin_id: '1234', plan_id: '5678', public_key: 'pk_ccca7be7fa43aec791448b43c6266', image: 'https://your-plugin-site.com/logo-100x100.png', }); ``` -------------------------------- ### Adapt Singleton Checkout Calls to Instance Calls (JavaScript) Source: https://github.com/freemius/freemius-checkout-js/blob/main/README.md Illustrates the necessary code adjustment when moving from the old singleton `FS.Checkout.open()` pattern to the new instance-based approach. This involves creating a `handler` instance and calling methods on it. ```javascript const handler = new FS.Checkout({ plugin_id: 'x', // ... }); handler.open({ // ... }); ``` -------------------------------- ### Instantiate Freemius Checkout Class (CDN) Source: https://github.com/freemius/freemius-checkout-js/blob/main/README.md Demonstrates how to instantiate the Checkout class when using the Freemius Checkout JS library via a CDN. The class is available under the global `FS` namespace. The `product_id` and `public_key` are required parameters. ```javascript const handler = new FS.Checkout({ product_id: '1234', public_key: 'pk_xxxx', }); ``` -------------------------------- ### Configure Multiple Freemius Checkouts on One Page (JavaScript) Source: https://github.com/freemius/freemius-checkout-js/blob/main/README.md Demonstrates how to initialize and use multiple independent Freemius checkout instances on the same page. Each instance is configured with distinct product and plan IDs, allowing for different purchase options. ```javascript const anotherHandler = new FS.Checkout({ product_id: '4321', plan_id: '9876', public_key: 'pk_....nnn', image: 'https://your-plugin-site.com/logo-100x100.png', }); document .querySelector('#another-purchase-button') .addEventListener('click', (e) => { anotherHandler.open({ name: 'My Awesome Plugin', licenses: getSelectedLicenses(), purchaseCompleted: function (response) { //... }, success: function (response) { //... }, }); e.preventDefault(); }); ``` -------------------------------- ### Use Freemius Checkout Migration Adapter (JavaScript) Source: https://github.com/freemius/freemius-checkout-js/blob/main/README.md Provides the code snippet for the migration adapter, which allows existing checkout code to function with the new script without immediate code changes. Note the limitations regarding future compatibility, singleton behavior, and bundle size. ```javascript // Ensure you have removed the old checkout script and added the new one: // const handler = FS.Checkout.configure({ plugin_id: '1234', plan_id: '5678', public_key: 'pk_ccca7be7fa43aec791448b43c6266', image: 'https://your-plugin-site.com/logo-100x100.png', }); document.querySelector('#purchase').addEventListener('click', (e) => { handler.open({ name: 'My Awesome Plugin', licenses: getSelectedLicenses(), // You can consume the response for after purchase logic. purchaseCompleted: function (response) { // The logic here will be executed immediately after the purchase confirmation. // alert(response.user.email); }, success: function (response) { // The logic here will be executed after the customer closes the checkout, after a successful purchase. // alert(response.user.email); }, }); e.preventDefault(); }); ``` -------------------------------- ### JavaScript for Multiple Freemius Checkout Instances Source: https://context7.com/freemius/freemius-checkout-js/llms.txt Illustrates how to manage and initialize multiple distinct Freemius Checkout handlers on the same web page, each configured for different plans or products. This pattern is useful for sites offering various pricing tiers or add-ons. Event listeners are attached to specific buttons to trigger the appropriate checkout instance. ```javascript import { Checkout } from '@freemius/checkout'; // Basic plan checkout const basicHandler = new Checkout({ product_id: '1234', public_key: 'pk_xxxx', }); // Pro plan checkout const proHandler = new Checkout({ product_id: '1234', public_key: 'pk_xxxx', }); // Enterprise plan checkout const enterpriseHandler = new Checkout({ product_id: '1234', public_key: 'pk_xxxx', }); // Attach to different buttons document.getElementById('buy-basic').addEventListener('click', (e) => { e.preventDefault(); basicHandler.open({ plan_id: 100, licenses: 1, billing_cycle: 'monthly', }); }); document.getElementById('buy-pro').addEventListener('click', (e) => { e.preventDefault(); proHandler.open({ plan_id: 200, licenses: 5, billing_cycle: 'annual', }); }); document.getElementById('buy-enterprise').addEventListener('click', (e) => { e.preventDefault(); enterpriseHandler.open({ plan_id: 300, licenses: 'unlimited', billing_cycle: 'lifetime', }); }); // Close all on custom event window.addEventListener('close-all-checkouts', () => { basicHandler.close(); proHandler.close(); enterpriseHandler.close(); }); ``` -------------------------------- ### Await Freemius Checkout Popup Opening Source: https://github.com/freemius/freemius-checkout-js/blob/main/README.md Demonstrates how to use `async/await` with the `handler.open()` method. The `open` method returns a Promise that resolves when the popup is visible, which is useful for performing actions immediately after the popup appears. ```javascript async function main() { await handler.open({ plan_id: 9999, licenses: 1, billing_cycle: 'annual', }); console.log('Checkout popup is now open'); } ``` -------------------------------- ### Include Freemius Checkout SDK via Hosted CDN Source: https://github.com/freemius/freemius-checkout-js/blob/main/README.md Includes the Freemius Checkout SDK using a script tag pointing to the hosted CDN. This makes the `FS.Checkout` class globally available for use in HTML pages. ```html ``` -------------------------------- ### Configure Global Payment Method Update Events with CDN Source: https://context7.com/freemius/freemius-checkout-js/llms.txt Sets up global event handlers for payment method updates when using the CDN version, by configuring window.FS.paymentMethodUpdateEvents before SDK load. Supports track, success, and cancel callbacks that fire during the payment method update flow. The dunning flow automatically restores on page load if triggered by an email link. ```html Checkout with Dunning

Your Account

``` -------------------------------- ### Open Freemius Checkout Popup Source: https://github.com/freemius/freemius-checkout-js/blob/main/README.md Illustrates how to open the Freemius checkout popup using the `open` method on the Checkout handler. This method can optionally accept parameters to configure the checkout experience. ```javascript handler.open(); ``` ```javascript handler.open({ // plan plan_id: 9999, // number of sites licenses: 1, // billing cycles billing_cycle: 'annual', }); ``` -------------------------------- ### Configure Freemius Checkout with Sandbox Tokens Source: https://github.com/freemius/freemius-checkout-js/blob/main/README.md JavaScript configuration object that includes sandbox token and context (timestamp) for testing Freemius Checkout. The token and context are typically injected from server-side PHP generation to maintain security. ```javascript const config = { // ... sandbox: { token: '', ctx: '', }, }; ``` -------------------------------- ### Freemius Checkout SDK TypeScript Interface Source: https://github.com/freemius/freemius-checkout-js/blob/main/README.md Defines the TypeScript interface for additional options available for the Freemius Checkout SDK, including callbacks for `afterOpen`, `afterClose`, `onExitIntent`, and settings for `sandbox` mode, `loadingImageUrl`, and `loadingImageAlt`. ```typescript interface AdditionalCheckoutOptions { /** * Optional callback to execute when the iFrame opens. * * @new */ afterOpen?: () => void; /** * An optional callback to execute when the iFrame closes. * * @new */ afterClose?: () => void; /** * Optional callback to trigger on exit intent. This is called only when the * checkout iFrame is shown, not on global exit intent. * * @new */ onExitIntent?: () => void; /** * If you would like the dialog to open in sandbox mode, */ sandbox?: { ctx: string; token: string; }; /** * The URL of the image to display while the checkout is loading. By default a loading indicator from Freemius will be used. */ loadingImageUrl?: string; /** * The alt text for the loading image. By default 'Loading Freemius Checkout' will be used. */ loadingImageAlt?: string; } ``` -------------------------------- ### TypeScript Type Definitions for Freemius Checkout Source: https://context7.com/freemius/freemius-checkout-js/llms.txt Demonstrates using TypeScript interfaces for type-safe configuration and event handling with the Freemius Checkout SDK. This ensures that checkout options, popup settings, and event callbacks adhere to predefined types, improving code reliability and maintainability. It requires importing types from the '@freemius/checkout' package. ```typescript import { Checkout, CheckoutOptions, CheckoutPopupOptions, CheckoutPopupEvents, CheckoutResponse, ILoader, IStyle, IExitIntent, } from '@freemius/checkout'; // Type-safe checkout configuration const config: CheckoutOptions = { product_id: '1234', public_key: 'pk_xxxx', loadingImageUrl: 'https://example.com/loader.svg', }; const handler: Checkout = new Checkout(config); // Type-safe popup options const openOptions: Partial = { plan_id: 5678, licenses: 3, billing_cycle: 'annual', currency: 'usd', trial: false, }; // Type-safe event handlers const events: CheckoutPopupEvents = { purchaseCompleted: (response: CheckoutResponse | null) => { if (response?.purchase) { const amount: number | undefined = response.purchase.initial_amount; const email: string = response.user.email; console.log(`Purchase: ${email} paid ${amount}`); } if (response?.trial) { console.log('Trial started:', response.trial.trial_ends_at); } }, success: (response: CheckoutResponse | null) => { console.log('Success:', response?.user.email); }, cancel: () => { console.log('Canceled'); }, track: (event: string, data: Record | null) => { console.log('Track:', event, data); }, }; handler.open({ ...openOptions, ...events }); ``` -------------------------------- ### HTML Multi-Site License Selector with Purchase Button Source: https://github.com/freemius/freemius-checkout-js/blob/main/WebsiteDoc.md Creates a dropdown selection menu for different license tiers (Single Site, 5-Site, 25-Site) and a purchase button. The select element with ID 'licenses' stores the selected license count, while the button triggers the checkout process. ```html ``` -------------------------------- ### Handle Purchase Button Click with Dynamic License Selection Source: https://github.com/freemius/freemius-checkout-js/blob/main/WebsiteDoc.md Attaches a click event listener to the purchase button that opens the checkout modal with the selected license count from the dropdown. Accepts a success callback function to handle post-purchase logic, such as accessing user email from the response object. ```javascript document.querySelector('#purchase').addEventListener('click', function (e) { handler.open({ name: '', licenses: $('#licenses').val(), // You can consume the response for after purchase logic. success: function (response) { // alert(response.user.email); }, }); e.preventDefault(); }); ``` -------------------------------- ### React Custom Hook for Freemius Checkout Management Source: https://context7.com/freemius/freemius-checkout-js/llms.txt Provides a reusable React hook (useFSCheckout) that initializes the Checkout instance with environment variables and manages lifecycle cleanup via useEffect. The hook accepts configuration with product_id and public_key, instantiates a Checkout object, and destroys it on component unmount. Used in functional components to trigger checkout flows with plan, license, and billing cycle options. ```typescript // checkout.ts import { Checkout, CheckoutOptions } from '@freemius/checkout'; import { useState, useEffect } from 'react'; export const checkoutConfig: CheckoutOptions = { product_id: import.meta.env.VITE_FS_PLUGIN_ID as string, public_key: import.meta.env.VITE_FS_PUBLIC_KEY as string, }; export function useFSCheckout() { const [fsCheckout] = useState(() => new Checkout(checkoutConfig)); useEffect(() => { return () => { fsCheckout.destroy(); }; }, [fsCheckout]); return fsCheckout; } // App.tsx import React from 'react'; import { useFSCheckout } from './checkout'; export default function App() { const fsCheckout = useFSCheckout(); const handlePurchase = (e: React.MouseEvent) => { e.preventDefault(); fsCheckout.open({ plan_id: 1234, licenses: 1, billing_cycle: 'annual', success: (data) => { console.log('Purchase successful:', data); // Update app state, redirect, etc. }, }); }; return (

Premium Features

); } ``` -------------------------------- ### Restore Dunning Flow (npm) Source: https://github.com/freemius/freemius-checkout-js/blob/main/README.md Shows how to call the `restoreDunningIfPresent` function when using the npm package to restore a dunning flow if it was previously initiated. This should be called early on page load. It accepts an optional object with event handlers for tracking and success callbacks. ```typescript import { restoreDunningIfPresent } from '@freemius/checkout'; restoreDunningIfPresent(); ``` ```typescript import { restoreDunningIfPresent } from '@freemius/checkout'; restoreDunningIfPresent({ track(event, data) { console.log('Payment Method Update Event:', data, event); }, success(data) { console.log('Payment Method Update Success:', data); }, }); ``` -------------------------------- ### Cart Recovery System with URL Parameters Source: https://context7.com/freemius/freemius-checkout-js/llms.txt Implements automatic cart restoration from URL parameters on Checkout instantiation. Provides methods to check for existing carts, verify plugin matching, and retrieve cart options. Cart recovery can be disabled via a second parameter during initialization. ```javascript import { Checkout } from '@freemius/checkout'; // Cart recovery happens automatically on instantiation const handler = new Checkout({ product_id: '1234', public_key: 'pk_xxxx', }); // If URL contains cart parameters like: // ?__fs_authorization=...&__fs_plugin_id=1234&plan_id=5678&licenses=5 // The checkout will automatically open with those parameters // Disable automatic cart recovery const handlerNoRecover = new Checkout( { product_id: '1234', public_key: 'pk_xxxx', }, false // second parameter disables recovery ); // Manual cart checking if (handler.cart?.hasCart()) { console.log('Cart found for plugin:', handler.cart.getPluginID()); console.log('Matches current product:', handler.cart.matchesPluginID('1234')); const cartOptions = handler.cart.getCheckoutOptions(); console.log('Cart options:', cartOptions); } ``` -------------------------------- ### Create React Hook for Freemius Checkout Source: https://github.com/freemius/freemius-checkout-js/blob/main/README.md A custom React hook that initializes a single Checkout instance and properly cleans up resources on component unmount. The hook uses React's useState and useEffect to manage the Checkout lifecycle and reads configuration from environment variables. ```typescript import { Checkout, CheckoutOptions } from '@freemius/checkout'; import { useState, useEffect } from 'react'; export const checkoutConfig: CheckoutOptions = { product_id: import.meta.env.VITE_FS_PLUGIN_ID as string, }; export function useFSCheckout() { // create a Checkout instance once const [fsCheckout] = useState(() => new Checkout(checkoutConfig)); useEffect(() => { // close and destroy the DOM related stuff on unmount return () => { fsCheckout.destroy(); }; }, [fsCheckout]); return fsCheckout; } ``` -------------------------------- ### Generate Freemius Sandbox Token with PHP Source: https://github.com/freemius/freemius-checkout-js/blob/main/README.md PHP server-side code that generates a secure sandbox token and timestamp for Freemius Checkout testing. The token is created using MD5 hashing of timestamp, product ID, secret key, public key, and a checkout string. This protects the secret key from client-side exposure. ```php { e.preventDefault(); fsCheckout.open({ plan_id: 1234, licenses: 1, billing_cycle: 'annual', success: (data) => { console.log(data); }, }); }} > Buy Plan ); } ``` -------------------------------- ### Postman Cross-Frame Communication for Iframe Integration Source: https://context7.com/freemius/freemius-checkout-js/llms.txt Provides internal utility for iframe message passing and event communication. The postman function creates a communication channel with an iframe at a specified origin, supporting event listeners, one-time listeners, message posting, and resource cleanup. Useful for advanced integrations requiring direct iframe control. ```javascript import { postman } from '@freemius/checkout'; // Create communication channel with iframe const iframe = document.querySelector('#checkout-iframe'); const pm = postman(iframe, 'https://checkout.freemius.com'); if (pm) { // Listen for events from iframe pm.on('purchase-complete', (data) => { console.log('Purchase completed:', data); }); // One-time event listener pm.one('checkout-loaded', (data) => { console.log('Checkout loaded once:', data); }); // Send message to iframe pm.post('custom-event', { key: 'value' }); // Track events pm.on('track', (data) => { console.log('Analytics event:', data); }); // Cleanup on component unmount pm.destroy(); } ``` -------------------------------- ### Set Payment Method Update Events (CDN) Source: https://github.com/freemius/freemius-checkout-js/blob/main/README.md Demonstrates how to configure event handlers for payment method updates when using the Freemius Checkout JS library via CDN. This is done by setting the `paymentMethodUpdateEvents` property on the `window.FS` global object before including the CDN script. ```javascript window.FS.paymentMethodUpdateEvents = { track(event, data) { console.log('Payment Method Update Event:', data, event); }, success(data) { console.log('Payment Method Update Success', data); }, }; ``` -------------------------------- ### Update Freemius Checkout JS Script Tag Source: https://github.com/freemius/freemius-checkout-js/blob/main/README.md Replace the old Freemius Checkout script URL with the new one. Ensure jQuery is removed if not actively used. The new script is located at `https://checkout.freemius.com/js/v1/`. ```html ``` -------------------------------- ### Restore Dunning Payment Recovery Flow in JavaScript Source: https://context7.com/freemius/freemius-checkout-js/llms.txt Automatically restores payment method update flows triggered from dunning email links using the restoreDunningIfPresent function. Supports event handlers for tracking, success, and cancellation, and returns a checkout instance if a dunning flow is detected. Call early in the application lifecycle, typically on page load, to detect and restore interrupted payment updates. ```javascript import { restoreDunningIfPresent } from '@freemius/checkout'; // Basic restoration (call on page load) restoreDunningIfPresent(); // With event handlers restoreDunningIfPresent({ track: (event, data) => { console.log('Payment Method Update Event:', event, data); }, success: (data) => { console.log('Payment method updated successfully:', data); alert('Your payment method has been updated!'); }, cancel: () => { console.log('Payment update canceled'); }, }); // Async pattern with result checking async function handleDunning() { const checkoutInstance = await restoreDunningIfPresent({ success: (data) => { console.log('Payment updated:', data); }, }); if (checkoutInstance) { console.log('Dunning flow restored'); } else { console.log('No dunning flow to restore'); } } // Call early in application lifecycle document.addEventListener('DOMContentLoaded', () => { restoreDunningIfPresent(); }); ``` -------------------------------- ### Close Freemius Checkout Popup Source: https://github.com/freemius/freemius-checkout-js/blob/main/README.md Provides the code snippet to programmatically close the Freemius checkout popup using the `close` method. ```javascript handle.close(); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.