Skip to main content

JavaScript API Reference


This reference provides details about the JavaScript API for creating Microform Integration web pages.

Class: Field

An instance of this class is returned when you add a Field to a Microform integration using microform.createField. With this object, you can then interact with the Field to subscribe to events, programmatically set properties in the Field, and load it to the DOM.

Methods

clear()

Programmatically clear any entered value within the field.

Example

field.clear();

dispose()

Permanently remove this field from your Microform integration.

Example

field.dispose();

focus()

Programmatically set user focus to the Microform input field.

Example

field.focus();

load(container)

Load this field into a container element on your page.

Successful loading of this field triggers a load event.

NameTypeDescription
containerHTMLElement | stringLocation in which to load this field. It can be either an HTMLElement reference or a CSS selector string that is used to load the element.

Examples

Using a CSS selector

field.load('.form-control.card-number');

Using an HTML element

const container = document.getElementById('container');field.load(container);

off(type, listener)

Unsubscribe an event handler from a Microform Field.

NameTypeDescription
typestringName of the event you wish to unsubscribe from.
listenerfunctionThe handler you wish to be unsubscribed.

Example

// subscribe to an event using .on() but keep a reference to the handler that was supplied.const focusHandler = function() { console.log('focus received'); }field.on('focus', focusHandler);// then at a later point you can remove this subscription by supplying the same arguments to .off()field.off('focus', focusHandler);

on(type, listener)

Subscribe to events emitted by a Microform Field. Supported eventTypes are:

  • autocomplete
  • blur
  • change
  • focus
  • inputSubmitRequest
  • load
  • unload
  • update

Some events might return data as the first parameter to the callback; otherwise this is undefined. For further details see each event's documentation using the links above.

NameTypeDescription
typestringName of the event you wish to subscribe to.
listenerfunctionHandler to execute when event is triggered.

Example

field.on('focus', function() {  console.log('focus received'); });

unload()

Remove the Field from the Document Object Model (DOM). This is the opposite of a load operation.

Example

field.unload();

update(options)

Update the field with new configuration options. This accepts the same parameters as microform.createField(). New options are merged into the existing configuration of the field.

NameTypeDescription
optionsobjectNew options to be merged with previous configuration.

Example

// field initially loaded as disabled with no placeholderconst number = microform.createField('number', { disabled: true });number.load('#container');// enable the field and set placeholder textnumber.update({ disabled: false, placeholder: 'Please enter your card number' });

Events

autocomplete

Emitted when a customer has used a browser or third-party tool to perform an autocomplete/autofill on the input field. Microform attempts to capture additional information from the autocompletion and supply these to the callback if available. Possible additional values returned are:

  • expirationMonth
  • expirationYear
  • name

If a value has not been supplied in the autocompletion, it is undefined in the callback data. As such, verify that it exists before use.

Examples

Possible format of data supplied to callback

{  "name": "_____",  "expirationMonth": "__",  "expirationYear": "____"}

Updating the rest of your checkout after an autocomplete event

field.on('autocomplete', function(data) {if (data.name) document.querySelector('#myName').value = data.name;if (data.expirationMonth) document.querySelector('#myMonth').value = data.expirationMonth;if (data.expirationYear) document.querySelector('#myYear').value = data.expirationYear;});

blur

This event is emitted when the input field has lost focus.

Example

field.on('blur', function() {  console.log('Field has lost focus');});// focus the field in the browser then un-focus the field to see your supplied handler execute

change

Emitted when some state has changed within the input field. The payload for this event contains several properties.

Type: object

NameType
cardobject
validboolean
couldBeValidboolean
emptyboolean

Examples

Minimal example:

field.on('change', function(data) {  console.log('Change event!');  console.log(data);});

Use the card detection result to update your UI.

const cardImage = document.querySelector('img.cardDisplay');const cardSecurityCodeLabel = document.querySelector('label[for=securityCode]');// create an object to map card names to the URL of your custom imagesconst cardImages = {	visa: '/your-images/visa.png',	mastercard: '/your-images/mastercard.png',	amex: '/your-images/amex.png',	maestro: '/your-images/maestro.png',	discover: '/your-images/discover.png',	dinersclub: '/your-images/dinersclub.png',	jcb: '/your-images/jcb.png'};field.on('change', function(data) {	if (data.card.length === 1) {		// use the card name to set the correct image src		cardImage.src = cardImages[data.card[0].name];		// update the security code label to match the detected card's naming convention		cardSecurityCodeLabel.textContent = data.card[0].securityCode.name;	} else {		// show a generic card image		cardImage.src = '/your-images/generic-card.png';	}});

Use the card detection result to filter select element in another part of your checkout.

const cardTypeOptions = document.querySelector('select[name=cardType] option');field.on('change', function(data) {  // extract the identified card types  const detectedCardTypes = data.card.map(function(c) { return c.cybsCardType; });  // disable any select options not in the detected card types list  cardTypeOptions.forEach(function (o) {    o.disabled = detectedCardTypes.includes(o.value);  });});

Updating validation styles on your form element.

const myForm = document.querySelector('form');field.on('change', function(data) {	myForm.classList.toggle('cardIsValidStyle', data.valid);	myForm.classList.toggle('cardCouldBeValidStyle', data.couldBeValid);});

focus

Emitted when the input field has received focus.

Example

field.on('focus', function() {	console.log('Field has received focus');});// focus the field in the browser to see your supplied handler execute

inputSubmitRequest

Emitted when a customer has requested submission of the input by pressing Return key or similar. By subscribing to this event you can easily replicate the familiar user experience of pressing enter to submit a form. Shown below is an example of how to implement this. The inputSubmitRequest handler will:

  1. Call Microform.createToken(). For more information, see these topics:
  1. Take the result and add it to a hidden input on your checkout.
  2. Trigger submission of the form containing the newly created token for you to use server-side.

Example

const form = document.querySelector('form');const hiddenInput = document.querySelector('form input[name=token]');field.on('inputSubmitRequest', function() {	const options = {		//	};	microform.createToken(options, function(response) {		hiddenInput.value = response.token;		form.submit();	});});

load

This event is emitted when the field has been fully loaded and is ready for user input.

Example

field.on('load', function() {	console.log('Field is ready for user input');});

unload

This event is emitted when the field has been unloaded and no longer available for user input.

Example

field.on('unload', function() {	console.log('Field has been removed from the DOM');});

update

This event is emitted when the field has been updated. The event data contains the settings that were successfully applied during this update.

Type: object

Example

field.on('update', function(data) {	console.log('Field has been updated. Changes applied were:');	console.log(data);});

Module: FLEX

Flex(captureContext)

new Flex(captureContext)

For detailed setup instructions, see Getting Started.

Parameters:

NameTypeDescription
captureContextStringJSON Web Token (JWT) string requested through a server-side authenticated call before the checkout flow starts.

Example

Basic Setup

<script src="[INSERT clientLibrary VALUE HERE]" integrity="[INSERT clientLibraryIntegrity VALUE HERE]" crossorigin="anonymous"></script><!-- Note: Script location and integrity value should be sourced from the capture context response clientLibrary and clientLibraryIntegrity values. --><script> const flex = new Flex('captureContext');</script>

Methods

microform(optionsopt) > {Microform}

This method is the main setup function used to initialize Microform Integration. Upon successful setup, the callback receives a microform, which is used to interact with the service and build the integration. For details, see Class: Microform.

NameTypeDescription
optionsObject
NameTypeAttributesDescription
stylesObject<optional>Apply custom styling to all the fields in your integration.

Returns:

Type: Microform

Examples

Minimal Setup

const flex = new Flex('header.payload.signature');const microform = flex.microform();

Custom Styling

const flex = new Flex('header.payload.signature');const microform = flex.microform({	styles: {		input: {			color: '#212529',			'font-size': '20px'		}	}});

Class: Microform

An instance of this class is returned when you create a Microform integration using flex.microform. This object allows the creation of Microform Fields. For details, see Module: Flex.

Methods

createField(fieldType, optionsopt) > {Field}

Creates a field for this Microform integration.

Parameters

NameTypeAttributesDescription
fieldTypestringSupported values: number securityCode
optionsobject<optional>These options can be changed after initialization using field.update().

Properties

NameTypeAttributesDefaultDescription
aria-labelstring<optional>trueSets the input's label for use by assistive technologies using the aria-label attribute.
aria-requiredboolean<optional>trueUsed to indicate through assistive technologies that this input is required for submission using the aria-required attribute.
autoformatBoolean<optional>trueEnables or disables automatic formatting of the input field. This is only supported for number fields and automatically inserts spaces based on the detected card type.
descriptionstring<optional>Sets the input's description for use by assistive technologies using the aria-describedby attribute.
disabledBoolean<optional>falseSets the disabled attribute on the input.
maxLengthnumber<optional>3Sets the maximum length attribute on the input. This is only supported for securityCode fields and might take a value of 3 or 4.
placeholderstring<optional>Sets the placeholder attribute on the input.
stylesstylingOptions<optional>Applies custom styling to this field.
titlestring<optional>Sets the title attribute on the input. Typically used to display tooltip text on hover.

Returns

Type: Field

Examples

Minimal Setup

const flex = new Flex('.........');const microform = flex.microform('card');const number = microform.createField('number');

Providing Custom Styles

const flex = new Flex('.........');const microform = flex.microform();const number = microform.createField('number', {	styles: {		input: {			'font-family': '"Courier New", monospace'		}	}});

Providing Custom Styles to All Fields within the Microform Integration

const flex = new Flex('.........');// apply styles to all fieldsconst microform = flex.microform('card', { styles: customStyles });// override the text color for the card number field onlyconst number = microform.createField('number', { styles: { input: { color: '#000' }}});

Providing Custom Styles to A Specific Field within the Microform Integration

const flex = new Flex('.........');const microform = flex.microform('card');const number = microform.createField('number', {    styles: {        input: {            'font-family': '"Courier New", monospace'        }    }});

Setting the Length of a Security Code Field

const flex = new Flex('.........');const microform = flex.microform('card');const securityCode = microform.createField('securityCode', {maxLength: 4});

createToken(options, callback)

Requests a token using the card data captured in the Microform fields. A successful token creation receives a transient token as its second callback parameter.

Parameter

NameTypeDescription
optionsobjectAdditional tokenization options.
callbackcallbackAny error is returned as the first callback parameter. Any successful creation of a token is returned as a string in the second parameter.

Properties

NameTypeAttributesDescription
typestring<optional>Three-digit card type string. If set, this overrides any automatic card detection.
expirationMonthstring<optional>Two-digit month string. Must be padded with leading zeros if single digit.
expirationYearstring<optional>Four-digit year string.

Examples

Minimal example omitting all optional parameters.

microform.createToken({}, function(err, token) {	if (err) {		console.error(err);		return;	}	console.log('Token successfully created!');	console.log(token);});

Override the cardType parameter using a select element that is part of your checkout.

// Assumes your checkout has a select element with option values that are  card type codes:// <select id="cardTypeOverride">//   <option value="001">Visa</option>//   <option value="002">Mastercard</option>//   <option value="003">American Express</option>//    etc...// </select>const options = {	type: document.querySelector('#cardTypeOverride').value};microform.createToken(options, function(err, token) {	// handle errors & token response});

Handling error scenarios

microform.createToken(options, function(err, token) {  if (err) {    switch (err.reason) {      case 'CREATE_TOKEN_NO_FIELDS_LOADED':        break;      case 'CREATE_TOKEN_TIMEOUT':        break;      case 'CREATE_TOKEN_NO_FIELDS':        break;      case 'CREATE_TOKEN_VALIDATION_PARAMS':        break;      case 'CREATE_TOKEN_VALIDATION_FIELDS':        break;      case 'CREATE_TOKEN_VALIDATION_SERVERSIDE':        break;      case 'CREATE_TOKEN_UNABLE_TO_START':        break;      default:        console.error('Unknown error');        break;    }  } else {    console.log('Token created: ', token);  }});

Class: MicroformError

This class defines how error scenarios are presented by Microform, primarily as the first argument to callbacks. See callback(erropt, nullable, dataopt, nullable) > {void}.

Members

(static, readonly)Reason Codes - Field Load Errors

Possible errors that can occur during the loading or unloading of a field.

Properties

NameTypeDescription
FIELD_UNLOAD_ERRORstringOccurs when you attempt to unload a field that is not currently loaded.
FIELD_ALREADY_LOADEDstringOccurs when you attempt to load a field which is already loaded.
FIELD_LOAD_CONTAINER_SELECTORstringOccurs when a Document Object Model (DOM) element cannot be located using the supplied CSS Selector string.
FIELD_LOAD_INVALID_CONTAINERstringOccurs when an invalid container parameter has been supplied.
FIELD_SUBSCRIBE_UNSUPPORTED_EVENTstringOccurs when you attempt to subscribe to an unsupported event type.
FIELD_SUBSCRIBE_INVALID_CALLBACKstringOccurs when you supply a callback that is not a function.

(static, readonly)Reason Codes - Field object Creation

Possible errors that can occur during the creation of a Field object createField(fieldType, optionsopt) > {Field}.

Properties

NameTypeDescription
CREATE_FIELD_INVALID_FIELD_TYPEstringOccurs when you try to create a field with an unsupported type.
CREATE_FIELD_DUPLICATEstringOccurs when a field of the given type has already been added to the integration.

(static, readonly)Reason Codes - Flex object Creation

Possible errors that can occur during the creation of a Flex object.

Properties

NameTypeDescription
CAPTURE_CONTEXT_INVALIDstringOccurs when you pass an invalid JWT.
CAPTURE_CONTEXT_EXPIREDstringOccurs when the JWT you pass has expired.

(static, readonly)Reason Codes - Iframe validation errors

Possible errors that can occur during the loading of an iframe.

Properties

NameTypeDescription
IFRAME_JWT_VALIDATION_FAILEDstringOccurs when the iframe cannot validate the JWT passed.
IFRAME_UNSUPPORTED_FIELD_TYPEstringOccurs when the iframe is attempting to load with an invalid field type.

(static, readonly)Reason Codes - Token creation

Possible errors that can occur during the request to create a token.

Properties

NameTypeDescription
CREATE_TOKEN_NO_FIELDS_LOADEDstringOccurs when you try to request a token, but no fields have been loaded.
CREATE_TOKEN_TIMEOUTstringOccurs when the createToken call was unable to proceed within Capture Context Validity (15 mins): Do not resend the capture context or reload Microform. Instruct the customer to retry until successful. After Capture Context Validity (>15 mins): Resend the capture context request and reload Microform.
CREATE_TOKEN_XHR_ERRORstringOccurs when there is a network error when attempting to create a token. Resend the capture context request and reload Microform.
CREATE_TOKEN_NO_FIELDSstringOccurs when the data fields are unavailable for collection.
CREATE_TOKEN_VALIDATION_PARAMSstringOccurs when there is an issue with parameters supplied to createToken.
CREATE_TOKEN_VALIDATION_FIELDSstringOccurs when there is a validation issue with data in the loaded fields. Instruct the customer to enter valid data.
CREATE_TOKEN_VALIDATION_SERVERSIDEstringOccurs when server-side validation rejects the createToken request.
CREATE_TOKEN_UNABLE_TO_STARTstringOccurs when no loaded field was able to handle the createToken request.

(nullable)correlationID :string

The correlationId of any underlying API call that resulted in this error.

Type

String

(nullable)details :array

Additional error-specific information.

Type

Array

(nullable)informationLink :string

A URL to general online documentation for this error.

Type

String

message :string

A simple human-readable description of the error that has occurred.

Type

String

reason :string

A reason corresponding to the specific error that has occurred.

Type

String

Global

Type Definitions

callback(erropt, nullable, dataopt, nullable) > {void}

Microform uses the error-first callback pattern, as commonly used in Node.js.

If an error occurs, it is returned by the first err argument of the callback. If no error occurs, err has a null value and any return data is provided in the second argument.

Parameters

NameTypeAttributesDescription
errMicroformError. See Class: MicroformError.<optional> <nullable>An Object detailing occurred errors, otherwise null.
data*<optional> <nullable>In success scenarios, this is whatever data has been returned by the asynchronous function call, if any.

Returns

Type: void

Example

This example shows how to make use of this style of error handling in your code:

foo(function (err, data) {    // check for and handle any errors    if (err) throw err;    // otherwise use the data returned    console.log(data);});

StylingOptions

Styling options are supplied as an object that resembles CSS but is limited to a subset of CSS properties that relate only to the text within the iframe.

These CSS selectors are supported:

  • input
  • ::placeholder
  • :hover
  • :focus
  • :disabled
  • valid
  • invalid
  • incomplete

These CSS properties are supported:

  • color
  • cursor
  • font
  • font-family
  • font-kerning
  • font-size
  • font-size-adjust
  • font-stretch
  • font-style
  • font-variant
  • font-variant-alternates
  • font-variant-caps
  • font-variant-east-asian
  • font-variant-ligatures
  • font-variant-numeric
  • font-weight
  • incomplete
  • line-height
  • opacity
  • text-shadow
  • text-rendering
  • transition
  • -moz-osx-font-smoothing
  • -moz-tap-highlight-color
  • -moz-transition
  • -o-transition
  • -webkit-font-smoothing
  • -webkit-tap-highlight-color
  • -webkit-transition

Any unsupported properties are not applied and raise a console.warn() alert.

Properties

NameTypeAttributesDescription
inputobject<optional>Main styling applied to the input field.
::placeholderobject<optional>Styles for the ::placeholder pseudo-element within the main input field. This also adds vendor prefixes for supported browsers.
:hoverobject<optional>Styles to apply when the input field is hovered over.
:focusobject<optional>Styles to apply when the input field has focus.
:disabledobject<optional>Styles applied when the input field has been disabled.
validobject<optional>Styles applied when Microform detects that the input card number is valid. Relies on card detection being enabled.
invalidobject<optional>Styles applied when Microform detects that the input card number is invalid. Relies on card detection being enabled.

Example

const styles = {	'input': {		'color': '#464646',		'font-size': '16px',		'font-family': 'monospace'	},	':hover': {		'font-style': 'italic'	},	'invalid': {		'color': 'red'	}};

Last published: September 29, 2026