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
- 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:
objectName | 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:
objectExample
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"></script> <script> var flex = new Flex('header.payload.signature'); </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 your integration. For details, see Class: Microform.Name | Type | Description |
---|---|---|
options | Object |
Name | Type | Attributes | Description |
---|---|---|---|
styles | Object | <optional> | 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 | <optional> | To change these options after
initialization use field.update() . |
Properties
Name | Type | Attributes | Default | Description |
---|---|---|---|---|
placeholder | string | <optional> | Sets
the placeholder attribute on the input. | |
title | string | <optional> | Sets the title attribute on the input. Typically used
to display tooltip text on hover. | |
description | string | <optional> | Sets the input's description for use by
assistive technologies using the aria-describedby attribute. | |
disabled | Boolean | <optional> | false | Sets
the disabled attribute on the input. |
autoformat | Boolean | <optional> | 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 | <optional> | 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 | <optional> | 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 | <optional> | Three digit card type string. If set,
this will override any automatic card detection. |
expirationMonth | string | <optional> | Two digit month string. Must be padded
with leading zeros if single digit. |
expirationYear | string | <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 areCybersourcecard type codes: // <select id="cardTypeOverride"> // <option value="001">Visa</option> // <option value="002">Mastercard</option> // <option value="003">American Express</option> // etc... // </select> 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 ErrorsPossible 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 CreationPossible 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 CreationPossible 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 errorsPossible 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 creationPossible 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. Resend the capture context request and reload
Microform. |
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. Instruct the customer to enter valid
data. |
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
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. | <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
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 | <optional> | Main styling applied to the input
field. |
::placeholder | object | <optional> | Styles for the ::placeholder
pseudo-element within the main input field. This also adds vendor prefixes for
supported browsers. |
:hover | object | <optional> | Styles to apply when the input field is
hovered over. |
:focus | object | <optional> | Styles to apply when the input field has
focus. |
:disabled | object | <optional> | Styles applied when the input field has
been disabled. |
valid | object | <optional> | Styles applied when Microform detects
that the input card number is valid. Relies on card detection being enabled. |
invalid | object | <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' } };
JSON Web Tokens
JSON Web Tokens (JWTs) are digitally signed JSON objects based on the open standard RFC 7519. These tokens provide a compact, self-contained
method for securely transmitting information between parties. These tokens are
signed with an RSA-encoded public/private key pair. The signature is calculated
using the header and body, which enables the receiver to validate that the content
has not been tampered with. Token-based applications are best for applications that
use browser and mobile clients.
A JWT takes the form of a string, consisting of three parts separated by dots:
- Header
- Payload
- Signature
This example shows a JWT:
xxxxx.yyyyy.zzzzz