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 will trigger a load event.
Name
|
Type
|
Description
|
---|---|---|
container
|
HTMLElement | string
|
Location in which to load this field. It can be either an HTMLElement reference or a CSS selector string that will be used to load the element.
|
Examples
Using a CSS selector
field.load('.form-control.card-number');
Using an HTML element
var container = document.getElementById('container'); field.load(container);
off(type, listener)
Unsubscribe an event handler from a Microform Field.
Name
|
Type
|
Description
|
---|---|---|
type
|
string
|
Name of the event you wish to unsubscribe from.
|
listener
|
function
|
The handler you wish to be unsubscribed.
|
Example
// subscribe to an event using .on() but keep a reference to the handler that was supplied. var 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
-
error
-
focus
-
inputSubmitRequest
-
load
-
unload
-
update
Some events may return data as the first parameter to the callback otherwise this will be undefined. For further details see each event's documentation using the links above.
Name
|
Type
|
Description
|
---|---|---|
type
|
string
|
Name of the event you wish to subscribe to.
|
listener
|
function
|
Handler to execute when event is triggered.
|
Example
field.on('focus', function() { console.log('focus received'); });
unload()
Remove a the Field from the 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 will be merged into the existing configuration of the field.
Name
|
Type
|
Description
|
---|---|---|
options
|
object
|
New options to be merged with previous configuration.
|
Example
// field initially loaded as disabled with no placeholder var number = microform.createField('number', { disabled: true }); number.load('#container'); // enable the field and set placeholder text number.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 will attempt to capture additional information from the autocompletion and supply these to the callback if available. Possible additional values returned are:
-
name
-
expirationMonth
-
expirationYear
If a value has not been supplied in the autocompletion, it will be undefined in the callback data. As such you should check for its existence 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
Name
|
Type
|
---|---|
card
|
object
|
valid
|
boolean
|
couldBeValid
|
boolean
|
empty
|
boolean
|
Examples
Minimal example:
field.on('change', function(data) { console.log('Change event!'); console.log(data); });
Use the card detection result to update your UI.
var cardImage = document.querySelector('img.cardDisplay'); var cardSecurityCodeLabel = document.querySelector('label[for=securityCode]'); // create an object to map card names to the URL of your custom images var 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 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.
var cardTypeOptions = document.querySelector('select[name=cardType] option'); field.on('change', function(data) { // extract the identified card types var 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.
var 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:
-
Call Microform.createToken().
-
Take the result and add it to a hidden input on your checkout.
-
Trigger submission of the form containing the newly created token for you to use server-side.
Example
var form = document.querySelector('form'); var hiddenInput = document.querySelector('form input[name=token]'); field.on('inputSubmitRequest', function() { var 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 will contain 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:
Name
|
Type
|
Description
|
---|---|---|
captureContext
|
String
|
JWT string that you requested via a server-side authenticated call before starting the checkout flow.
|
Example
Basic Setup
script src="https://flex.cybersource.com/cybersource/assets/microform/0.11/flex-microform.min.js">
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 your integration. For details, see Class: Microform.
Name
|
Type
|
Description
|
---|---|---|
options
|
Object
|
Name
|
Type
|
Attributes
|
Description
|
---|---|---|---|
styles
|
Object
|
|
Apply custom styling to all the fields in your integration.
|
Returns:
Type: Microform
Examples
Minimal Setup
var flex = new Flex('header.payload.signature'); var microform = flex.microform();
Custom Styling
var flex = new Flex('header.payload.signature'); var 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}
Create a field for this Microform integration.
Parameters
Name
|
Type
|
Attributes
|
Description
|
---|---|---|---|
fieldType
|
string
|
Supported values:
|
|
options
|
object
|
|
To change these options after initialization use
field.update()
.
|
Properties
Name
|
Type
|
Attributes
|
Default
|
Description
|
---|---|---|---|---|
placeholder
|
string
|
|
Sets the
placeholder
attribute on the input.
|
|
title
|
string
|
|
Sets the title attribute on the input. Typically used to display tooltip text on hover.
|
|
description
|
string
|
|
Sets the input's description for use by assistive technologies using the aria-describedby attribute.
|
|
disabled
|
Boolean
|
|
false
|
Sets the
disabled
attribute on the input.
|
autoformat
|
Boolean
|
|
true
|
Enable or disable automatic formatting of the input field. This is only supported for number fields and will automatically insert spaces based on the detected card type.
|
maxLength
|
number
|
|
3
|
Sets the maximum length attribute on the input. This is only supported for
securityCode
fields and may take a value of
3
or
4
.
|
styles
|
stylingOptions
|
|
Apply custom styling to this field
|
Returns
Type: Field
Examples
Minimal Setup
var flex = new Flex('.........'); var microform = flex.microform(); var number = microform.createField('number');
Providing Custom Styles
var flex = new Flex('.........'); var microform = flex.microform(); var number = microform.createField('number', { styles: { input: { 'font-family': '"Courier New", monospace' } } });
Setting the length of a security code field
var flex = new Flex('.........'); var microform = flex.microform(); var securityCode = microform.createField('securityCode', { maxLength: 4 });
createToken(options, callback)
Request a token using the card data captured in the Microform fields. A successful token creation will receive a transient token as its second callback parameter.
Parameter
Name
|
Type
|
Description
|
---|---|---|
options
|
object
|
Additional tokenization options.
|
callback
|
callback
|
Any error will be returned as the first callback parameter. Any successful creation of a token will be returned as a string in the second parameter.
|
Properties
Name
|
Type
|
Attributes
|
Description
|
---|---|---|---|
type
|
string
|
|
Three digit card type string. If set, this will override any automatic card detection.
|
expirationMonth
|
string
|
|
Two digit month string. Must be padded with leading zeros if single digit.
|
expirationYear
|
string
|
|
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 areCybersourcecard type codes: // var 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
Name
|
Type
|
Description
|
---|---|---|
FIELD_UNLOAD_ERROR
|
string
|
Occurs when you attempt to unload a field that is not currently loaded.
|
FIELD_ALREADY_LOADED
|
string
|
Occurs when you attempt to load a field which is already loaded.
|
FIELD_LOAD_CONTAINER_SELECTOR
|
string
|
Occurs when a DOM element cannot be located using the supplied CSS Selector string.
|
FIELD_LOAD_INVALID_CONTAINER
|
string
|
Occurs when an invalid container parameter has been supplied.
|
FIELD_SUBSCRIBE_UNSUPPORTED_EVENT
|
string
|
Occurs when you attempt to subscribe to an unsupported event type.
|
FIELD_SUBSCRIBE_INVALID_CALLBACK
|
string
|
Occurs 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
Name
|
Type
|
Description
|
---|---|---|
CREATE_FIELD_INVALID_FIELD_TYPE
|
string
|
Occurs when you try to create a field with an unsupported type.
|
CREATE_FIELD_DUPLICATE
|
string
|
Occurs when a field of the given type has already been added to your integration.
|
(static, readonly)
Reason Codes - Flex object Creation
Possible errors that can occur during the creation of a Flex object.
Properties
Name
|
Type
|
Description
|
---|---|---|
CAPTURE_CONTEXT_INVALID
|
string
|
Occurs when you pass an invalid JWT.
|
CAPTURE_CONTEXT_EXPIRED
|
string
|
Occurs 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
Name
|
Type
|
Description
|
---|---|---|
IFRAME_JWT_VALIDATION_FAILED
|
string
|
Occurs when the iframe cannot validate the JWT passed.
|
IFRAME_UNSUPPORTED_FIELD_TYPE
|
string
|
Occurs 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
Name
|
Type
|
Description
|
---|---|---|
CREATE_TOKEN_NO_FIELDS_LOADED
|
string
|
Occurs when you try to request a token, but no fields have been loaded.
|
CREATE_TOKEN_TIMEOUT
|
string
|
Occurs when the
createToken
call was unable to proceed.
|
CREATE_TOKEN_XHR_ERROR
|
string
|
Occurs when there is a network error when attempting to create a token.
|
CREATE_TOKEN_NO_FIELDS
|
string
|
Occurs when the data fields are unavailable for collection.
|
CREATE_TOKEN_VALIDATION_PARAMS
|
string
|
Occurs when there's an issue with parameters supplied to
createToken
.
|
CREATE_TOKEN_VALIDATION_FIELDS
|
string
|
Occurs when there's a validation issue with data in your loaded fields.
|
CREATE_TOKEN_VALIDATION_SERVERSIDE
|
string
|
Occurs when server-side validation rejects the
createToken
request.
|
CREATE_TOKEN_UNABLE_TO_START
|
string
|
Occurs 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 link 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
Events
You can subscribe to
Microform Integration
events and obtain them through event listeners. Using these events, you can easily enable your checkout user interface to respond to any state changes as soon as they happen.
Event Name
|
Emitted When
|
---|---|
autocomplete
|
Customer fills the credit card number using a browser or third-party extension. This event provides a hook onto the additional information provided during the
autocomplete
event.
|
blur
|
Field loses focus.
|
change
|
Field contents are edited by the customer. This event contains various data such as validation information and details of any detected card types.
|
focus
|
Field gains focus.
|
inputSubmitRequest
|
Customer requests submission of the field by pressing the Return key or similar.
|
load
|
Field has been loaded on the page and is ready for user input.
|
unload
|
Field is removed from the page and no longer available for user input.
|
update
|
Field configuration was updated with new options.
|
Some events may return data to the event listener’s callback as described in the next section.
Subscribing to Events
Using the
.on()
method provided in the
microformInstance
object, you can easily subscribe to any of the supported events.
For example, you could listen for the
change
event and in turn display appropriate card art and display brand-specific information.
var secCodeLbl = document.querySelector('#mySecurityCodeLabel'); var numberField = flex.createField('number'); // Update your security code label to match the detected card type's terminology numberField.on('change', function(data) { secCodeLbl.textContent = (data.card && data.card.length > 0) ? data.card[0].securityCode.name : 'CVN'; }); numberField.load('#myNumberContainer');
The
data
object supplied to the event listener’s callback includes any information specific to the triggered event.
Card Detection
By default, Microform attempts to detect the card type as it is entered. Detection info is bubbled outwards in the
change
event. You can use this information to build a dynamic user experience, providing feedback to the user as they type their card number.
{ "card": [ { "name": "mastercard", "brandedName": "MasterCard", "cybsCardType": "002", "spaces": [ 4, 8, 12], "lengths": [16], "securityCode": { "name": "CVC", "length": 3 }, "luhn": true, "valid": false, "couldBeValid": true }, /* other identified card types */ ] }
If
Microform Integration
is unable to determine a single card type, you can use this information to prompt the customer to choose from a possible range of values.
If
type
is specified in the
microformInstance.createToken(options,...)
method, the specified value always takes precedence over the detected value.
Autocomplete
By default,
Microform Integration
supports the autocomplete event of the
cardnumber
field provided by certain browsers and third-party extensions. An
autocomplete
event is provided to allow easy access to the data that was provided to allow integration with other elements in your checkout process.
The format of the data provided in the event might be as follows:
{ name: '_____', expirationMonth: '__', expirationYear: '____' }
These properties are in the object only if they contain a value; otherwise, they are undefined. Check for the properties before using the event. The following example displays how to use this event to update other fields in your checkout process:
var number = microform.createField('number'); number.on('autocomplete', function(data) { if (data.name) document.querySelector('#myName').value = data.name; if (data.expirationMonth) document.querySelector('#myMonth').value = data.expirationMonth; java.io.PrintWriter@136ffc65 if (data.expirationYear) document.querySelector('#myYear').value = data.expirationYear; });
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
Name
|
Type
|
Attributes
|
Description
|
---|---|---|---|
err
|
MicroformError. See Class: MicroformError.
|
|
An Object detailing occurred errors, otherwise null.
|
data
|
*
|
|
In success scenarios, this is whatever data has been returned by the asynchronous function call, if any.
|
Returns
Type: void
Example
The following 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.
Supported CSS selectors:
-
input
-
::placeholder
-
:hover
-
:focus
-
:disabled
-
valid
-
invalid
Supported CSS properties:
-
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
-
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 will not be applied and raise a
console.warn()
.
Properties
Name
|
Type
|
Attributes
|
Description
|
---|---|---|---|
input
|
object
|
|
Main styling applied to the input field.
|
::placeholder
|
object
|
|
Styles for the ::placeholder pseudo-element within the main input field. This also adds vendor prefixes for supported browsers.
|
:hover
|
object
|
|
Styles to apply when the input field is hovered over.
|
:focus
|
object
|
|
Styles to apply when the input field has focus.
|
:disabled
|
object
|
|
Styles applied when the input field has been disabled.
|
valid
|
object
|
|
Styles applied when Microform detects that the input card number is valid. Relies on card detection being enabled.
|
invalid
|
object
|
|
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' } };