iFrame events

API docs for version 1 of the Spreedly iFrame Javascript API

Events

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.

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

3ds:status

Setup event handling after kickoff of the iFrame ThreeDS lifecycle.

Note: If you plan to run multiple 3DS authentications without a full page reload or redirect, this function should only be set up once. Invoking it multiple times will register the event handlers multiple times leading undefined behavior.

Spreedly.on("3ds:status", function(evt) {
  console.log(`3DS Status Update from Spreedly ThreeDS Lifecycle: ${evt}`);

  switch (evt.action) {
    case "challenge":
      // show the challenge-modal
      break;
    case "succeeded":
      // finish your checkout and redirect to success page
      break;
    case "finalization-timeout":
      // present an error to the user to retry
      break;
    case "error":
      // present an error to the user to retry
      break;
    case "trigger-completion": // only applicable for Spreedly Gateway Specific 3DS integrations
      // "Trigger Completion Event. Manually complete your transaction"
      break;
    default:
      console.log(`Event ${evt.action} not handled`)
  }
});

Event handler

function(evt)

Arguments

NameDescription
evtcontains the context of the 3DS status

In addition, you must handle all possible evt.action values:

ActionOccurs whenNote
succeededTransaction has finished and it’s time to move your user away from your checkout page.
errorThere was an error with the transaction and you should either present an error to the user or cancel the transaction. Transactions that have failed cannot be updated or used to challenge the cardholder again; if you would like to present a cardholder with a new challenge upon failure, a new transaction should be used. The event has a response hash that contains information on the transaction state, message, and error_code if available.
challengeIt’s time to pop open the challenge flow, see our 3DS guidelines.
finalization-timeoutCustomer authentication could not be completed within the expected window. This gets triggered 10-15 minutes after presenting a challenge without the transaction state changing. It is recommended that merchants attempt a manual completion here to attempt to continue or finalize the transaction.
trigger-completionMake the authenticated transaction completion call from your backend to Spreedly and call event.finalize with the response data in your frontend.Gateway Specific 3DS2 only.

consoleError

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

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

Event handler

function(error)

Arguments

NameDescription
errorMap of error properties. Keys inlude msg, url, line, col

errors

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

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"]
  }
});
[
  {
    "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"
  }
]

Event handler

function(errors)

Arguments

NameDescription
errorsAn 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:

KeysDescription
errors.account_inactiveA 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_requiredAn environment was not specified. Specify one when initializing iFrame: Spreedly.init("your_environment_key");
errors.invalid_environment_key_parameterThe specified environment key is not valid. Check the supplied environment key value and re-submit.
errors.blankThe 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.invalidThe 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_typeThe credit card number was invalid; we were unable to determine the card type.
errors.expiredThe 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_referrerSpreedly could not determine the source (referring URL) of the form submission. A referring URL is required to identify MITM attacks.
errors.invalid_referrerThe form submission did not originate from the Spreedly payment frame and has been rejected. This is a protection against MITM attempts.
errors.configurationIf iFrame is configured to recache but tokenizeCreditCard is invoked, or iFrame is configured to tokenize but recache is invoked.

fieldEvent

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

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";
    }
  }
});

Event handler

function(name, type, activeEl, inputProperties)

Arguments

NameDescription
nameThe name of the field triggering the event. One of number or cvv.
typeThe event type. One of focus, blur, mouseover, mouseout, input, enter, escape, tab, or shiftTab
activeElThe 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.
inputPropertiesMap of properties indicating the state of the user’s input in the iFrame fields. This map is only populated on the input event type.

The list of event types include:

TypeOccurs when
blurAn iFrame field has lost focus. Note that on iOS devices this event does not consistently trigger. As a workaround, we have seen some customers use the mouseout event in place of blur when iFrame is used in Safari or a WKWebview on iOS.
enterThe user has pressed “enter” while in an iFrame field
escapeThe user has pressed “escape” while in an iFrame field
focusAn iFrame field has gained focus
inputThe user has entered a new input value into an iFrame field
mouseoverThe cursor has moved onto an iFrame field
mouseoutThe cursor has left an iFrame field
shiftTabThe user has pressed the “shift+tab” key combo while in an iFrame field
tabThe user has pressed “tab” while in an iFrame field

inputProperties includes the following keys on the input event type:

{
  "cardType": "visa",
  "validNumber": true,
  "validCvv": true,
  "numberLength": 16,
  "cvvLength": 3,
  "iin": "41111111"
}
NameDescription
cardTypeThe type (brand) of the card. One of supported card brands.
validNumberThis will check if the supplied card number is a supported brand and expected length. If the brand has an algorithm check, it validates that the algorithm passes. Will return either true or false.
validCvvThis will check if the supplied CVV matches the expected length based on the card type, and is comprised of only numbers. Will return either true or false.
numberLengthThe length of the value entered into the number field
cvvLengthThe length of the value entered into the CVV field
iinThe issuer identification number (IIN) of the supplied card number. All card types (brands) will return the first 6 digits as the number is entered. Visa and MasterCard brands will also return the first 8 digits.

paymentMethod

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.

Supports BIN metadata for Advanced Vault enabled cards. See the BIN Metadata guide for more information.

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();
});

Event handler

function(token, paymentMethod)

Arguments

NameDescription
tokenThe token of the newly tokenized payment method. Tokens are alphanumerics in the form M8TBiUmc19cjV16PdMbsj65uViL.
paymentMethodA map of the full payment method in JSON form

ready

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.

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

Event handler

function()

recache

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](doc:iframe-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();
});

Event handler

function(token, paymentMethod)

Arguments

NameDescription
tokenThe token of the recached payment method. Tokens are alphanumerics in the form M8TBiUmc19cjV16PdMbsj65uViL.
paymentMethodA map of the full payment method in JSON form

recacheReady

Triggered when iFrame is properly configured for recache.

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;
});

Event handler

function()

validation

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

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

Event handler

function(inputProperties)

Arguments

NameDescription
inputPropertiesMap of properties indicating the state of the user’s input in the iFrame fields

inputProperties includes the following keys:

{
  "cardType": "visa",
  "validNumber": true,
  "validCvv": true,
  "numberLength": 16,
  "cvvLength": 3,
  "iin": "41111111"
}
NameDescription
cardTypeThe type (brand) of the card. One of supported card brands.
validNumberThis will check if the supplied card number is a supported brand and expected length. If the brand has an algorithm check, it validates that the algorithm passes. Will return either true or false.
validCvvThis will check if the supplied CVV matches the expected length based on the card type, and is comprised of only numbers. Will return either true or false.
numberLengthThe length of the value entered into the number field
cvvLengthThe length of the value entered into the CVV field
iinThe issuer identification number (IIN) of the supplied card number. All card types (brands) will return the first 6 digits as the number is entered. Visa and MasterCard brands will also return the first 8 digits.

NOTE: If validNumber is false, iFrame will prevent a call to tokenizeCreditCard. However, the validCVV property will not prevent a call to tokenizeCreditCard, since not all customers require a valid CVV at time of tokenizing.