Chargebee Object
Overview
The Chargebee object is the main instance that provides access to all Chargebee.js SDK features. After initializing Chargebee.js, you can use the Chargebee object to manage checkout flows, customer portals, payment processing, and other subscription-related functionality.
Prerequisites
Before using the Chargebee object, ensure you have:
- Initialized Chargebee.js in your application.
- ⚠️ Allowlisted your domain to ensure all callbacks are fired.
Checkout
The Checkout functions enable you to manage subscription checkout flows. These functions help you provide your customers with the ability to subscribe to your services.
Checkout tutorials
For step-by-step integration, see the Checkout tutorials.
setBusinessEntity(businessEntityId)
Sets the business entity context for the Chargebee instance.
Syntax
chargebee.setBusinessEntity(businessEntityId)Parameters
Return value
This function returns a promise that resolves when the business entity is set.
Example
const chargebee = Chargebee.init({
site: "YOUR-CHARGEBEE-BILLING-SUBDOMAIN",
isItemsModel: true, // Product catalog 2.0
});
// Set the business entity for Checkout.
await chargebee.setBusinessEntity("acme-inc-us");
// Create a cart and proceed to checkout.
const cart = chargebee.getCart();
const product = chargebee.initializeProduct("silver-USD-monthly");
cart.replaceProduct(product);
cart.proceedToCheckout();openCheckout(options)
Opens a Chargebee hosted page in a modal or new window. This function handles the complete hosted page flow including any payment processing and subscription creation.
Supported hosted page types
All hosted page types are supported by openCheckout(), except Collect Now. To open a Collect Now page, open the url from the Collect Now API response in a new browser tab or window (for example, window.open(response.hosted_page.url, '_blank')).
Syntax
chargebee.openCheckout(options)Parameters
Return value
This function does not return a value.
Example
chargebee.openCheckout({
hostedPage: function() {
// Required: Return a promise that resolves to a hosted page object.
// This should make an AJAX call to your server to create a hosted page.
return new Promise(function(resolve, reject) {
// Example hosted page response from your server.
const hostedPageResponse = {
"id": "8ajOxcuyG692GDy9yjnZ2hNM1ATugOFQl",
"type": "checkout_new",
"url": "https://yourapp.chargebee.com/pages/v3/8ajOxcuyG692GDy9yjnZ2hNM1ATugOFQl/",
"state": "created",
"embed": true,
"created_at": 1515494821,
"expires_at": 1515498421
};
resolve(hostedPageResponse);
});
},
loaded: function() {
// Optional: Called when Checkout page is loaded.
console.log('Checkout page loaded successfully.');
},
error: function(error) {
// Optional: Called if there's an error.
console.error('Checkout error:', error);
},
step: function(step) {
// Optional: Called for each step in the checkout process.
console.log('Checkout step:', step);
},
success: function(hostedPageId) {
// Optional: Called when checkout is successful
console.log('Checkout successful:', hostedPageId);
// Redirect user or update UI as needed.
},
close: function() {
// Optional: Called when user closes the checkout modal.
console.log('Checkout modal closed.');
}
});For a complete list of supported callbacks, see the Checkout parameters reference.
getCart()
Retrieves the current shopping cart object that you can use to manage items before checkout.
Syntax
const cart = chargebee.getCart();Return value
Returns a cart object that provides methods to manage the shopping cart items.
Example
const chargebee = Chargebee.init({
site: "moments-test",
isItemsModel: true, // Product catalog 2.0
});
const cart = chargebee.getCart();
// Add products to cart and proceed to checkout.
const product = chargebee.initializeProduct("silver-USD-monthly");
cart.replaceProduct(product);
cart.proceedToCheckout();getProduct(checkoutButtonElement)
Retrieves the Product object associated with a checkout button element. This is useful when you have HTML elements with data-* attributes that define the product configuration.
Syntax
chargebee.getProduct(checkoutButtonElement)Parameters
Return value
Returns a Product object.
Example
<a href="javascript:void(0)"
id="diamond-subscribe-button"
data-cb-type="checkout"
data-cb-item-0="diamond-USD-monthly"
data-cb-item-1="silver-pass-USD-monthly"
data-cb-item-1-quantity="2">
Subscribe to Diamond Plan
</a>// Option 1: Get the button element by ID
const subscribeButton = document.getElementById("diamond-subscribe-button");
// Option 2: Get the button element using querySelector for data-cb-type
const checkoutButtonElement = document.querySelector("[data-cb-type='checkout']");
// Extract product configuration from the button
const product = chargebee.getProduct(subscribeButton);
// Use the product object for checkout
const cart = chargebee.getCart();
cart.replaceProduct(product);
cart.proceedToCheckout();initializeProduct(planId, planQuantity?)
Creates a new Product object with the specified plan and optional quantity. Use this function to programmatically create product configurations.
Syntax
chargebee.initializeProduct(planId, planQuantity)Parameters
Return value
Returns a Product object.
Example
// Create a product with a specific quantity.
const product = chargebee.initializeProduct("silver-USD-monthly", 2);
// Use the product in a cart.
const cart = chargebee.getCart();
cart.replaceProduct(product);
cart.proceedToCheckout();setCheckoutCallbacks(setterFunction)
Sets global callbacks for all Checkout operations. This function allows you to define callback handlers that will be triggered during checkout flows.
Syntax
chargebee.setCheckoutCallbacks(setterFunction);Parameters
Return value
This function does not return a value.
Example
chargebee.setCheckoutCallbacks((cart) => {
// You can define custom callbacks based on cart object
return {
loaded: () => {
console.log('Checkout page loaded successfully.');
// Update UI to show checkout is ready.
},
step: (step) => {
// Called for each step in the checkout process.
console.log('Checkout step:', step);
// Track checkout progress.
},
success: (hostedPageId) => {
console.log('Checkout completed successfully:', hostedPageId);
// Redirect user or update UI.
},
error: (err) => {
console.error('Checkout failed:', err);
// Show error message to user.
alert('Checkout failed. Please try again.');
},
close: () => {
console.log('Checkout modal closed.');
// Handle modal close event.
},
resize: (height) => {
// Called when checkout page height changes.
console.log('Checkout page height:', height);
// Adjust iframe or modal height if needed.
}
};
});Portal
The Portal functions enable you to manage customer self-service portals. These functions help you provide your customers with the ability to manage their accounts efficiently.
Portal tutorials
For step-by-step integration, see the self-serve portal tutorials.
setPortalSession(setterFunction)
Sets up the portal session for customer self-service portal access. This function must be called before creating a portal instance.
Prerequisite
Enable single sign-on (SSO) in your Chargebee Portal settings.
Syntax
chargebee.setPortalSession(setterFunction)Parameters
Return value
This function returns a promise that resolves to a portal session object.
Example
chargebee.setPortalSession(function() {
// This function should return a promise that resolves to a portal session object.
// Make an AJAX call to your server to create a portal session.
return new Promise(function(resolve, reject) {
// Example portal session response from your server.
const portalSessionResponse = {
"id": "portal_XpbGElGQgEHspHB",
"token": "<portal-session-token>",
"access_url": "https://yourapp.chargebeeportal.com/portal/access/<portal-session-token>",
"status": "created",
"created_at": 1515494835,
"expires_at": 1515498435,
"object": "portal_session",
"customer_id": "XpbGEt7QgEHsnL7O"
};
resolve(portalSessionResponse);
});
});createChargebeePortal()
Creates a Chargebee Portal instance that provides access to the customer self-service portal functionality.
Prerequisite
Call setPortalSession() before calling this function.
Syntax
const chargebeePortal = chargebee.createChargebeePortal()Return value
Returns a Chargebee portal object.
Example
const chargebee = Chargebee.getInstance();
// Set up portal session (required before creating portal).
chargebee.setPortalSession(() => {
// Return a promise that resolves to portal session data.
return new Promise(function(resolve, reject) {
// Example portal session response from your server.
const portalSessionResponse = {
"id": "portal_XpbGElGQgEHspHB",
"token": "<portal-session-token>",
"access_url": "https://yourapp.chargebeeportal.com/portal/access/<portal-session-token>",
"status": "created",
"created_at": 1515494835,
"expires_at": 1515498435,
"object": "portal_session",
"customer_id": "XpbGEt7QgEHsnL7O"
};
resolve(portalSessionResponse);
});
});
// Create and open the portal.
const chargebeePortal = chargebee.createChargebeePortal();
chargebeePortal.open();logout()
Logs out the Chargebee self-service portal session. If you don't call this function, the session will automatically expire after one hour.
Syntax
chargebee.logout()closeAll()
Closes all open Chargebee modals.
Syntax
chargebee.closeAll()setPortalCallbacks(callbacks)
Sets global callbacks for portal operations. These callbacks will be triggered during various portal events.
Syntax
chargebee.setPortalCallbacks(callbacks);Parameters
Example
chargebee.setPortalCallbacks({
loaded: () => {
console.log('Portal loaded successfully.');
// Update UI to show portal is ready.
},
subscriptionChanged: (data) => {
console.log('Subscription changed:', data.subscription.id);
// Refresh subscription data in your app.
},
closed: () => {
console.log('Portal closed');
// Handle portal close event.
}
});Payment Components
Payment Components tutorials
For step-by-step integration, see the Payment Components tutorials.
components(options)
Creates a Components object that you use to create Payment Components.
Syntax
chargebee.components(options);Parameters
Return value
Returns a Components instance.
Example
const components = chargebee.components({
style: {
theme: {
radius: "large",
scaling: "100%",
},
variables: {
colorBackground: "#dcf5bf33",
defaultFontFamily: "'Sora', sans-serif",
},
rules: {
".g-RadioCardsItem": {
background: "linear-gradient(150deg, transparent 60%, var(--gray-9))",
},
".g-BaseButton:where(.g-variant-solid)": {
background: "linear-gradient(10deg, var(--gray-9), var(--gray-7))",
boxShadow: "0 6px 8px rgba(0, 0, 0, 0.3), 0 3px 6px rgba(0, 0, 0, 0.2)",
},
"#payment-container": {
padding: "var(--space-6)",
minHeight: "150rem",
},
},
},
locale: "fr"
});Pricing Table
Previous Version
The earlier version of Pricing Table was available as the @chargebee/atomicpricing NPM package. That package has since been deprecated. See Migrate Pricing Tables from Pricify.js.
Pricing Table tutorials
For step-by-step integration, see the Pricing Tables tutorials.
pricingTable()
Returns a Pricing Table instance.
Syntax
chargebee.pricingTable();Parameters
None.
Return value
Returns a Pricing Table object.
Example
const chargebee = window.Chargebee.init({
site: "YOUR-CHARGEBEE-SUBDOMAIN",
});
const pricingTable = await chargebee.pricingTable();
pricingTable.init();Personalized Offers
Previous Version
The earlier version of Personalized Offers was delivered via Retention.js, which has since been deprecated. You can still view the documentation for reference.
Personalized Offers tutorials
For step-by-step integration, see the Personalized Offers tutorials.
personalizedOffers()
Returns a Personalized Offers instance used to dynamically display eligible offers to the user.
Syntax
chargebee.personalizedOffers();Parameters
None.
Return value
Returns a Personalized Offers object.
Example
const chargebee = window.Chargebee.init({
site: "YOUR-CHARGEBEE-SUBDOMAIN",
});
const personalizedOffers = await chargebee.personalizedOffers();
personalizedOffers.init({
account: {
customerId: "16CRibUdE6pV6HoU"
},
externalUserId: "jane_doe",
firstName: "Jane",
lastName: "Doe",
roles: ['sales-manager'],
custom: {
viewCount: 6
}
});Cancel Page
Previous Version
The earlier version of Cancel Page was delivered via Brightback.js, which has since been deprecated. See Migrate Cancel Pages from Brightback.js. You can still view the legacy documentation for reference.
Cancel Pages tutorials
For step-by-step integration, see the Cancel Pages tutorials.
cancelPage()
Returns a Cancel Page instance used to control and integrate cancel pages during subscription cancellation flows.
Syntax
chargebee.cancelPage();Parameters
None.
Return value
Returns a Cancel Page object.
Example
<a id="cb-cancel" href="https://app.yourcompany.com/cancel" class="btn btn-danger">
Cancel Subscription
</a>const chargebee = window.Chargebee.init({
site: "YOUR-CHARGEBEE-SUBDOMAIN",
});
const cancelPage = await chargebee.cancelPage();
cancelPage.attachCancelHandler({
account: {
customerId: "16CRibUdE6pV6HoU",
firstPurchaseDate: "2024-06-26"
},
externalUserId: "jane_doe",
firstName: "Jane",
lastName: "Doe",
saveReturnUrl: "https://app.yourcompany.com/save?id=jane_doe",
cancelConfirmationUrl: "https://app.yourcompany.com/cancel_confirm?id=jane_doe",
custom: {
emailCount: 4208
}
});Payments
The functions described in this section are used to handle payment processing and related workflows. These include cards with 3D Secure authentication and various other payment methods.
Payments tutorials
For step-by-step integration, see the Payments tutorials.
load(moduleName)
Loads a specific Chargebee module that you need for your application. This function must be called before using any module-specific functionality.
Syntax
chargebee.load(moduleName)Parameters
Return value
Returns a promise that resolves when the module is loaded and ready for use.
Example
// Load the card components module.
chargebee.load('components').then(() => {
console.log('Card components module loaded successfully.');
// Now you can mount card components.
}).catch(error => {
console.error('Failed to load card components module:', error);
});load3DSHandler()
Loads the 3D Secure (3DS) Helper module and initializes the 3DS handler object for secure payment authentication.
Syntax
chargebee.load3DSHandler()Return value
Returns a promise that resolves to a 3DS handler object.
Example
chargebee.load3DSHandler().then((threeDSHandler) => {
console.log('3DS handler loaded successfully.');
// Use the threeDSHandler for 3D Secure authentication.
}).catch(error => {
console.error('Failed to load 3DS handler:', error);
});handlePayment(paymentMethodType, paymentOptions?)
Initiates the payment process for the specified payment method. This function handles the complete payment flow including authentication and authorization.
Syntax
chargebee.handlePayment(paymentMethodType, paymentOptions);Parameters
Return value
Returns a promise that resolves to an authorized payment intent object.
Example
chargebee.handlePayment('ideal', {
paymentIntent: () => {
// Make an Ajax call to your server to create a payment intent.
return fetch('/api/create-payment-intent', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
amount: 1000,
currency: 'EUR'
})
}).then(response => response.json());
}
}).then(paymentIntent => {
console.log('Payment authorized successfully:', paymentIntent);
// Use the authorized payment intent to create a subscription.
}).catch(err => {
console.error('Payment authorization failed:', err);
// Handle payment failure.
});tokenize(component, additionalData?)
Sends the card details to the payment gateway for tokenization. The payment gateway configured for the business entity specified during initialization is used for tokenization.
The generated temporary token expires after 30 minutes.
Syntax
chargebee.tokenize(component, additionalData);Parameters
Return value
Returns a promise that resolves to a Chargebee nonce (temporary token) object.
Example
// Create a card component.
const cardComponent = chargebee.createComponent('card');
// Tokenize the card with additional customer data.
chargebee.tokenize(cardComponent, {
firstName: 'John',
lastName: 'Doe',
addressLine1: '1600 Amphitheatre Parkway',
addressLine2: 'Building 42',
city: 'Mountain View',
state: 'California',
stateCode: 'CA',
zip: '94039',
countryCode: 'US'
}).then((data) => {
console.log('Chargebee token:', data.token);
// Use the token to create a payment source or subscription.
}).catch((error) => {
console.error('Tokenization failed:', error);
// Handle tokenization error.
});Response example
{
"token": "cb_XAKJhqUVXuhyiJRYgLQSakdkNQad"
}create3DSHandler() deprecated
Deprecated
The create3DSHandler() method is deprecated. Use the load3DSHandler() method instead.
Creates a 3DS handler object after the 3ds-handler module has been loaded using the load(moduleName) method. This is an alternative way to get a 3DS handler instance.
Syntax
chargebee.create3DSHandler();Return value
Returns a 3DS handler object.
Example
// First load the 3ds-handler module.
chargebee.load('3ds-handler').then(() => {
// Then create the 3DS handler.
const threeDSHandler = chargebee.create3DSHandler();
console.log('3DS handler created successfully');
// Use the threeDSHandler for authentication.
}).catch(error => {
console.error('Failed to load 3DS module:', error);
});Functions
This section provides utility functions for validating customer information before processing payments. Currently, validateVat() is the only available function. See the Functions reference for the full details.
EU VAT validation
The VAT validation function allows you to verify European Union VAT numbers by sending validation requests to the VAT Information Exchange System (VIES), which is maintained by the European Commission.
Prerequisite
To use EU VAT validation, you must set your organization address in Chargebee Billing.
validateVat(options)
Validates a European Union VAT number using VIES.
Syntax
chargebee.vat.validateVat(options)Example
const chargebee = Chargebee.getInstance();
// Load the functions module first.
chargebee.load('functions').then(() => {
const options = {
// VAT validation configuration options.
};
chargebee.vat.validateVat(options)
.then(result => {
console.log('VAT validation result:', result);
// Handle validation result.
})
.catch(err => {
console.error('VAT validation failed:', err);
});
});Parameters
Return value
Returns an object containing the VAT validation status and an optional message.
Response example
{
"status": "VALID",
"message": "VAT number is valid."
}Response properties
status: The validation result status.
Status | Description |
|---|---|
| VAT number validation was successful and the number is valid |
| VAT number validation failed |
| No response from VIES or other errors occurred |
message: Describes the response received from the VIES system