# Chargebee Object

## Overview

The Chargebee object is the main instance that provides access to all Chargebee.js SDK features. After [initializing Chargebee.js](https://www.chargebee.com/docs/js/settingup-api-ref), 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](https://www.chargebee.com/docs/js/settingup-api-ref) in your application.
- ⚠️ [Allowlisted your domain](https://www.chargebee.com/docs/2.0/configure-fullpage.html#domain-allowlist) to ensure all callbacks are fired.

## Checkout

The Checkout functions enable you to manage subscription [checkout](https://www.chargebee.com/docs/billing/2.0/hosted-capabilities/hosted-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](https://www.chargebee.com/tutorials/topics/checkout/).

### `setBusinessEntity(businessEntityId)`

Sets the [business entity](https://apidocs.chargebee.com/docs/api/business_entities) context for the `Chargebee` instance.

#### Syntax

```js
chargebee.setBusinessEntity(businessEntityId)
```

#### Parameters

- `entityId` (String, required) Id of business entity.

#### Return value
This function returns a promise that resolves when the business entity is set.

#### Example

```js
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](https://apidocs.chargebee.com/docs/api/hosted_pages/hosted-page-object#type) are supported by `openCheckout()`, except [Collect Now](https://apidocs.chargebee.com/docs/api/hosted_pages/collect-now). To open a Collect Now page, open the `url` from the [Collect Now API](https://apidocs.chargebee.com/docs/api/hosted_pages/collect-now) response in a new browser tab or window (for example, `window.open(response.hosted_page.url, '_blank')`).

#### Syntax

```js
chargebee.openCheckout(options)
```

#### Parameters

**Parameters**

- `options` (Object, required)
  - `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: `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.
    - `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.
    - `currentStep` (String) Current step in checkout.

#### Return value
This function does not return a value.

#### Example

```js
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.');
  }
});
```

> **Tip**
>
> For a complete list of supported callbacks, see the [Checkout parameters reference](https://www.chargebee.com/docs/js/cbinstanceobj-api-ref#opencheckout-options).

### `getCart()`

Retrieves the current [shopping cart object](https://www.chargebee.com/docs/js/cart-api-ref) that you can use to manage items before checkout.

#### Syntax

```js
const cart = chargebee.getCart();
```

#### Return value
Returns a [cart object](https://www.chargebee.com/docs/js/cart-api-ref) that provides methods to manage the shopping cart items.

#### Example

```js
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

```js
chargebee.getProduct(checkoutButtonElement)
```

#### Parameters

**Parameters**

- `checkoutButtonElement` (required) HTML Element associated with the checkout button.

#### Return value
Returns a [Product object](https://www.chargebee.com/docs/js/product-api-ref).

#### Example

```html
<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>
```

```js
// 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](https://www.chargebee.com/docs/js/product-api-ref) with the specified plan and optional quantity. Use this function to programmatically create product configurations.

#### Syntax

```js
chargebee.initializeProduct(planId, planQuantity)
```

#### Parameters

**Parameters**

- `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](https://www.chargebee.com/docs/js/product-api-ref).

#### Example

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

```js
chargebee.setCheckoutCallbacks(setterFunction);
```

#### Parameters

**Parameters**

- `setterFunction` (Function)
  - `cart` (Cart Object)
  - `callbacks` (Object)
    - `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.
      - `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.
      - `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.
      - `data` (Object)
        - `subscription` (Object)
          - `id` (String) Subscription ID

#### Return value
This function does not return a value.

#### Example

```js
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](https://www.chargebee.com/docs/billing/2.0/hosted-capabilities/hosted-portal). 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](https://www.chargebee.com/tutorials/topics/self-serve-portal/).

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

```js
chargebee.setPortalSession(setterFunction)
```

#### Parameters

**Parameters**

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

```js
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](https://www.chargebee.com/docs/js/cbportal-api-ref) instance that provides access to the customer [self-service portal](https://www.chargebee.com/docs/billing/2.0/hosted-capabilities/hosted-portal) functionality.

> **Prerequisite**
>
> Call [`setPortalSession()`](#setportalsession-setterfunction) before calling this function.

#### Syntax

```js
const chargebeePortal = chargebee.createChargebeePortal()
```

#### Return value
Returns a [Chargebee portal object](https://www.chargebee.com/docs/js/cbportal-api-ref). 

#### Example

```js
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

```js
chargebee.logout()
```

### `closeAll()`

Closes all open Chargebee modals.

#### Syntax

```js
chargebee.closeAll()
```

### `setPortalCallbacks(callbacks)`

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

#### Syntax

```js
chargebee.setPortalCallbacks(callbacks);
```

#### Parameters

**Parameters**

- `callbacks` (Object)
  - `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.
    - `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.
    - `data` (Object)
      - `subscription` (Object)
        - `id` (String) Subscription ID
  - `subscriptionCustomFieldsChanged` (Function) This function will be called whenever a subscription custom fields are changed.
    - `data` (Object)
      - `subscription` (Object)
        - `id` (String) Subscription ID
  - `subscriptionCancelled` (Function) This function will be called when a subscription is canceled.
    - `data` (Object)
      - `subscription` (Object)
        - `id` (String) Subscription ID
  - `subscriptionResumed` (Function) This function will be called when a subscription is resumed.
    - `data` (Object)
      - `subscription` (Object)
        - `id` (String) Subscription ID
  - `subscriptionPaused` (Function) This function will be called when a subscription is paused.
    - `data` (Object)
      - `subscription` (Object)
        - `id` (String) Subscription ID
  - `scheduledPauseRemoved` (Function) This function will be called when a subscription that is scheduled for pause is removed.
    - `data` (Object)
      - `subscription` (Object)
        - `id` (String) Subscription ID
  - `scheduledCancellationRemoved` (Function) This function will be called when the schedule to cancel a subscription is removed.
    - `data` (Object)
      - `subscription` (Object)
        - `id` (String) Subscription ID
  - `subscriptionReactivated` (Function) This function will be called when an end customer reactivates their canceled subscription.
    - `data` (Object)
      - `subscription` (Object)
        - `id` (String) Subscription ID
  - `subscriptionExtended` (Function) This function will be called when an end customer extends their subscription.
    - `data` (Object)
      - `subscription` (Object)
        - `id` (String) Subscription ID

#### Example

```js
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](https://www.chargebee.com/tutorials/topics/payment-components/).

### `components(options)`

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

#### Syntax

```js
chargebee.components(options);
```

#### Parameters

- `options` (Object, required)
  - `style` (Object)
    - `theme` (Object)
      - `appearance` (String) The color scheme for the component. Allowed: `light (default)`, `dark`.
      - `accentColor` (String) The most dominant color in the component. This color is applied to primary buttons and other interactive elements. Allowed: `indigo (default)`, `gray`, `gold`, `bronze`, `brown`, `yellow`, `amber`, `orange`, `tomato`, `red`, `ruby`, `crimson`, `pink`, `plum`, `purple`, `violet`, `iris`, `blue`, `cyan`, `teal`, `jade`, `green`, `grass`, `lime`, `mint`, `sky`.
      - `grayColor` (String) The grayscale color used in the component, such as for shadows, out-of-focus elements, disabled elements, and placeholder text. The value `auto` automatically selects a gray shade that complements the `accentColor`. Allowed: `auto (default)`, `gray`, `mauve`, `slate`, `sage`, `olive`, `sand`.
      - `scaling` (String) The linear scaling applied to the component. Use this setting to adjust the UI density uniformly across the component. Allowed: `90%`, `95%`, `100% (default)`, `105%`, `110%`.
      - `radius` (String) Specifies the border-radius factor applied to the component. The resulting `border-radius` is contextual and varies based on the type of UI element. Allowed: `none`, `small`, `medium (default)`, `large`, `full`.
    - `variables` (Object) The variables option is a map of CSS-like variables to CSS values, allowing granular customization of individual components.Note: You can set font family names using `defaultFontFamily` and related options. They're used only when available on the customer's device. Loading custom font files is not supported.
      - `accent1` (String) Background color 1
      - `accent2` (String) Background color 2
      - `accent3` (String) Interactive components color 1
      - `accent4` (String) Interactive components color 2
      - `accent5` (String) Interactive components color 3
      - `accent6` (String) Borders and separators color 1
      - `accent7` (String) Borders and separators color 2
      - `accent8` (String) Borders and separators color 3
      - `accent9` (String) Solid color 1
      - `accent10` (String) Solid color 2
      - `accent11` (String) Accessible text color 1
      - `accent12` (String) Accessible text color 2
      - `accentSurface` (String) Functional color for surface
      - `accentIndicator` (String) Functional color for accent indicator
      - `accentTrack` (String) Functional color for accent track
      - `accentContrast` (String) Functional color for accent contrast
      - `gray1` (String) Gray background 1
      - `gray2` (String) Gray background 2
      - `gray3` (String) Gray for interactive components 1
      - `gray4` (String) Gray for interactive components 2
      - `gray5` (String) Gray for interactive components 3
      - `gray6` (String) Gray for borders and separators 1
      - `gray7` (String) Gray for borders and separators 2
      - `gray8` (String) Gray for borders and separators 3
      - `gray9` (String) Gray for solid color 1
      - `gray10` (String) Gray for solid color 2
      - `gray11` (String) Gray for accessible text 1
      - `gray12` (String) Gray for accessible text 2
      - `graySurface` (String) Gray color for surface
      - `grayIndicator` (String) Gray color for accent indicator
      - `grayTrack` (String) Gray color for accent track
      - `grayContrast` (String) Gray color for accent contrast
      - `colorBackground` (String) Page background
      - `colorPanelSolid` (String) Solid panel backgrounds, such as cards, tables, popovers, dropdown menus, etc.
      - `colorPanelTranslucent` (String) Translucent panel backgrounds, such as cards, tables, popovers, dropdown menus, etc.
      - `colorSurface` (String) Form component backgrounds, such as text fields, checkboxes, select, etc.
      - `colorOverlay` (String) Dialog overlays
      - `defaultFontFamily` (String) Your custom default font
      - `headingFontFamily` (String) Your custom font for <Heading> components
      - `codeFontFamily` (String) Your custom font for <Code> components
      - `strongFontFamily` (String) Your custom font for <Strong> components
      - `emFontFamily` (String) Your custom font for <Em> components
      - `quoteFontFamily` (String) Your custom font for <Quote> components
      - `fontWeightLight` (String) Font weight for light text
      - `fontWeightRegular` (String) Font weight for regular text
      - `fontWeightMedium` (String) Font weight for medium text
      - `fontWeightBold` (String) Font weight for bold text
      - `space1` (String) Spacing for 1 unit
      - `space2` (String) Spacing for 2 units
      - `space3` (String) Spacing for 3 units
      - `space4` (String) Spacing for 4 units
      - `space5` (String) Spacing for 5 units
      - `space6` (String) Spacing for 6 units
      - `space7` (String) Spacing for 7 units
      - `space8` (String) Spacing for 8 units
      - `space9` (String) Spacing for 9 units
      - `radiusFactor` (String) Radius base variable, used for multiplying.
      - `radiusFull` (String) A variable used to calculate a fully rounded radius.
      - `radiusThumb` (String) A variable used to calculate radius of a thumb element.
    - `rules` (Object) The rules option is a map of CSS-like selectors to CSS properties, allowing granular customization of individual components.
  - `locale` (String) Locale code in ISO 639-1 format (en, fr). By default, `en` will be used

#### Return value

Returns a `Components` instance.

#### Example

```js
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`](https://www.npmjs.com/package/@chargebee/atomicpricing) NPM package. That package has since been deprecated. See [Migrate Pricing Tables from Pricify.js](https://www.chargebee.com/tutorials/pricing-table-migration-guide/).

### Pricing Table tutorials

For step-by-step integration, see the [Pricing Tables tutorials](https://www.chargebee.com/tutorials/topics/pricing-tables/).

### `pricingTable()`

Returns a [Pricing Table](https://www.chargebee.com/docs/js/pricing-table-api-ref) instance.

#### Syntax

```js
chargebee.pricingTable();
```

#### Parameters

None.

#### Return value

Returns a [Pricing Table object](https://www.chargebee.com/docs/js/pricing-table-api-ref).

#### Example

```javascript
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](https://www.chargebee.com/docs/retention/getting-started-guide/chargebee-growth-installation#install-chargebee-retentionjs-deprecated) for reference.

### Personalized Offers tutorials

For step-by-step integration, see the [Personalized Offers tutorials](https://www.chargebee.com/tutorials/topics/offers/).

### `personalizedOffers()`

Returns a [Personalized Offers](https://www.chargebee.com/docs/js/personalized-offers-api-ref) instance used to dynamically display eligible offers to the user.

#### Syntax

```js
chargebee.personalizedOffers();
```

#### Parameters

None.

#### Return value

Returns a [Personalized Offers object](https://www.chargebee.com/docs/js/personalized-offers-api-ref).

#### Example

```javascript
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](https://www.chargebee.com/tutorials/cancel-page-migration-guide/). You can still view the [legacy documentation](https://www.chargebee.com/docs/retention/settings-and-installation/installing-chargebee-retention#install-retentionjs-deprecated) for reference.

### Cancel Pages tutorials

For step-by-step integration, see the [Cancel Pages tutorials](https://www.chargebee.com/tutorials/topics/cancel-pages/).

### `cancelPage()`

Returns a [Cancel Page](https://www.chargebee.com/docs/js/cancel-page-api-ref) instance used to control and integrate cancel pages during subscription cancellation flows.

#### Syntax

```js
chargebee.cancelPage();
```

#### Parameters

None.

#### Return value

Returns a [Cancel Page object](https://www.chargebee.com/docs/js/cancel-page-api-ref).

#### Example

```html
<a id="cb-cancel" href="https://app.yourcompany.com/cancel" class="btn btn-danger">
  Cancel Subscription
</a>
```

```javascript
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](https://www.chargebee.com/tutorials/topics/payments/).

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

```js
chargebee.load(moduleName)
```

#### Parameters

**Parameters**

- `moduleName` (String, required) Name of the module to load. Allowed: `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

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

```js
chargebee.load3DSHandler()
```

#### Return value

Returns a promise that resolves to a [3DS handler object](https://www.chargebee.com/docs/js/payment-handler-api-ref#3ds-handler).

#### Example

```js
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

```js
chargebee.handlePayment(paymentMethodType, paymentOptions);
```

#### Parameters

**Parameters**

- `paymentMethodType` (Enum, required) Name of the payment method type. Allowed: `ideal`, `sofort`, `bancontact`, `dotpay`, `netbanking_emandates`, `klarna_pay_now`, `direct_debit`.
- `paymentOptions` (Object) Options for the payment method type.
  - `paymentIntent` (Function, required) Pass a function that resolves to a Payment Intent object. Learn more object.
  - `paymentInfo` (Object) 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) 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.) 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)) 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) 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)) 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: `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: `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 gatewayMobile 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) Additional information that needs to be passed for improving the chances of frictionless checkout flow.
      - `plan` (String) Plan name
      - `billingAddress` (Object) 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) 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) 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) 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) 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) 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

```js
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](https://apidocs.chargebee.com/docs/api#mbe) specified during [initialization](https://www.chargebee.com/docs/js/settingup-api-ref) is used for tokenization.

> **Tip**
>
> The generated temporary token expires after 30 minutes.

#### Syntax

```js
chargebee.tokenize(component, additionalData);
```

#### Parameters

**Parameters**

- `component` Pass card component object or component type for which you want to get Chargebee token
  - (object) Allowed: `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

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

```json
{
  "token": "cb_XAKJhqUVXuhyiJRYgLQSakdkNQad"
}
```

### `create3DSHandler()` deprecated

> **Deprecated**
>
> The `create3DSHandler()` method is deprecated. Use the [`load3DSHandler()`](#load3dshandler) method instead.

Creates a 3DS handler object after the `3ds-handler` module has been loaded using the [`load(moduleName)`](https://www.chargebee.com/docs/js/cbinstanceobj-api-ref#load-modulename) method. This is an alternative way to get a 3DS handler instance.

#### Syntax

```js
chargebee.create3DSHandler();
```

#### Return value

Returns a [3DS handler object](https://www.chargebee.com/docs/js/payment-handler-api-ref#3ds-handler).

#### Example

```js
// 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](https://www.chargebee.com/docs/js/functions-api-ref) 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)](http://ec.europa.eu/taxation_customs/vies/), which is maintained by the European Commission.

> **Prerequisite**
>
> To use EU VAT validation, you must set your [organization address](https://www.chargebee.com/docs/billing/2.0/taxes/tax#prerequisites) in Chargebee Billing.

#### `validateVat(options)`

Validates a European Union VAT number using VIES.

##### Syntax

```js
chargebee.vat.validateVat(options)
```

##### Example

```js
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

**Parameters**

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

```json
{
  "status": "VALID",
  "message": "VAT number is valid."
}
```

##### Response properties

- **`status`**: The validation result status.

<Table>
  <TableHeader>
    <TableRow>
      <TableHead>

Status

      </TableHead>
      <TableHead>

Description

      </TableHead>
    </TableRow>
  </TableHeader>
  <TableBody>
      <TableRow>
        <TableCell>

`VALID`

        </TableCell>
        <TableCell>

VAT number validation was successful and the number is valid

        </TableCell>
      </TableRow>
      <TableRow>
        <TableCell>

`INVALID`

        </TableCell>
        <TableCell>

VAT number validation failed

        </TableCell>
      </TableRow>
      <TableRow>
        <TableCell>

`UNDETERMINED`

        </TableCell>
        <TableCell>

No response from VIES or other errors occurred

        </TableCell>
      </TableRow>
  </TableBody>
</Table>

- **`message`**: Describes the response received from the VIES system
