# 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 and Portal

The Checkout and Portal functions enable you to manage subscription checkout flows and customer self-service portals. These functions help you provide your customers with the ability to subscribe to your services and manage their accounts efficiently.

# 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 the Chargebee Checkout page in a modal or new window. This function handles the complete checkout flow including payment processing and subscription creation.

# 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

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

Early Access

The Payment Components feature is in early access. To request access, submit a request (opens new window) via Chargebee Billing.

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

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

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

# cancelPage()

Returns a Cancel Page instance used 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 3D Secure authentication and various payment methods.

# 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
giropay
dotpay
paypal
netbanking_emandates
apple-pay
upi
payconiq_by_bancontact
venmo

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

# create3DSHandler()

Creates a 3DS handler object after the 3ds-handler module has been loaded. 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

# 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
giropay
dotpay
netbanking_emandates
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 gateway
Name of the end-user..
userEmail
String Required if Using Stripe gateway
Mail ID of the end-user.
country
String Required if Using Stripe SOFORT payment method
Country name.
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 via GoCardless, Autogiro via GoCardless, and BACS via GoCardless
Use this flag to determine whether or not to use the payment gateway is during the checkout process.
customer
Object Required if Using Netbanking, UPI, Direct Debit via Adyen, Stripe, Bluesnap, and GoCardless SEPA, ACH via GoCardless, ACH via Bluesnap, Autogiro via GoCardless, BACS via GoCardless Hide properties
Customer with whom the subscription will be associated
firstName
String
First name
lastName
String
Last name
email
String
E-mail address
phone
String
Phone number
bankAccount
Object Required if Using Netbanking and Direct Debit via Adyen, Stripe, Bluesnap, and GoCardless SEPA, ACH via GoCardless, ACH via Bluesnap, Autogiro via GoCardless, BACS via 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 Direct debit via Adyen, Stripe, GoCardless, and Bluesnap SEPA.
Account holder’s International Bank Account Number.
nameOnAccount
String
The name of the individual or entity that is associated with a particular bank account.
routingNumber
String
A code that is used to identify financial organisations or banks when making a payment
accountHolderType
String
Specifies the type of entity that holds a particular bank account, such as an individual or a business.
Allowed Values:
Indvidual
Company
bankCode
String
A unique identifier assigned by financial institutions to identify a specific bank branch in a country's banking system.
countryCode
String
A two-letter code used to identify a country, as defined by the ISO 3166-1 standard.
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.
vpa
String Required if using UPI
Virtual Payment Address (VPA) is a unique ID created by the user to send or receive money through UPI(mandates). Having a VPA, linked with a UPI(mandates)-enabled Bank, enables you to receive money in your bank account without sharing your account details.
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

# Functions

This section provides utility functions for subscription estimates and VAT validation. These functions help you calculate costs and validate customer information before processing payments.

# Available functions

  • Estimates
    • createSubscriptionEstimate() - Calculate costs for new subscriptions.
    • updateSubscriptionEstimate() - Calculate costs for subscription changes.
    • renewSubscriptionEstimate() - Calculate costs for subscription renewals.
  • VAT Validation
    • validateVat() - Validate EU VAT numbers.

# Estimate Functions

Estimate functions allow you to calculate the costs and details of subscription operations without actually performing them. This is useful for displaying pricing information to customers before they commit to a purchase or subscription change.

For example, if you want to create a new subscription or update an existing one, you can calculate details such as:

  • The amount the customer will be charged.
  • The subscription state after the operation.
  • Tax calculations and discounts.
  • Proration amounts for mid-cycle changes.

# createSubscriptionEstimate(options)

Generates an estimate (opens new window) for creating a new subscription and customer record. This function calculates the costs and details without actually creating the subscription, allowing you to show customers what they'll be charged.

# Syntax
chargebee.estimates.createSubscriptionEstimate(options)
1
# Example
const chargebee = Chargebee.getInstance();

// Load the functions module first.
chargebee.load('functions').then(() => {
  const options = {
    // Subscription configuration options.
  };
  
  chargebee.estimates.createSubscriptionEstimate(options)
    .then(data => {
      console.log('Subscription estimate:', data);
      // Display pricing information to customer.
    })
    .catch(err => {
      console.error('Failed to create estimate:', err);
    });
});
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# Parameters
DETAILS
billing_cycles
Number
Number of cycles(plan interval) this subscription should be charged. After the billing cycles exhausted, the subscription will be cancelled
terms_to_charge
Number
The number of future renewals for which advance invoicing is done. However, if a new term gets started in this operation, the specified terms_to_charge will be inclusive of this new term.
billing_alignment_mode
String
Applicable when calendar billing is enabled and subscription is getting created in active / non_renewing states. Unless specified the configured default value will be used.
Allowed Values:
immediate
delayed
mandatory_addons_to_remove
Array
List of addons IDs that are mandatory to the plan and has to be removed from the subscription
coupon_ids
Array
Identifier of the coupon as a List. Coupon Codes can also be passed
invoice_immediately
Boolean
Applicable when charges are added during this operation. If specified as false, these charges will be added to unbilled charges. The default value for this parameter will be as per your site settings
client_profile_id
String
Indicates the Client profile id for the customer. This is applicable only if you use Chargebee’s AvaTax for Communications integration.
subscription
Object Hide properties
Subscription details
id
String
A unique identifier to identify the subscription. You will use this to perform all operations on this subscription.
plan_id
String Required
Identifier of the plan for this subscription
plan_quantity
Number
Plan quantity for this subscription
plan_unit_price
Number
Amount that will override the Plan's default price (in cents)
setup_fee
Number
Amount that will override the default setup fee (in cents)
start_date
UTC timestamp
Allows you to specify a future date or a past date on which the subscription starts.Past dates can be entered in case the subscription has already started. Any past date entered must be within the current billing cycle/plan term. The subscription will start immediately if this parameter is not passed
trial_end
UTC timestamp
The time at which the trial ends for this subscription. Can be specified to override the default trial period.If '0' is passed, the subscription will be activated immediately
billing_address
Object Hide properties
Parameters for Billing Address
line1
String
Address line 1
line2
String
Address line 2
line3
String
Address line 3
city
String
City
state_code
String
The ISO 3166-2 state/province code without the country prefix. Currently supported for USA, Canada and India. For instance, for Arizona (USA), set the state_code as AZ (not US-AZ). or, for Tamil Nadu (India), set the state_code as TN (not IN-TN). or, for British Columbia (Canada), set the state_code as BC (not CA-BC). Note: If the 'state_code' is specified, the 'state' attribute should not be provided as Chargebee will set the value automatically (for US, Canada, India).
zip
String
Zip or Postal code
country
String
2-letter ISO 3166 alpha-2 country code
country
String
2-letter ISO 3166 alpha-2 country code
validation_status
String
The address verification status
Allowed Values:
not_validated
valid
partially_valid
invalid
shipping_address
Object Hide properties
Parameters for Shipping Address
line1
String
Address line 1
line2
String
Address line 2
line3
String
Address line 3
city
String
City
state_code
String
The ISO 3166-2 state/province code without the country prefix. Currently supported for USA, Canada and India. For instance, for Arizona (USA), set the state_code as AZ (not US-AZ). or, for Tamil Nadu (India), set the state_code as TN (not IN-TN). or, for British Columbia (Canada), set the state_code as BC (not CA-BC). Note: If the 'state_code' is specified, the 'state' attribute should not be provided as Chargebee will set the value automatically (for US, Canada, India).
zip
String
Zip or Postal code
country
String
2-letter ISO 3166 alpha-2 country code
country
String
2-letter ISO 3166 alpha-2 country code
validation_status
String
The address verification status
Allowed Values:
not_validated
valid
partially_valid
invalid
customer
Object Hide properties
Parameters for customer
vat_number
String
VAT number of this customer. VIES validation will not happen for this parameter
registered_for_gst
String
Confirms that a customer is registered under GST. This field is available for Australia only
taxability
String
Specifies if the customer is liable for tax
Allowed Values:
taxable
exempt
entity_code
String
The exemption category of the customer, for USA and Canada. Applicable if you use Chargebee's AvaTax for Sales integration.
Allowed Values:
a
b
c
d
e
f
g
h
i
j
k
l
m
n
p
q
r
med1
med2
exempt_number
String
Any string value that will cause the sale to be exempted. Use this if your finance team manually verifies and tracks exemption certificates. Applicable if you use Chargebee's AvaTax for Sales integration
exemption_details
String
Indicates the exemption information. You can customize customer exemption based on specific Location, Tax level (Federal, State, County and Local), Category of Tax or specific Tax Name. This is applicable only if you use Chargebee’s AvaTax for Communications integration. To know more about what values you need to provide, refer to this Avalara’s API document.
customer_type
String
Indicates the type of the customer. This is applicable only if you use Chargebee’s AvaTax for Communications integration
Allowed Values:
residential
business
senior_citizen
industrial
addons
Array<Object>
Parameters for addons. Multiple addon objects can be passed in the array
Object Hide properties
id
String
Identifier of the addon.
quantity
Number
Addon quantity. Applicable only for the quantity based addons
unit_price
Number
Amount that will override the Addon's default price. The Plan's billing frequency will not be considered for overriding. For example: If the Plan's billing frequency is every 3 months, and if the price override amount is $10, $10 will be used, and not $30 (i.e $10*3). (in cents)
billing_cycles
Number
Number of billing cycles the addon will be charged for
trial_end
Number
The time at which the trial ends for the addon. In order to use this param please contact support@chargebee.com.
event_based_addons
Array<Object>
Parameters for event_based_addons. Multiple event_based_addon objects can be passed in the array
Object Hide properties
id
String
A unique 'id' used to identify the addon
quantity
Number
Addon quantity. Applicable only for the quantity based addons.
unit_price
Number
Amount that will override the Addon's default price
service_period_in_days
Number
Defines service period of the addon in days from the day of charge
on_event
String
Event on which this addon will be charged
Allowed Values:
subscription_creation
subscription_trial_start
plan_activation
subscription_activation
charge_once
Boolean
If enabled, the addon will be charged only at the first occurrence of the event. Applicable only for non-recurring add-ons
charge_on
String
Indicates when the non-recurring addon will be charged
Allowed Values:
immediately
on_event
# Return value

Returns an estimate (opens new window) object containing the subscription estimate details.

# Response example
{
  "estimate": {
    "created_at": 1517507462,
    "invoice_estimate": {
      "amount_due": 895,
      "amount_paid": 0,
      "credits_applied": 0,
      "currency_code": "USD",
      "date": 1517507462,
      "line_item_discounts": [],
      "line_item_taxes": [],
      "line_items": [
        {
          "amount": 895,
          "date_from": 1517507462,
          "date_to": 1519926662,
          "description": "No Trial",
          "discount_amount": 0,
          "entity_id": "no_trial",
          "entity_type": "plan",
          "id": "li___test__5SK0bLNFRFuFFZLf3",
          "is_taxed": false,
          "item_level_discount_amount": 0,
          "object": "line_item",
          "pricing_model": "per_unit",
          "quantity": 1,
          "tax_amount": 0,
          "unit_amount": 895
        }
      ],
      "object": "invoice_estimate",
      "price_type": "tax_exclusive",
      "recurring": true,
      "round_off_amount": 0,
      "sub_total": 895,
      "taxes": [],
      "total": 895
    },
    "object": "estimate",
    "subscription_estimate": {
      "currency_code": "USD",
      "next_billing_at": 1519926662,
      "object": "subscription_estimate",
      "status": "active"
    }
  }
}
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
41
42
43
44
45
46
47

# updateSubscriptionEstimate(options)

Generates an estimate for updating an existing subscription. This function calculates the costs and changes without actually modifying the subscription, allowing you to show customers the impact of their changes.

# Syntax
chargebee.estimates.updateSubscriptionEstimate(options)
1
# Example
const chargebee = Chargebee.getInstance();

// Load the functions module first.
chargebee.load('functions').then(() => {
  const options = {
    // Subscription update configuration options.
  };
  
  chargebee.estimates.updateSubscriptionEstimate(options)
    .then(data => {
      console.log('Subscription update estimate:', data);
      // Display pricing changes to customer.
    })
    .catch(err => {
      console.error('Failed to create update estimate:', err);
    });
});
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# Parameters
DETAILS
billing_cycles
Number
Number of cycles(plan interval) this subscription should be charged. After the billing cycles exhausted, the subscription will be cancelled
terms_to_charge
Number
The number of future renewals for which advance invoicing is done. However, if a new term gets started in this operation, the specified terms_to_charge will be inclusive of this new term.
billing_alignment_mode
String
Applicable when calendar billing is enabled and subscription is getting created in active / non_renewing states. Unless specified the configured default value will be used.
Allowed Values:
immediate
delayed
mandatory_addons_to_remove
Array
List of addons IDs that are mandatory to the plan and has to be removed from the subscription
coupon_ids
Array
Identifier of the coupon as a List. Coupon Codes can also be passed
invoice_immediately
Boolean
Applicable when charges are added during this operation. If specified as false, these charges will be added to unbilled charges. The default value for this parameter will be as per your site settings
subscription
Object Hide properties
Subscription details
id
String
A unique identifier to identify the subscription. You will use this to perform all operations on this subscription.
plan_id
String Required
Identifier of the plan for this subscription
plan_quantity
Number
Plan quantity for this subscription
plan_unit_price
Number
Amount that will override the Plan's default price (in cents)
setup_fee
Number
Amount that will override the default setup fee (in cents)
start_date
UTC timestamp
Allows you to specify a future date or a past date on which the subscription starts.Past dates can be entered in case the subscription has already started. Any past date entered must be within the current billing cycle/plan term. The subscription will start immediately if this parameter is not passed
trial_end
UTC timestamp
The time at which the trial ends for this subscription. Can be specified to override the default trial period.If '0' is passed, the subscription will be activated immediately
billing_address
Object Hide properties
Parameters for Billing Address
line1
String
Address line 1
line2
String
Address line 2
line3
String
Address line 3
city
String
City
state_code
String
The ISO 3166-2 state/province code without the country prefix. Currently supported for USA, Canada and India. For instance, for Arizona (USA), set the state_code as AZ (not US-AZ). or, for Tamil Nadu (India), set the state_code as TN (not IN-TN). or, for British Columbia (Canada), set the state_code as BC (not CA-BC). Note: If the 'state_code' is specified, the 'state' attribute should not be provided as Chargebee will set the value automatically (for US, Canada, India).
zip
String
Zip or Postal code
country
String
2-letter ISO 3166 alpha-2 country code
country
String
2-letter ISO 3166 alpha-2 country code
validation_status
String
The address verification status
Allowed Values:
not_validated
valid
partially_valid
invalid
shipping_address
Object Hide properties
Parameters for Shipping Address
line1
String
Address line 1
line2
String
Address line 2
line3
String
Address line 3
city
String
City
state_code
String
The ISO 3166-2 state/province code without the country prefix. Currently supported for USA, Canada and India. For instance, for Arizona (USA), set the state_code as AZ (not US-AZ). or, for Tamil Nadu (India), set the state_code as TN (not IN-TN). or, for British Columbia (Canada), set the state_code as BC (not CA-BC). Note: If the 'state_code' is specified, the 'state' attribute should not be provided as Chargebee will set the value automatically (for US, Canada, India).
zip
String
Zip or Postal code
country
String
2-letter ISO 3166 alpha-2 country code
country
String
2-letter ISO 3166 alpha-2 country code
validation_status
String
The address verification status
Allowed Values:
not_validated
valid
partially_valid
invalid
customer
Object Hide properties
Parameters for customer
vat_number
String
VAT number of this customer. VIES validation will not happen for this parameter
registered_for_gst
String
Confirms that a customer is registered under GST. This field is available for Australia only
taxability
String
Specifies if the customer is liable for tax
Allowed Values:
taxable
exempt
entity_code
String
The exemption category of the customer, for USA and Canada. Applicable if you use Chargebee's AvaTax for Sales integration.
Allowed Values:
a
b
c
d
e
f
g
h
i
j
k
l
m
n
p
q
r
med1
med2
exempt_number
String
Any string value that will cause the sale to be exempted. Use this if your finance team manually verifies and tracks exemption certificates. Applicable if you use Chargebee's AvaTax for Sales integration
exemption_details
String
Indicates the exemption information. You can customize customer exemption based on specific Location, Tax level (Federal, State, County and Local), Category of Tax or specific Tax Name. This is applicable only if you use Chargebee’s AvaTax for Communications integration. To know more about what values you need to provide, refer to this Avalara’s API document.
customer_type
String
Indicates the type of the customer. This is applicable only if you use Chargebee’s AvaTax for Communications integration
Allowed Values:
residential
business
senior_citizen
industrial
addons
Array<Object>
Parameters for addons. Multiple addon objects can be passed in the array
Object Hide properties
id
String
Identifier of the addon.
quantity
Number
Addon quantity. Applicable only for the quantity based addons
unit_price
Number
Amount that will override the Addon's default price. The Plan's billing frequency will not be considered for overriding. For example: If the Plan's billing frequency is every 3 months, and if the price override amount is $10, $10 will be used, and not $30 (i.e $10*3). (in cents)
billing_cycles
Number
Number of billing cycles the addon will be charged for
trial_end
Number
The time at which the trial ends for the addon. In order to use this param please contact support@chargebee.com.
event_based_addons
Array<Object>
Parameters for event_based_addons. Multiple event_based_addon objects can be passed in the array
Object Hide properties
id
String
A unique 'id' used to identify the addon
quantity
Number
Addon quantity. Applicable only for the quantity based addons.
unit_price
Number
Amount that will override the Addon's default price
service_period_in_days
Number
Defines service period of the addon in days from the day of charge
on_event
String
Event on which this addon will be charged
Allowed Values:
subscription_creation
subscription_trial_start
plan_activation
subscription_activation
charge_once
Boolean
If enabled, the addon will be charged only at the first occurrence of the event. Applicable only for non-recurring add-ons
charge_on
String
Indicates when the non-recurring addon will be charged
Allowed Values:
immediately
on_event
replace_addon_list
Boolean
Should be true if the existing addons should be replaced with the ones that are being passed
reactivate_from
UTC timestamp
The time from which this subscription should be reactivated.
replace_coupon_list
Boolean
Should be true if the existing coupons should be replaced with the ones that are being passed.
prorate
Boolean
Add Prorated Credits and Charges, if applicable, while updating the subscription. If this parameter is not passed, the default value set in the site settings will be used. Else, it will be assumed as true.
end_of_term
Boolean
You can specify when you want to update the subscription.
force_term_reset
Boolean
Applicable for 'Active' & 'Non Renewing' states alone. Generally, subscription's term will be reset (i.e current term is ended and a new term starts immediately) when a new plan having different billing frequency is specified in the input. For all other cases, the subscription's term will remain intact. Now for this later scenario, if you want to force a term reset you can specify this param as 'true'. Note: Specifying this value as 'false' has no impact on the default behavior.
reactivate
Boolean
Applicable only for canceled subscriptions. Once this is passed as true, canceled subscription will become active; otherwise subscription changes will be made but the the subscription state will remain canceled. If not passed, subscription will be activated only if there is any change in subscription data.
include_delayed_charges
Boolean
If true, all unbilled charges will be included for the invoice estimate.
use_existing_balances
Boolean
If true, all existing balances - promotional credits, refundable credits and excess payments - will be included for the invoice estimate.
# Return value

Returns an estimate (opens new window) object containing the subscription update estimate details.

# Response example
{
  "estimate": {
    "created_at": 1517507463,
    "credit_note_estimates": [
      {
        "amount_allocated": 895,
        "amount_available": 0,
        "currency_code": "USD",
        "line_item_discounts": [],
        "line_item_taxes": [],
        "line_items": [
          {
            "amount": 895,
            "date_from": 1517507463,
            "date_to": 1519926663,
            "description": "No Trial - Prorated Credits for 01-Feb-2018 - 01-Mar-2018",
            "discount_amount": 0,
            "entity_id": "no_trial",
            "entity_type": "plan",
            "id": "li___test__5SK0bLNFRFuFFhhfS",
            "is_taxed": false,
            "item_level_discount_amount": 0,
            "object": "line_item",
            "pricing_model": "per_unit",
            "quantity": 1,
            "subscription_id": "__test__5SK0bLNFRFuFFekfI",
            "tax_amount": 0,
            "unit_amount": 895
          }
        ],
        "object": "credit_note_estimate",
        "price_type": "tax_exclusive",
        "reference_invoice_id": "__demo_inv__6",
        "round_off_amount": 0,
        "sub_total": 895,
        "taxes": [],
        "total": 895,
        "type": "adjustment"
      }
    ],
    "invoice_estimate": {
      "amount_due": 1500,
      "amount_paid": 0,
      "credits_applied": 0,
      "currency_code": "USD",
      "date": 1517507463,
      "line_item_discounts": [],
      "line_item_taxes": [],
      "line_items": [
        {
          "amount": 1500,
          "date_from": 1517507463,
          "date_to": 1519926663,
          "description": "Plan1 - Prorated Charges",
          "discount_amount": 0,
          "entity_id": "plan1",
          "entity_type": "plan",
          "id": "li___test__5SK0bLNFRFuFFhbfQ",
          "is_taxed": false,
          "item_level_discount_amount": 0,
          "object": "line_item",
          "pricing_model": "per_unit",
          "quantity": 1,
          "subscription_id": "__test__5SK0bLNFRFuFFekfI",
          "tax_amount": 0,
          "unit_amount": 1500
        }
      ],
      "object": "invoice_estimate",
      "price_type": "tax_exclusive",
      "recurring": true,
      "round_off_amount": 0,
      "sub_total": 1500,
      "taxes": [],
      "total": 1500
    },
    "object": "estimate",
    "subscription_estimate": {
      "currency_code": "USD",
      "id": "__test__5SK0bLNFRFuFFekfI",
      "next_billing_at": 1519926663,
      "object": "subscription_estimate",
      "status": "active"
    }
  }
}
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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86

# renewSubscriptionEstimate(options)

Calculates an estimate of the amount that will be charged when the subscription is billed next. The estimate is based on the current recurring items of the subscription including plans, addons, and coupons.

# Syntax
chargebee.estimates.renewSubscriptionEstimate(options)
1
# Example
const chargebee = Chargebee.getInstance();

// Load the functions module first.
chargebee.load('functions').then(() => {
  const options = {
    // Subscription renewal configuration options.
  };
  
  chargebee.estimates.renewSubscriptionEstimate(options)
    .then(data => {
      console.log('Subscription renewal estimate:', data);
      // Display next billing amount to customer.
    })
    .catch(err => {
      console.error('Failed to create renewal estimate:', err);
    });
});
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# Parameters
DETAILS
subscription
Object Hide properties
Subscription details.
id
String Required
A unique identifier to identify the subscription.
include_delayed_charges
Boolean
If true, all unbilled charges will be included for the invoice estimate.
use_existing_balances
Boolean
If true, all existing balances - promotional credits, refundable credits and excess payments - will be included for the invoice estimate.
ignore_scheduled_cancellation
Boolean
if true, ignores scheduled cancellation for non renewing subscription
ignore_scheduled_changes
Boolean
If true, ignores all recurring charges scheduled during renewal
# Return value

Returns an estimate (opens new window) object, containing the subscription renewal estimate details.

# Response example
{
  "estimate": {
    "created_at": 1517507462,
    "invoice_estimate": {
      "amount_due": 895,
      "amount_paid": 0,
      "credits_applied": 0,
      "currency_code": "USD",
      "line_item_discounts": [],
      "line_item_taxes": [],
      "line_items": [
        {
          "amount": 895,
          "date_from": 1519926661,
          "date_to": 1522605061,
          "description": "No Trial",
          "discount_amount": 0,
          "entity_id": "no_trial",
          "entity_type": "plan",
          "id": "li___test__5SK0bLNFRFuFFNnek",
          "is_taxed": false,
          "item_level_discount_amount": 0,
          "object": "line_item",
          "pricing_model": "per_unit",
          "quantity": 1,
          "subscription_id": "__test__5SK0bLNFRFuFFLAed",
          "tax_amount": 0,
          "unit_amount": 895
        }
      ],
      "object": "invoice_estimate",
      "price_type": "tax_exclusive",
      "recurring": true,
      "round_off_amount": 0,
      "sub_total": 895,
      "taxes": [],
      "total": 895
    },
    "object": "estimate",
    "subscription_estimate": {
      "currency_code": "USD",
      "id": "__test__5SK0bLNFRFuFFLAed",
      "next_billing_at": 1519926661,
      "object": "subscription_estimate",
      "status": "active"
    }
  }
}
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
41
42
43
44
45
46
47
48

# 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
2-letter ISO 3166 alpha-2 country code
vat_number
String
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