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

# Checkout

The Checkout functions enable you to manage subscription checkout (opens new window) 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 (opens new window).

# setBusinessEntity(businessEntityId)

Sets the business entity (opens new window) context for the Chargebee instance.

# Syntax

chargebee.setBusinessEntity(businessEntityId)
1

# Parameters

entityId
String Required
Id of business entity.

# 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();
1
2
3
4
5
6
7
8
9
10
11
12
13

# 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 (opens new window) are supported by openCheckout(), except Collect Now (opens new window). To open a Collect Now page, open the url from the Collect Now API (opens new window) response in a new browser tab or window (for example, window.open(response.hosted_page.url, '_blank')).

# Syntax

chargebee.openCheckout(options)
1

# Parameters

DETAILS
options
Object Required Hide properties
hostedPage
Function Required
This function should return a promise that resolves a hosted page object
layout
Enum
Specifies the checkout layout that overrides the default checkout layout configured in the Checkout & Self-Serve Portal settings.

Allowed Values:
in_app
full_page
loaded
Function
This function will be called once the checkout page is loaded.
error
Function
This function will be called if the promise returned from the hostedPage function rejects an error.
success
Function
This function will be called once the checkout is successful.
Arguments - Hide
hostedPageId
String
Hosted page token.
close
Function
This function will be called once the checkout is closed by the end user.
step
Function
This function will be called everytime a user navigates from one step to another during checkout. You can send the step value to different tracking services for identiyfing checkout drop-off.
Arguments - Hide
currentStep
String
Current step in checkout.

# 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.');
  }
});
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40

TIP

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();
1

# 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();
1
2
3
4
5
6
7
8
9
10
11

# 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)
1

# Parameters

DETAILS
checkoutButtonElement
Required
HTML Element associated with the checkout button.

# 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>
1
2
3
4
5
6
7
8
// 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();
1
2
3
4
5
6
7
8
9
10
11
12
13

# 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)
1

# Parameters

DETAILS
planId
String Required
Unique identifier for the plan / item price.
planQuantity
number
Quantity of the plan in number, if applicable.

# 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();
1
2
3
4
5
6
7

# 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);
1

# Parameters

DETAILS
setterFunction
Function
Arguments - Hide
cart
Cart Object
Return type
callbacks
Object Hide properties
loaded
Function
This function will be called once the checkout page is loaded.
error
Function
This function will be called if the promise returned from the hostedPage function rejects an error.
success
Function
This function will be called once the checkout is successful.
Arguments - Hide
hostedPageId
String
Hosted page token.
close
Function
This function will be called once the checkout is closed by the end user.
step
Function
This function will be called everytime a user navigates from one step to another during checkout. You can send the step value to different tracking services for identiyfing checkout drop-off.
Arguments - Hide
currentStep
String
Current step in checkout.
resize
Function
This function is invoked whenever the height of the embedded checkout page changes due to interactions within the page. The callback receives the new height, allowing the iframe size in the parent page to be adjusted accordingly.
trackCustom
String
Custom event name.
subscriptionExtended
Function
This function will be called when an end customer extends their subscription.
Arguments - Hide
data
Object Hide properties
subscription
Object Hide properties
id
String
Subscription ID

# 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.
    }
  };
});
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32

# Portal

The Portal functions enable you to manage customer self-service portals (opens new window). 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 (opens new window).

# 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)
1

# Parameters

DETAILS
setterFunction
Function
This function should return a promise that resolves to a portal session object.

# 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);
  });
});
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

# createChargebeePortal()

Creates a Chargebee Portal instance that provides access to the customer self-service portal (opens new window) functionality.

Prerequisite

Call setPortalSession() before calling this function.

# Syntax

const chargebeePortal = chargebee.createChargebeePortal()
1

# 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();
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24

# 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()
1

# closeAll()

Closes all open Chargebee modals.

# Syntax

chargebee.closeAll()
1

# setPortalCallbacks(callbacks)

Sets global callbacks for portal operations. These callbacks will be triggered during various portal events.

# Syntax

chargebee.setPortalCallbacks(callbacks);
1

# Parameters

DETAILS
callbacks
Object Hide properties
loaded
Function
This function will be called once the portal is loaded.
close
Function
This function will be called once the portal is closed by the end user.
visit
Function
This function will be called everytime an user visits a section in the customer portal.
Arguments - Hide
sectionType
String
paymentSourceAdd
Function
This function will be called whenever a new payment source is added in portal
paymentSourceUpdate
Function
This function will be called whenever a payment source is updated in portal
paymentSourceRemove
Function
This function will be called whenever a payment source is removed from portal.
subscriptionChanged
Function
This function will be called whenever a subscription is changed.
Arguments - Hide
data
Object Hide properties
subscription
Object Hide properties
id
String
Subscription ID
subscriptionCustomFieldsChanged
Function
This function will be called whenever a subscription custom fields are changed.
Arguments - Hide
data
Object Hide properties
subscription
Object Hide properties
id
String
Subscription ID
subscriptionCancelled
Function
This function will be called when a subscription is canceled.
Arguments - Hide
data
Object Hide properties
subscription
Object Hide properties
id
String
Subscription ID
subscriptionResumed
Function
This function will be called when a subscription is resumed.
Arguments - Hide
data
Object Hide properties
subscription
Object Hide properties
id
String
Subscription ID
subscriptionPaused
Function
This function will be called when a subscription is paused.
Arguments - Hide
data
Object Hide properties
subscription
Object Hide properties
id
String
Subscription ID
scheduledPauseRemoved
Function
This function will be called when a subscription that is scheduled for pause is removed.
Arguments - Hide
data
Object Hide properties
subscription
Object Hide properties
id
String
Subscription ID
scheduledCancellationRemoved
Function
This function will be called when the schedule to cancel a subscription is removed.
Arguments - Hide
data
Object Hide properties
subscription
Object Hide properties
id
String
Subscription ID
subscriptionReactivated
Function
This function will be called when an end customer reactivates their canceled subscription.
Arguments - Hide
data
Object Hide properties
subscription
Object Hide properties
id
String
Subscription ID
subscriptionExtended
Function
This function will be called when an end customer extends their subscription.
Arguments - Hide
data
Object Hide properties
subscription
Object Hide properties
id
String
Subscription ID

# 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.
  }
});
1
2
3
4
5
6
7
8
9
10
11
12
13
14

# Payment Components

# Payment Components tutorials

For step-by-step integration, see the Payment Components tutorials (opens new window).

# components(options)

Creates a Components object that you use to create Payment Components.

# Syntax

chargebee.components(options);
1

# Parameters

options
Object Required View properties

# 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"
});
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26

# Pricing Table

Previous Version

The earlier version of Pricing Table was available as the @chargebee/atomicpricing (opens new window) NPM package. That package has since been deprecated. See Migrate Pricing Tables from Pricify.js (opens new window).

# Pricing Table tutorials

For step-by-step integration, see the Pricing Tables tutorials (opens new window).

# pricingTable()

Returns a Pricing Table instance.

# Syntax

chargebee.pricingTable();
1

# 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();
1
2
3
4
5
6
7

# 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 (opens new window) for reference.

# Personalized Offers tutorials

For step-by-step integration, see the Personalized Offers tutorials (opens new window).

# personalizedOffers()

Returns a Personalized Offers instance used to dynamically display eligible offers to the user.

# Syntax

chargebee.personalizedOffers();
1

# 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
  }
});
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

# 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 (opens new window). You can still view the legacy documentation (opens new window) for reference.

# Cancel Pages tutorials

For step-by-step integration, see the Cancel Pages tutorials (opens new window).

# cancelPage()

Returns a Cancel Page instance used to control and integrate cancel pages during subscription cancellation flows.

# Syntax

chargebee.cancelPage();
1

# 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>
1
2
3
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
  }
});
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

# 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 (opens new window).

# 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)
1

# Parameters

DETAILS
moduleName
String Required
Name of the module to load.
Allowed Values:
components
3ds-handler
functions
ideal
sofort
google-pay
bancontact
dotpay
paypal
netbanking_emandates
apple-pay
upi
payconiq_by_bancontact
venmo
stablecoin
amazon-pay
kakao-pay
naver-pay
revolut-pay
alipay
wechat-pay
cash-app-pay
klarna_pay_now
boleto
direct_debit

# 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);
});
1
2
3
4
5
6
7

# load3DSHandler()

Loads the 3D Secure (3DS) Helper module and initializes the 3DS handler object for secure payment authentication.

# Syntax

chargebee.load3DSHandler()
1

# 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);
});
1
2
3
4
5
6

# 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);
1

# Parameters

DETAILS
paymentMethodType
Enum Required
Name of the payment method type.
Allowed Values:
ideal
sofort
bancontact
dotpay
netbanking_emandates
klarna_pay_now
direct_debit
paymentOptions
Object Hide properties
Options for the payment method type.
paymentIntent
Function Required
Pass a function that resolves to a Payment Intent object. Learn more object.
paymentInfo
Object Hide properties
Payment details and additional information.
element
Object Required if Using card component
Instance of gateway's hosted card fields can be passed here. For example: Adyen web components, Stripe elements.
card
Object Required if Using raw card details Hide properties
Card details.
number
String Required
Credit card number.
expiryMonth
String Required
Card expiration month.
expiryYear
String Required
Card expiration year.
cvv
String Required
Card CVV code.
firstName
String Required if Worldpay gateway is used.
Cardholder's first name.
lastName
String
Cardholder's last name.
tokenizer
Function Required if Using gateway tokenization.
A function that returns a gateway's card temporary token.
cbToken
String Required if Using Chargebee's Components & Fields
Chargebee's temporary token.
currencyCode
String
Currency code of the payment currency. If not provided, currency code from Payment Intent will be used.
amount
String
Total amount to be paid. If not provided, amount value from Payment Intent will be used.
issuerBank
String Required if Using iDEAL payment
The bank to which the user has to be redirected for authorization.
userName
String Required if using Stripe for iDEAL or SOFORT
Full name of the payer. Required for Stripe iDEAL and Stripe SOFORT. For iDEAL, Stripe uses it as the account holder name on the SEPA Direct Debit mandate; it must match the name on the payer's bank account exactly, or the payment can fail. Because Smart routing can select any of these gateways, provide this field for every iDEAL or SOFORT payment.
userEmail
String Required if using Stripe for iDEAL or SOFORT
Email address of the payer. Required for Stripe iDEAL and Stripe SOFORT. For iDEAL, Stripe uses it to create the SEPA Direct Debit mandate. Because Smart routing can select any of these gateways, provide this field for every iDEAL or SOFORT payment.
country
String Required if using Stripe for SOFORT
Two-letter ISO 3166-1 alpha-2 country code of the payer.
plaid
Object Required if Using Direct debit via Stripe ACH. Hide properties
Plaid enables applications to connect with users’ bank accounts.
userId
String
Plaid user id.
locale
String
Locale code in ISO 639-1 format (en, fr). By default, `en` will be used.
useGateway
Boolean Required if using ACH, Autogiro, BACS, or SEPA via GoCardless
When true, Chargebee redirects the customer to the GoCardless payment page to collect bank account details. Customer fields are used to prefill that page. Check your GoCardless plan to see whether you can collect bankAccount details yourself.
customer
Object Required if using Netbanking, UPI, SEPA (via Adyen, Stripe, BlueSnap, Checkout.com, or GoCardless), ACH (via GoCardless, BlueSnap, Braintree, or Stripe Financial Connections), Autogiro (via GoCardless), or BACS (via GoCardless or Stripe) Hide properties
Customer with whom the subscription will be associated. Required for most Direct Debit schemes.
firstName
String
First name. For most Direct Debit schemes, required if company is not provided.
lastName
String
Last name. For most Direct Debit schemes, required if company is not provided.
email
String Required if using Direct Debit (SEPA, ACH, Autogiro, or BACS), except Chargebee Payments ACH and Adyen ACH
Email address of the customer.
phone
String
Phone number
company
String
Company name. For most Direct Debit schemes, required if firstName and lastName are not provided.
billingAddress
Object Required if using Stripe BACS Hide properties
Billing address of the customer. Required for Stripe BACS. Also sent to GoCardless and Checkout.com SEPA.
addressLine1
String
Address line 1.
addressLine2
String
Address line 2.
addressLine3
String
Address line 3.
city
String
City.
state
String
State name.
stateCode
String
Two-letter state code.
countryCode
String
Two-letter ISO 3166-1 alpha-2 country code.
zip
String
Postal code.
bankAccount
Object Required if using Netbanking, SEPA (via Adyen, Stripe, BlueSnap, Checkout.com, or GoCardless), ACH (via GoCardless, BlueSnap, Adyen, Braintree, or Chargebee Payments), Autogiro (via GoCardless), or BACS (via Stripe or GoCardless) Hide properties
Bank account details of the customer.
bank
String
Name of account holder's bank.
beneficiaryName
String
Name of the beneficiary to whom the money is going to be sent.
accountNumber
String
Bank account number.
accountType
Enum
Represents the account type used to create a payment source. Available for Authorize.net ACH and Razorpay Net Banking(mandates) users only. If not passed, account type is taken as null.

Allowed Values:
checking
savings
business_checking
current
ifscCode
String
Indian Financial System Code (IFSC) is a unique code assigned to your bank's branch for online money transfers
iban
String Required if using SEPA via Adyen, Stripe, BlueSnap, Checkout.com, or GoCardless (unless you pass local bank fields for GoCardless)
Account holder's International Bank Account Number.
nameOnAccount
String Required if using ACH via Chargebee Payments
The name of the individual or entity associated with the bank account.
routingNumber
String
A code that is used to identify financial organisations or banks when making a payment
accountHolderType
String Required if using ACH via BlueSnap or Braintree
Type of entity that holds the bank account.
Allowed Values:
individual
company
bankCode
String
A unique identifier assigned by financial institutions to identify a specific bank branch in a country's banking system.
countryCode
String
Two-letter ISO 3166-1 alpha-2 country code of the bank account. Use US for GoCardless ACH, SE for Autogiro, and GB for Stripe BACS.
swedishIdentityNumber
String Required if Using Autogiro via GoCardless.
A unique identifier used to identify individuals in Sweden for various purposes, such as tax and social security purposes.
upi_app
String

Applicable only for:

  • Razorpay gateway
  • Mobile web browsers (Android or iOS)

The ID of the UPI app to be used for the UPI mandate authorization. Must be a valid id returned by the fetchUpiInstalledAppList() method. When not provided or when the value is invalid, the user is prompted to select a UPI app from the list of supported UPI apps.

additionalData
Object Hide properties
Additional information that needs to be passed for improving the chances of frictionless checkout flow.
plan
String
Plan name
billingAddress
Object Hide properties
Card Billing Address
firstName
String Required if Worldpay gateway is used
First name associated with billing address
lastName
String
Last name associated with billing address
phone
String
Phone number associated with the billing address
addressLine1
String
Billing address line 1 (eg. number, street, etc).
addressLine2
String
Billing address line 2 (eg. suite, apt #, etc.).
addressLine3
String
Billing address line 3 (eg. suite, apt #, etc).
city
String
City or locality name
state
String
State
stateCode
String
2 letter code for US states or equivalent
countryCode
String
2 letter country code
zip
String
Zip code or postal code
customerBillingAddress
Object Hide properties
Customer's Billing Address
firstName
String Required if Worldpay gateway is used
First name associated with billing address
lastName
String
Last name associated with billing address
phone
String
Phone number associated with the billing address
addressLine1
String
Billing address line 1 (eg. number, street, etc).
addressLine2
String
Billing address line 2 (eg. suite, apt #, etc.).
addressLine3
String
Billing address line 3 (eg. suite, apt #, etc).
city
String
City or locality name
state
String
State
stateCode
String
2 letter code for US states or equivalent
countryCode
String
2 letter country code
zip
String
Zip code or postal code
shippingAddress
Object Hide properties
Shipping Address
firstName
String Required if Worldpay gateway is used
First name associated with shipping address
lastName
String
Last name associated with shipping address
phone
String
Phone number associated with the shipping address
addressLine1
String
Shipping address line 1 (eg. number, street, etc).
addressLine2
String
Shipping address line 2 (eg. suite, apt #, etc.).
addressLine3
String
Shipping address line 3 (eg. suite, apt #, etc).
city
String
City or locality name
state
String
State
stateCode
String
2 letter code for US states or equivalent
countryCode
String
2 letter country code
zip
String
Zip code or postal code
email
String Required if Worldpay gateway is used
Mail ID of the customer.
phone
String
Phone number
mandate
Object Hide properties
Enabling this parameter will request Additional Factor Authentication (AFA) and mandate setup to the gateway. Applicable only for cards issued in India.
requireMandate
Boolean
Set the value as `true` to create a mandate. The default value is `false`.
description
String
Send the plan name in this description. This plan name will appear on the AFA page.
document
Object Required if EBANX or dLocal gateway is used Hide properties
The document details (e.g., national IDs or passports) used for document verification and payment processing by EBANX and dLocal.
number
String
The document number.
type
String
The type of document. Refer to the EBANX table or dLocal table below for the possible values.
callbacks
Object Hide properties
Callbacks to be used for this operation.
change
Function
This function will be called during each step of 3DS flow
success
Function
This function will be called if 3DS Authorization is successful
error
Function
This function will be called if 3DS Authorization has failed
challenge
Function
When this callback is implemented, the transaction will proceed in a redirect workflow if supported by the gateway. This callback function will be called with a redirect URL when the 3DS transaction requires a challenge. This workflow is currently supported by Adyen, Braintree and Stripe payment gateways.
redirectMode
Boolean
Default value of this flag is false. When this is true, the entire page will be redirected to the success_url or failure_url instead of opening a new window.

Note: success_url and failure_url must be provided while creating a payment intent for utilizing the redirectMode.

mandateText
String Required if Using ACH via Braintree
Text implying proof of customer authorization. For example, 'I authorize Braintree to debit my bank account on behalf of My Online Store.'

# 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.
});
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21

# tokenize(component, additionalData?)

Sends the card details to the payment gateway for tokenization. The payment gateway configured for the business entity (opens new window) specified during initialization is used for tokenization.

TIP

The generated temporary token expires after 30 minutes.

# Syntax

chargebee.tokenize(component, additionalData);
1

# Parameters

DETAILS
component
Pass card component object or component type for which you want to get Chargebee token
object
Allowed Values:
Card component object
additionalData
Data that is collected at your end.
object
For card component, you can pass additional information like firstName, lastName. Chargebee will generate temporary token for all these details along with the card information collected via our components.
firstName
string
First name.
lastName
string
Last name.
addressLine1
string
Billing address line 1.
addressLine2
string
Billing address line 2.
city
string
City.
state
string
State.
stateCode
string
State code.
zip
string
Zip
countryCode
string
2 letter country code.

# 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.
});
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21

# Response example

{
  "token": "cb_XAKJhqUVXuhyiJRYgLQSakdkNQad"
}
1
2
3

# 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();
1

# 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);
});
1
2
3
4
5
6
7
8
9

# 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) (opens new window), which is maintained by the European Commission.

Prerequisite

To use EU VAT validation, you must set your organization address (opens new window) in Chargebee Billing.

# validateVat(options)

Validates a European Union VAT number using VIES.

# Syntax
chargebee.vat.validateVat(options)
1
# 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);
    });
});
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# Parameters
DETAILS
country
String Required
2-letter ISO 3166 alpha-2 country code
vat_number
String Required
EU VAT Number
# Return value

Returns an object containing the VAT validation status and an optional message.

# Response example
{
  "status": "VALID",
  "message": "VAT number is valid."
}
1
2
3
4
# Response properties
  • status: The validation result status.
Status Description
VALID VAT number validation was successful and the number is valid
INVALID VAT number validation failed
UNDETERMINED No response from VIES or other errors occurred
  • message: Describes the response received from the VIES system