NAV
Spreedly Logo

iFrame Javascript API

These are the API docs for version 1 of the Spreedly iFrame Javascript API.

The Spreedly iFrame is available from the following URL:

https://core.spreedly.com/iframe/iframe-v1.min.js

// Invoke methods on the "Spreedly" global object,
// for instance...
Spreedly.validate();

By default, an instance of the Spreedly iFrame will be available on the host page as Spreedly. Invoke the functions described in these docs using the Spreedly object.

Lifecycle

Including the iFrame Javascript file on a checkout page does not automatically load the library. The iFrame’s lifecycle must be explictly managed using these functions.

init

Spreedly.init("C7cRfNJGODKh4Iu5Ox3PToKjniY", {
  "numberEl": "spreedly-number",
  "cvvEl": "spreedly-cvv"
});

Initialize the iFrame library. This must be the first call made to iFrame and will trigger the loading of the iFrame fields.

Signature

init(environmentKey, options)

Arguments

Name Description
environmentKey The key of the Spreedly environment where the payment method should be tokenized
options Map of initialization options. numberEl should be set to the id of the HTML element where the number iFrame field should be rendered. cvvEl should be set to the id of the HTML element where the CVV iFrame field should be rendered.

Events

Name Triggered
ready When the iFrame has been initialized, rendered, and is ready for further configuration

reload

Spreedly.reload();

Reload the iFrame library. This resets and re-initializes all iFrame elements and state and is a convenient way to quickly reset the form.

When reload is complete, the ready event will be fired, at which time the iFrame can be customized.

Signature

reload()

removeHandlers

Spreedly.removeHandlers();

Remove all event handlers currently registered via the on function.

Signature

removeHandlers()

SpreedlyPaymentFrame

// Create a new instance
var otherIFrame = new SpreedlyPaymentFrame();

// Configure as usual
otherIFrame.init("C7cRfNJGODKh4Iu5Ox3PToKjniY", {
  "numberEl": "number-parent",
  "cvvEl": "cvv-parent"
});

otherIFrame.on("ready", function() {
  // Style etc...
});

Create a new, independent, instance of the iFrame. It will be created alongside the default instance, already exposed as Spreedly.

Signature

SpreedlyPaymentFrame()

Tokenization

tokenizeCreditCard

Spreedly.tokenizeCreditCard({

  // Required
  "first_name": document.getElementById("first-name").value,
  "last_name": document.getElementById("last-name").value,
  "month": document.getElementById("month").value,
  "year": document.getElementById("year").value,

  // Optional
  "email": document.getElementById("email").value,
  "zip": document.getElementById("zip").value
});

Trigger tokenization of the entered credit card. This will send the data contained within the iFrame fields to the Spreedly environment, along with any additional payment method data specified here.

On successful tokenization, the paymentMethod event will be triggered. On failure, the errors event will be triggered.

Signature

tokenizeCreditCard(additionalFields)

Arguments

Name Description
additionalFields Map of additional payment method fields to store alongside tokenized card

The list of additional payment method fields that can be set on tokenization include:

Name
first_name
required unless full_name is specified
last_name
required unless full_name is specified
full_name
required unless both first or last names are specified
month
year
email
address1
address2
city
state
zip
country
phone_number
company
shipping_address1
shipping_address2
shipping_city
shipping_state
shipping_zip
shipping_country
shipping_phone_number

Events

Name Triggered
paymentMethod When a payment method is successfully tokenized
errors When a payment method is not successfully tokenized

validate

Spreedly.validate();

Request iFrame fields to report their validation status. Useful for real-time validation functionality.

Signature

validate()

Events

Name Triggered
validation When validate is invoked

Recache

Update the CVV on an already tokenized credit card.

setRecache

Spreedly.on('ready', function(){
 Spreedly.setRecache("56wyNnSmuA6CWYP7w0MiYCVIbW6" , {
   'card_type': 'visa',
   'last_four_digits': '1234'
 });
});

Configure the iFrame to operate in recache mode. When iFrame has received and displayed the existing payment method information, the recacheReady event will be fired.

Signature

setRecache(token, options)

Arguments

Name Description
token Token of existing payment method in Spreedly environment
options Map of display options for existing payment method. Set card_type to support CVV validation, and last_four_digits to show the last four digits in the number field.

Events

Name Triggered
recacheReady When the iFrame has been properly configured for recache

recache

Spreedly.recache();

Trigger recache on existing payment method. Requires that setRecache has already been called.

On successful recache, the recache event will be triggered. On failure, the errors event will be triggered.

Signature

recache()

Events

Name Triggered
recache When a payment method is successfully recached
errors When a payment method is not successfully tokenized

UI

setFieldType

Spreedly.on('ready', function() {
  Spreedly.setFieldType("number", "tel");
});

Set the input type of the iFrame fields. This is useful to when you want different keyboards to display on mobile devices.

By default, the iFrame fields are set to type=number, which displays the numerical keyboard in most browsers on most mobile devices. However, behavior does vary by browser. If you’d like to manually control the input field type you can do so with setFieldType.

Signature

setFieldType(field, type)

Arguments

Name Description
field The iFrame field to set the type. Can be one of number or cvv.
type The input field type. Can be one of number, text or tel.

setLabel

Spreedly.on('ready', function() {
  Spreedly.setLabel("number", "Card Number");
  Spreedly.setLabel("cvv", "CVV");
});

Style iFrame fields’ label. Although the label for each iFrame field is not displayed, it is still used by screen readers and other accessibility devices.

Signature

setLabel(field, label)

Arguments

Name Description
field The iFrame field to set the label. Can be one of number or cvv.
placeholder The label text value

setNumberFormat

Spreedly.on('ready', function() {
  Spreedly.setFieldType("number", "text");
  Spreedly.setNumberFormat("prettyFormat");
});

Set the card number format. If set to pretty format, the card number value will include spaces in the credit card number as they appear on a physical card.

The number field must be set to type text for pretty formatting to take effect.

Signature

setNumberFormat(format)

Arguments

Name Description
format One of prettyFormat or plainFormat. The default is plainFormat.

The following is an example of how formatting affects what is displayed in the number field:

Format User enters Displayed as
prettyFormat 4111111111111111 4111 1111 1111 1111
plainFormat 4111111111111111 4111111111111111

setPlaceholder

Spreedly.on('ready', function() {
  Spreedly.setPlaceholder("number", "Card");
  Spreedly.setPlaceholder("cvv", "CVV");
});

Style iFrame fields’ placeholder text.

Signature

setParameter(field, placeholder)

Arguments

Name Description
field The iFrame field to set the placeholder. Can be one of number or cvv.
placeholder The placeholder text value

setStyle

Spreedly.on("ready", function() {
  Spreedly.setStyle("number", "width:225px;  height:35px;");
  Spreedly.setStyle("number", "font-size: 20px; text-align: center");
  Spreedly.setStyle("cvv", "width:60px;  height:35px;");
});

Style iFrame fields using CSS.

Signature

setStyle(field, css)

Arguments

Name Description
field The iFrame field to apply the CSS to. Can be one of number or cvv.
css The CSS to apply. Should be vanilla CSS, constructed as a single string.

More than one invocation of setStyle can be used per field to organize and better structure styling directives.

transferFocus

Spreedly.transferFocus("number");

Set the cursor focus to one of the iFrame fields. This is useful if you want to load your form with the card number field already in focus, or if you want to auto-focus one of the iFrame fields if they contain an input error.

Signature

transferFocus(field)

Arguments

Name Description
field The iFrame field to give focus to. Can be one of number or cvv.

Events

Spreedly.on("event name", function(args) {
  // Invoke your own functionality, using any
  // args passed in to the listener function
});

iFrame emits a variety of state-change events to the host page, which can register to respond to the event.

To register for an event, use the on registration function. To remove all event handlers, use the removeHandlers function.

consoleError

Spreedly.on("consoleError", function(error) {
  console.log("Error from Spreedly iFrame: " + error["msg"]);
});

Triggered when a javascript error occurs within the iFrame. This is useful for debugging runtime issues.

Event handler

function(error)

Arguments

Name Description
error Map of error properties. Keys inlude msg, url, line, col

errors

Spreedly.on('errors', function(errors) {
  messageEl = document.getElementById("message");
  for(var i = 0; i < errors.length; i++) {
    messageEl.innerHTML =
      "Error saving card " + errors[i]["key"] + ": " + errors[i]["message"]
  }
});

Triggered when a payment method is not successfully tokenized or recached. Requires a call to tokenizeCreditCard or recache.

Event handler

function(errors)

Arguments

[
  {
    "attribute":"first_name",
    "key":"errors.blank",
    "message":"First name can't be blank"
  }, {
    "attribute":"last_name",
    "key":"errors.blank",
    "message":"Last name can't be blank"
  }
]
Name Description
errors An array of error objects with attribute, key, and message fields describing the errors on the payment method when submitted to Spreedly

The list of error keys include:

Key Description
errors.account_inactive A non-test card number was submitted against a test (unpaid) account. This can also occur when an invalid card number is submitted while testing as Spreedly assumes all unknown card numbers are real.
errors.environment_key_parameter_required An environment was not specified. Specify one when initializing iFrame: Spreedly.init("your_environment_key");
errors.invalid_environment_key_parameter The specified environment key is not valid. Check the supplied environment key value and re-submit.
errors.blank The payment method field specified by the attribute property of this error was submitted without a value, which is required by Spreedly. Display an appropriate error message and prompt the user to fill in the specified fields.
errors.invalid The payment method field specified by the attribute property of this error was submitted with an invalid value (e.g., a month value of “13”). Display an appropriate error message and prompt the user to correct the specified fields.
errors.blank_card_type The credit card number was invalid; we were unable to determine the card type.
errors.expired The payment method month and year indicates that it is expired. Display an appropriate error message and prompt the user to enter a non-expired payment method.
errors.unknown_referrer Spreedly could not determine the source (referring URL) of the form submission. A referring URL is required to identify MITM attacks.
errors.invalid_referrer The form submission did not originate from the Spreedly payment frame and has been rejected. This is a protection against MITM attempts.
errors.configuration If iFrame is configured to recache but tokenizeCreditCard is invoked, or iFrame is configured to tokenize but recache is invoked.

fieldEvent

Spreedly.on('fieldEvent', function(name, type, activeEl, inputProperties) {
  if(name == "number") {
    numberParent = document.getElementById("spreedly-number");

    if(type == "focus") { numberParent.className = "highlighted"; }
    if(type == "input" && !inputProperties["numberValid"]) {
      numberParent.className == "error";
    }
  }
});

Triggered when an input event occurs in either iFrame field. This is useful to provide real-time feedback to the user.

Event handler

function(name, type, activeEl, inputProperties)

Arguments

Name Description
name The name of the field triggering the event. One of number or cvv.
type The event type. One of focus, blur, mouseover, mouseout, input, enter, escape, tab, or shiftTab
activeEl The name of the field that currently has focus (this can be different from the named field depending on the event). One of number or cvv.
inputProperties Map of properties indicating the state of the user’s input in the iFrame fields. This map is only populated on the input even type.

The list of event types include:

Type Fired when
blur An iFrame field has lost focus
enter The user has pressed “enter” while in an iFrame field
escape The user has pressed “escape” while in an iFrame field
focus An iFrame field has gained focus
input The user has entered a new input value into an iFrame field
mouseover The cursor has moved onto an iFrame field
mouseout The cursor has left an iFrame field
shiftTab The user has pressed the “shift+tab” key combo while in an iFrame field
tab The user has pressed “tab” while in an iFrame field
{
  "cardType": "visa",
  "validNumber": true,
  "validCvv": true,
  "numberLength": 16,
  "cvvLength": 3
}

inputProperties includes the following keys on the input event type.

Name Description
cardType The type (brand) of the card. One of supported card identifiers.
validNumber Is the card number valid and for a supported brand? true or false.
validCvv Is the CVV valid? true or false.
numberLength The length of the value entered into the number field
cvvLength The length of the value entered into the CVV field

paymentMethod

Spreedly.on("paymentMethod", function(token, paymentMethod) {

  // Send requisite payment method info to backend
  var tokenField = document.getElementById("payment_method_token");
  var fingerprintField = document.getElementById("payment_method_fingerprint");

  tokenField.setAttribute("value", token);
  fingerprintField.setAttribute("value", paymentMethod["fingerprint"]);

  var masterForm = document.getElementById('payment-form');
  masterForm.submit();
});

Triggered when a payment method is successfully tokenized by Spreedly. The host page must handle this event to take the payment method token and send it to the backend environment for further processing. Requires a call to tokenizeCreditCard.

Event handler

function(token, paymentMethod)

Arguments

Name Description
token The token of the newly tokenized payment method. Tokens are alphanumerics in the form M8TBiUmc19cjV16PdMbsj65uViL.
paymentMethod A map of the full payment method in JSON form

ready

Spreedly.on("ready", function() {
  Spreedly.setStyle("number", "font-family: 'Arial';")
});

Triggered when the iFrame is initialized and ready for configuration. setStyle and other UI function calls should be made within this event listener. This event will only fire after init() has been called.

Event handler

function()

recache

Spreedly.on("recache", function(token, paymentMethod) {

  // Send ping back to server for post-recache transaction processing
  var masterForm = document.getElementById('payment-form');
  masterForm.submit();
});

Triggered when a payment method is successfully recached by Spreedly (and the CVV is now available on the payment method). The host page must handle this event to ping the backend environment that the payment method is ready for further processing. Requires a call to recache.

Event handler

function(token, paymentMethod)

Arguments

Name Description
token The token of the recached payment method. Tokens are alphanumerics in the form M8TBiUmc19cjV16PdMbsj65uViL.
paymentMethod A map of the full payment method in JSON form

recacheReady

Spreedly.on("recacheReady", function() {
  // Enable form submit button or other logic dependent on
  // recache readiness...
  var paymentButton = document.getElementById('payment-form-button');
  paymentButton.disabled = false;
});

Triggered when iFrame is properly configured for recache.

Event handler

function()

validation

Spreedly.on('validation', function(inputProperties) {
  if(!inputProperties["validNumber"]) {
    messageEl = document.getElementById("message");
    messageEl.innerHTML = "Please enter a valid credit card number";
  }
});

Triggered when validation of the iFrame is requested. This event will only fire after validate() has been called.

Event handler

function(inputProperties)

Arguments

Name Description
inputProperties Map of properties indicating the state of the user’s input in the iFrame fields
{
  "cardType": "visa",
  "validNumber": true,
  "validCvv": true,
  "numberLength": 16,
  "cvvLength": 3
}

inputProperties includes the following keys:

Name Description
cardType The type (brand) of the card. One of supported card identifiers.
validNumber Is the card number valid and for a supported brand? true or false.
validCvv Is the CVV valid? true or false.
numberLength The length of the value entered into the number field
cvvLength The length of the value entered into the CVV field

Testing

Many development teams utilize automated testing to test their browser-based workflows. The following functions should aid in that endeavor.

setValue

Spreedly.on("ready", function() {
  Spreedly.setValue("number", "4111111111111111");
  Spreedly.setValue("cvv", "123");
});

Set the value the iFrame fields to a known test value. Any non-whitelisted values will be silently rejected.

Signature

setValue(field, value)

Arguments

Name Description
field The iFrame field to set the value. Can be one of number or cvv.
value The value to set the field to. The number field will only accept test card numbers. The cvv field will only accept 12, 123, or 1234