Card Components
Deprecated
Card Components is deprecated. It still works and existing integrations are unaffected, but it's no longer the recommended approach. For new integrations, use Payment Components instead — actively maintained and built to support multiple payment methods. For what changes when you move across, see Comparison with Card Components and the Payment method helper.
Overview
This page documents the Card Components API, which allows you to create secure, card input fields integrated with Chargebee. Card components can be integrated with or without 3D Secure (3DS) authentication. The components provide a secure way to collect payment card information directly on your website.
For the conceptual overview, the workflow, and the full gateway list, see Card Components.
Tutorials
For a step-by-step integration, see the following tutorial:
Try it out
Card details can be collected in two modes.
Default mode
In default mode, the number, expiry, and CVV fields appear as a single entity.
Loading card field…
Fields mode
In fields mode, you can customize each field individually so that every field in your form looks the same.
Loading card fields…
Prerequisites
- Ensure that your payment gateway is supported by Card Components. See the list of supported gateways.
- Ensure you have initialized Chargebee.js in your application with a publishable key.
var cbInstance = Chargebee.init({
site: "YOUR_CHARGEBEE_BILLING_SUBDOMAIN", // Your test site. This is the subdomain of your Chargebee Billing site.
domain: "https://mybilling.acme.com", // This is your custom domain, if configured in Chargebee. Chargebee-hosted pages will be served from this domain.
publishableKey: "test__"
})Load the components module
load() deprecated
Loads the specified Chargebee module. This function must be called before using any card component functionality.
Important
All card component and field functionality can be used only after the components module is loaded. If you are using Chargebee wrappers, the module loading is handled automatically. Otherwise, ensure you register components after the promise resolves.
Syntax
chargebee.load(moduleName);Parameters
Return value
Returns a promise that resolves after the corresponding module has been loaded.
Example
// Load the components module before creating card components.
chargebee.load('components').then(() => {
console.log('Components module loaded successfully.');
// Now you can create and mount card components.
const cardComponent = chargebee.createComponent('card');
cardComponent.mount('#card-component');
}).catch((error) => {
console.error('Failed to load components module:', error);
});Create a card component
createComponent()
Creates a card component based on the specified componentType and configuration options.
Syntax
chargebee.createComponent(componentType, options)Parameters
Return value
Returns a Card component object that provides methods to manage the card component.
Example
tokenize() deprecated
Important
This function is not supported for Adyen gateway.
Sends the card details to the payment gateway for tokenization. The payment gateway configured for the business entity specified during initialization is used for tokenization.
The generated temporary token expires after 30 minutes.
Syntax
chargebee.tokenize(component, additionalData);Parameters
Return value
Returns a promise that resolves to a Chargebee nonce (temporary token) object.
Example
// Create a card component.
const cardComponent = chargebee.createComponent('card');
cardComponent.mount('#card-component');
// Tokenize the card with additional customer data.
chargebee.tokenize(cardComponent, {
firstName: 'John',
lastName: 'Doe',
addressLine1: '1600 Amphitheatre Parkway',
addressLine2: 'Building 42',
city: 'Mountain View',
state: 'California',
stateCode: 'CA',
zip: '94039',
countryCode: 'US'
}).then((data) => {
console.log('Chargebee token:', data.token);
// Use the token to create a payment source or subscription.
}).catch((error) => {
console.error('Tokenization failed:', error);
// Handle tokenization error.
});Response example
{
"token": "cb_XAKJhqUVXuhyiJRYgLQSakdkNQad"
}Card component object
The Card component object provides methods to manage the card component, including tokenization, 3DS authorization, event handling, and field management.
tokenize()
Important
This function is not supported for Adyen gateway.
Sends the card details to the payment gateway for tokenization. The payment gateway for processing the card details is selected based on smart routing.
If multi business entity is configured, the payment gateway configured for the business entity specified during Chargebee.js initialization init() is selected here.
Syntax
cardComponent.tokenize(additionalData)Parameters
Return value
Returns a promise that resolves to a Chargebee token object with the following structure:
{
"token": "<chargebee-token>"
}Example
const cardComponent = chargebee.createComponent("card");
cardComponent.mount("#card-component");
cardComponent.tokenize({
firstName: "John",
lastName: "Doe",
addressLine1: "1600 Amphitheatre Parkway",
addressLine2: "Suite 100",
city: "Mountain View",
state: "California",
stateCode: "CA",
zip: "94039",
countryCode: "US",
}).then((data) => {
console.log('Chargebee token:', data.token);
}).catch((error) => {
console.error('Tokenization error:', error);
});authorizeWith3ds()
Initiates 3D Secure (3DS) authorization for the card details entered in the card component fields. After successful payment authorization, the payment intent is returned with an authorized state. The paymentIntent ID can then be used to create a payment source or create a subscription.
This method internally uses the 3DS Helper provided by Chargebee.
Use webhooks for production
Use webhooks for production use, instead of making the subscription creation request from the frontend, it's more secure and reliable to respond to webhooks from Chargebee on the backend. Listen to the payment_intent_updated event via webhooks and create the subscription when the payment_intent.status is authorized.
Syntax
cardComponent.authorizeWith3ds(paymentIntent, additionalData, callbacks)Parameters
Return value
Returns a promise that resolves to an authorized payment intent object.
Example
const cardComponent = chargebee.createComponent("card");
cardComponent.mount("#card-component");
function onSubmit() {
createPaymentIntent().then(paymentIntent => {
const additionalData = {
billingAddress: {
firstName: "John",
lastName: "Doe",
billingAddr1: "1600 Amphitheatre Parkway",
billingCity: "Mountain View",
billingState: "California",
billingStateCode: "CA",
billingZip: "94039",
billingCountry: "United States",
},
document: { //Required for EBANX gateway.
type: 'br_cpf',
number: '85351346893',
},
};
return cardComponent.authorizeWith3ds(paymentIntent, additionalData)
}).then((paymentIntent) => {
console.log('payment intent authorized', paymentIntent.id);
}).catch((error) => {
console.log('payment intent refused');
});
}EBANX document verification types
dLocal document verification types
on()
Attaches event listeners to the card component. In Default mode, you can attach focus, blur, ready, and change events.
Syntax
cardComponent.on(eventType, callbackFunction)Parameters
Return value
Returns the card component object for method chaining.
Example
cardComponent.on('ready', () => {
console.log("field is ready to collect data");
})
cardComponent.on('focus', () => {
// Triggered when field is focused
})
cardComponent.on('blur', () => {
// Triggered when field is blurred
})
cardComponent.on('change', (currentState) => {
// This event will be triggered whenever the state changes from "empty" -> "complete" -> "valid" / "invalid"
// The validation errors for this field can be checked here
console.log(currentState.error);
})at() deprecated
Specifies the container element where the card component will be mounted. This method is only needed when using the card component in Default mode. Accepts either a CSS selector or a DOM Element.
Syntax
cardComponent.at(domElement);Return value
Returns the card component object for method chaining.
Example
cardComponent.at("#card-component");mount()
Inserts the card component into the DOM. The component becomes ready for collecting card details only after this method is called. The container element for mounting must be specified here. This method accepts either a DOM Element or a CSS Selector.
Syntax
cardComponent.mount('#card-component');Parameters
Return value
Returns a promise that resolves after successfully mounting the card component.
focus()
Sets keyboard focus on the card component. This method is useful when you want to programmatically focus on the card component.
Syntax
cardComponent.focus()Example
const cardComponent = chargebee.createComponent("card");
cardComponent.mount("#card-component");
function onPageLoad() {
cardComponent.focus();
}blur()
Removes keyboard focus from the card component. This method is useful when you want to programmatically blur the card component.
Syntax
cardComponent.blur();clear()
Clears the contents of card fields.
Syntax
cardComponent.clear();update()
Updates the configuration for card fields.
Syntax
cardComponent.update(options)Parameters
Example
cardComponent.update({
placeholder: '4111 1111 1111 1111'
})validateCardDetails()
Use this method to validate the entered card details.
Syntax
cardComponent.validateCardDetails()Return value
Returns a promise that resolves to true if card details are valid, and false if invalid.
Example
cardComponent.validateCardDetails().then(isValid => {
if(isValid) {
console.log('Card details are valid')
} else {
console.log('Card details are invalid')
}
})getBinData()
Retrieves the Bank Identification Number (BIN) information of a card number entered in the card fields. BIN data is returned only if the entered card number is valid. To access BIN data, add your domain, where Chargebee.js is integrated, to the domain allowlist in Chargebee Billing.
Syntax
cardComponent.getBinData()Return value
Returns a BIN data object when the card number is valid, or undefined otherwise.
{
"bin": "411111",
"last4": "1111",
"brand": "visa"
}Field | Description |
|---|---|
| First six or eight digits of the card number. |
| Last four digits of the card number. |
| Detected card network, such as |
Example
const cardComponent = chargebee.createComponent("card");
cardComponent.mount("#card-component");
const binData = cardComponent.getBinData();
if (binData) {
console.log('BIN:', binData.bin);
console.log('Last 4 digits:', binData.last4);
console.log('Card brand:', binData.brand);
}get3DSHandler()
Retrieves the Chargebee.js 3DS payment handler instance. This method can be accessed only after the 3DS payment transaction has been initiated with authorizeWith3ds().
Syntax
cardComponent.get3DSHandler()Return value
Returns a 3DS handler instance.
Example
const cardComponent = chargebee.createComponent("card");
cardComponent.mount("#card-component");
cardComponent.authorizeWith3ds(paymentIntent, {
callbacks: {
challenge: (redirect_url) => {
// Present challenge URL to user in an iframe or popup window
window.open(redirect_url, "_blank");
},
},
}).then((intent) => {
console.log('Authorization successful');
}).catch((error) => {
console.error('Authorization failed:', error);
});
function onWindowClose() {
// Call this method when user closes the popup window or iframe
const threeDSHandler = cardComponent.get3DSHandler();
threeDSHandler.cancel();
}createField()
Creates individual card fields (number, cvv, and expiry) for use in Fields mode. This method allows you to display card fields separately instead of as a single component. You can pass options to override options passed at the component level.
Syntax
cardComponent.createField(fieldType, options)Parameters
Return value
Returns a Card Field object that provides methods to manage the individual field.
Example
cardComponent.createField("number", {
placeholder: "4111 1111 1111 1111",
style: {
// override styles for default state
base: {
color: '#333',
fontWeight: '500',
fontFamily: 'Poppins,-apple-system, BlinkMacSystemFont, Segoe UI, Helvetica Neue, sans-serif',
fontSize: '16px',
fontSmoothing: 'antialiased',
':focus': {
color: '#424770',
},
'::placeholder': {
color: 'transparent',
},
':focus::placeholder': {
color: '#7b808c',
},
},
invalid: {
color: '#e41029',
':focus': {
color: '#e44d5f',
},
'::placeholder': {
color: '#FFCCA5',
},
}
},
});
cardComponent.createField("cvv")
cardComponent.createField("expiry")Card field object
The Card field object allows you to specify where individual fields should be mounted and add event listeners at the field level. Use the createField() method to create card field objects.
const numberField = cardComponent.createField("number");
const expiryField = cardComponent.createField("expiry");
const cvvField = cardComponent.createField("cvv");at()
Specifies the container element where the card field will be mounted. This method is only needed when using the card component in Fields mode. Accepts either a CSS selector or a DOM Element.
Syntax
cardField.at(domElement)Parameters
Return value
Returns the card field object for method chaining.
Example
cardField.at("#card-field");on()
Attaches event listeners to the card field. In Fields mode, only ready and change events can be attached.
Syntax
cardField.on(eventType, callbackFunction)Parameters
Return value
Returns the card field object for method chaining.
Example
const numberField = cardComponent.createField("number");
numberField.on('ready', () => {
console.log("Field is ready to collect data.");
});
numberField.on('change', (currentState) => {
// This event will be triggered whenever the state changes
// Sample status object for change event on number field with error:
// {
// type: "change", // event type
// field: "number", // field type
// cardType: "visa",
// complete: false,
// empty: false,
// error: { // Validation error object
// name: "CARD_NUMBER_INCOMPLETE",
// message: "Invalid card"
// }
// }
console.log(currentState.error);
});update()
Updates the styling of the field.
Syntax
cardField.update(options)Parameters
Return value
Returns the card field object for method chaining.
Example
cardField.update({
style: {
base: {
color: '#fff',
fontSize: `18px`
}
}
});focus()
Sets keyboard focus on the field.
Syntax
cardField.focus();blur()
Removes keyboard focus from the field.
Syntax
cardField.blur();clear()
Clears the contents of the field.
Syntax
cardField.clear();mount()
Mounts the field to the specified DOM element. This method accepts a query selector for the HTML element, or the HTML element itself where the field should be mounted.
Syntax
cardField.mount(domElement);Parameters
Return value
Returns a promise that resolves once the field is successfully mounted.
Example
// Usage 1
cardField.mount("#number-field");
// Usage 2
cardField.at("#number-field").mount();Validation error object
Whenever a validation error occurs, the error object is passed to the callback function attached to the change event. This applies to both card component and card field objects.
Chargebee JS wrappers
Chargebee provides framework-specific wrappers for Angular, React, and Vue that simplify the integration of card components and fields. These wrappers offer native directives and components that you can use directly in your applications.
Each wrapper supports two mounting modes:
- Default mode: mount the card component on its own. Chargebee renders the card number, expiry, and CVV together in a single iframe, and you can't position them individually.
- Fields mode: mount the card component as a parent and place the individual card fields inside it. Each field renders in its own iframe, so you control the layout and style each field separately.
The examples in each framework section below use default mode unless the heading says otherwise.
Angular
The card component and its fields are available as directives (cbCardField, cbNumberField, cbExpiryField, cbCvvField) in the Angular wrapper.
Card component directive
The following attributes can be set on the cbCardField directive:
Example
...
<div
cbCardField
id="card-field"
[fonts]="fonts"
[styles]="styles"
[locale]="locale"
[classes]="classes"
[placeholder]="placeholder"
></div>
...export class AppComponent {
...
styles = {
// Styles for default field state
base: {
color: '#333',
fontWeight: '500',
fontFamily: 'Lato, Segoe UI, Helvetica Neue, sans-serif',
fontSize: '16px',
fontSmoothing: 'antialiased',
':focus': {
color: '#424770',
},
'::placeholder': {
color: 'transparent',
},
':focus::placeholder': {
color: '#7b808c',
},
},
// Styles for invalid field state
invalid: {
color: '#e41029',
':focus': {
color: '#e44d5f',
},
'::placeholder': {
color: '#FFCCA5',
},
}
};
// Custom fonts
fonts = [
'https://fonts.googleapis.com/css?family=Lato:400,700'
];
// Custom placeholder
placeholder = {
number: '4111 1111 1111 1111',
expiry: 'MM / YY',
cvv: 'CVV'
};
// Custom classes
classes = {
focus: 'focus',
invalid: 'invalid',
empty: 'empty',
complete: 'complete',
};
// Locale
locale = 'en';
...
}Attach event listeners
You can attach the following event listeners to the cbCardField directive:
readyfocusblurchange
Example
<div
id="card-field"
cbCardField
class="fieldset field"
(ready)="onReady($event)"
(focus)="onFocus($event)"
(blur)="onBlur($event)"
(change)="onChange($event)"
></div>Field directives
The following attributes can be set on the field directives (cbNumberField, cbExpiryField, cbCvvField):
Attach event listeners
You can attach the following event listeners to the field directives:
readyfocusblurchange
Example
<div
id="card-number"
cbNumberField
class="fieldset field"
(ready)="onReady($event)"
(focus)="onFocus($event)"
(blur)="onBlur($event)"
(change)="onChange($event)"
></div>Fields mode example
Place the field directives inside the cbCardField directive to render and position each field separately.
<div
cbCardField
id="card-field"
[fonts]="fonts"
[styles]="styles"
locale="en"
[classes]="classes"
(ready)="onReady($event)"
>
<div
id="card-number"
cbNumberField
class="field empty"
placeholder="4111 1111 1111 1111"
(ready)="setFocus($event)"
(change)="onChange($event)"
></div>
<div
id="card-expiry"
cbExpiryField
class="field empty"
placeholder="MM / YY"
(change)="onChange($event)"
></div>
<div
id="card-cvv"
cbCvvField
class="field empty"
placeholder="CVV"
(change)="onChange($event)"
></div>
</div>React
The following components are available in the React wrapper: CardComponent, CardNumber, CardExpiry, and CardCVV.
Card component
The following props can be passed to the CardComponent:
Example
<CardComponent
className="field"
ref={this.CardRef}
icon={false}
fonts={fonts}
classes={classes}
locale={locale}
styles={styles}
placeholder={placeholder}
/>Attach event listeners
You can attach the following event listeners to the CardComponent:
readyfocusblurchange
Example
<CardComponent
className="field"
ref={this.CardRef}
onReady={this.onReady}
onFocus={this.onFocus}
onBlur={this.onBlur}
onChange={this.onChange}
/>Card field components
The following props can be passed to the field components (CardNumber, CardExpiry, CardCVV):
Example
<CardNumber
className="field"
icon={false}
styles={styles}
placeholder={"4242 4242 4242 4242"}
/>Attach event listeners
You can attach the following event listeners to the card field components:
readyfocusblurchange
Example
<CardNumber
className="field"
onReady={this.onReady}
onFocus={this.onFocus}
onBlur={this.onBlur}
onChange={this.onChange}
/>Fields mode example
Nest the field components inside CardComponent to render and position each field separately.
<CardComponent
className="field"
ref={this.CardRef}
fonts={fonts}
classes={classes}
locale={locale}
styles={styles}
onReady={this.onReady}
>
<CardNumber
className="field empty"
placeholder="4111 1111 1111 1111"
onChange={this.onChange}
onReady={this.onReady}
/>
<CardExpiry className="field empty" placeholder="MM / YY" onChange={this.onChange} />
<CardCVV className="field empty" placeholder="CVV" onChange={this.onChange} />
</CardComponent>Vue
The following components are available in the Vue wrapper: CardComponent, CardNumber, CardExpiry, and CardCVV.
Card component
The following props can be passed to the CardComponent:
Example
<card-component
class="fieldset"
ref="cardComponent"
:fonts="fonts"
:styles="styles"
:locale="locale"
:classes="classes"
:icon="icon"
:placeholder="placeholder"
></card-component>Attach event listeners
You can attach the following event listeners to the CardComponent:
readyfocusblurchange
Example
<card-component
class="fieldset"
ref="cardComponent"
@ready="onReady"
@change="onChange"
@focus="onFocus"
@blur="onBlur"
></card-component>Card field components
The following props can be passed to the field components (CardNumber, CardExpiry, CardCVV):
Example
<card-number
class="fieldset"
:styles="styles"
:classes="classes"
:placeholder="placeholder"
></card-number>Attach event listeners
You can attach the following event listeners to the card field components:
readyfocusblurchange
Example
<card-number
class="fieldset"
@ready="onReady"
@change="onChange"
@focus="onFocus"
@blur="onBlur"
></card-number>Fields mode example
Nest the field components inside card-component to render and position each field separately.
<card-component
class="fieldset"
ref="cardComponent"
:fonts="fonts"
:styles="styles"
:locale="locale"
:classes="classes"
@ready="onReady"
@change="onChange"
>
<card-number class="field empty" :placeholder="'4111 1111 1111 1111'" @focus="onFocus" />
<card-expiry class="field empty" :placeholder="'MM / YY'" @focus="onFocus" />
<card-cvv class="field empty" :placeholder="'CVV'" @focus="onFocus" />
</card-component>