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

Set Parameters

// On an active Spreedly instance
// Validation will not require any of the name fields
Spreedly.setParam('allow_blank_name', true);

// Validation will still require a date, but it can be expired
Spreedly.setParam('allow_expired_date', true);

Sets parameters to bypass some validation features of the iframe. Valid parameters that can be passed are allow_blank_name and allow_expired_date. If set to true, the related steps in validation will be skipped. Defaults to false.

ThreeDS Lifecycle

Spreedly ThreeDS Lifecycle object is used to help simplify your frontend integration with Spreedly 3DS2 Solutions.

The Lifecycle object polls the Spreedly backend and emits events when the transaction changes status or times out. When a 3DS Challenge needs to be displayed to a cardholder, it will create an <iframe> element and inject it with the <form> from the acquiring bank.

new

var lifecycle = new Spreedly.ThreeDS.Lifecycle({
  // The key of the Spreedly environment where the payment method should be tokenized
  environmentKey: '...', // (highly recommended)

  // The DOM node that you'd like to inject hidden iframes
  hiddenIframeLocation: 'device-fingerprint', // (required)

  // The DOM node that you'd like to inject the challenge flow
  challengeIframeLocation: 'challenge', // (required)

  // The token for the transaction - used to poll for state
  transactionToken: '...', // (required)

  // The css classes that you'd like to apply to the challenge iframe.
  // e.g. 'red-border left-positioned custom-styles'
  challengeIframeClasses: '...', // (optional)
})

Arguments

Name Description Required/Optional
environmentKey The key of the Spreedly environment where the payment method should be tokenized O
hiddenIframeLocation The DOM node that you’d like to inject hidden iframes. R
challengeIframeLocation The DOM node that you’d like to inject the challenge flow R
transactionToken The token for the transaction - used to poll for state R
challengeIframeClasses The css classes that you’d like to apply to the challenge iframe O

start

lifecycle.start()

Starts Spreedly’s 3DSecure asynchronous flow once it is completely setup using the new constructor.

Signature

start()

Events

Before start() is invoked, the following events need to be wired with the Spreedly.on listener, see 3ds:status:

Name Triggered
3ds:status Setup event handling and kickoff 3DSecure lifecycle

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
metadata
key-value pairs

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.

Note: A credit card must be retained in your environment in order to re-cache its CVV.

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.
label The label text value

setTitle

Spreedly.on('ready', function() {
  Spreedly.setTitle("number", "credit card title");
  Spreedly.setTitle("cvv", "cvv title");
});

Set custom iFrame fields’ title attribute. Although the title for each iFrame field is not displayed, it can still be used by screen readers and other accessibility devices. By default, the title attribute is set to “credit card number” for the number field, and “cvv number” for the cvv field. If you would like to customize these titles you can do so with a call of this function.

Signature

setTitle(field, title)

Arguments

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

setNumberFormat

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

// Masked format
Spreedly.on('ready', function() {
  Spreedly.setFieldType("cvv", "text");
  Spreedly.setFieldType("number", "text");
  Spreedly.setNumberFormat("maskedFormat");
});

Set the card number format. If set to prettyFormat, 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 or tel for pretty formatting to take effect.

If set to maskedFormat, the card number and CVV values will be masked with * as the user enters text. Both the CVV and number fields must be set to type text for the masked formatting to take effect. Once maskedFormat has been set, the toggleMask function can be called to show the card number and CVV in plain text if they are masked, or mask them if they are shown.

Signature

setNumberFormat(format)

Arguments

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 (default) 4111111111111111 4111111111111111
maskedFormat 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, -moz-appearance, or -webkit-appearance. All CSS properties should be constructed as a single string.

More than one invocation of setStyle can be used per field to organize and better structure styling directives. Based on the iFrame CORS settings, we do not currently allow importing any external fonts or images.

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.

toggleAutoComplete

Spreedly.toggleAutoComplete();

Toggle autocomplete functionality for card number and cvv fields. By default, the autocomplete attribute is enabled, so the first call of this function will disable autocomplete

Signature

toggleAutoComplete()

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.

3ds:status

Setup event handling after kickoff of Spreedly 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

Name Description Note
evt contains the context of the 3DS status

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

Action Trigger Note
succeeded Transaction has finished and it’s time to move your user away from your checkout page.
error There 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
challenge It’s time to pop open the challenge flow, see our integration guides
finalization-timeout Customer 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-completion Make the authenticated transaction completion call from your backend to Spreedly and call event.finalize` with the response data in your frontend. 3DS Gateway Specific only

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 event type.

The list of event types include:

Type Fired when
blur An 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.
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 This 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.
validCvv This 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.
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 This 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.
validCvv This 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.
numberLength The length of the value entered into the number field
cvvLength The length of the value entered into the CVV field

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.

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 values that are not on the allowed list 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

Plugins

Spreedly provides helper functions in our iFrame that help our customers get the most out of their integrations.

stripeRadar


function callback(radarSessionId) {
  // pass radar_session_id to your backend to use it
  // as a gateway specific field when making and authorization
  // or purchase request
}

Spreedly.stripeRadar('pk_examplepk', callback);

The Spreedly.stripeRadar function allows Spreedly customers using the Stripe or Stripe Payment Intents gateways to integrate with Stripe’s Radar fraud detection tools. For more information on how to use this, see the Stripe or Stripe Payment Intents gateway guides.

This function is asynchronous in that it requires an API call to Stripe. If any failures occur, the callback will receive a null value for the radarSessionId. The transaction should still be performed in this case, but it will not leverage Stripe’s frontend fraud detection.

NOTE: The stripeRadar function uses Javascript’s console.log to log any problems with the integration. Check your browser’s console during development to ensure that any suggestions that it makes are fixed before going to production.

Signature

stripeRadar(publishableKey, callback)

Arguments

Name Description
publishableKey The Stripe publishable key for the account that the purchase or authorization will be created on. This can be found in the Stripe developer dashboard.
callback Upon completion of the Stripe API call, the callback function will be called with one argument: the Stripe Radar Session ID. This ID should be passed into your Stripe or Stripe Payment Intents transaction via the radar_session_id Gateway Specific Field.

createStripePaymentElement

const element = Spreedly.createStripePaymentElement({
  publishableKey: 'pk_...',
  clientSecret: clientSecret,
  paymentElement: '#payment-element',
  transactionToken: spreedlyTransactionToken,
  appearance: stripeAppearanceObject
});

The Spreedly.createStripePaymentElement function allows transactions using Alternative Payment Methods on the Stripe Payment Intents gateway begins the process by injecting the Stripe Payment Element form into the checkout page.

For more information, see the Making a Payment with Stripe APMs guide

Signature

Spreedly.createStripePaymentElement(options)

Arguments

Name Description
options An object that contains all other arguments available on Stripe Intents below
❯ publishableKey The publishable key attached to the Stripe account making this purchase. This value can be found in the Stripe developer dashboard.
❯ clientSecret The client secret is a field returned in the pending transaction from Step 1 that authorizes the frontend to complete the purchase. This value can be found in the Spreedly transaction response at transaction.gateway_specific_response_fields.stripe_payment_intents.client_secret.
❯ transactionToken The Spreedly transaction token returned by the pending transaction from Step 1.
❯ paymentElement An HTML DOM element that the Payment Element will be injected into.
❯ appearance (optional) See the Stripe Appearance API for more information.

Return Value

if (element.error) { handle(error); }

// This will redirect the customer to complete their order
checkoutButton.onclick = element.confirmPayment;

This function returns an object with the following public fields and methods:

element.error

The error field is a string if something went wrong, such as an invalid publishable key, invalid input fields, or Stripe.js not being on the page. These are mostly used during implementation to ensure that the call is being performed correctly. Any value here mean that the Payment Element has not been displayed. If no errors occur when mounting the Payment Element, this function returns undefined.

element.confirmPayment();

When the customer is ready to checkout, confirmPayment() should be called to begin the redirect. This function has no return value as the customer will be redirected to complete the purchase. This should only be called if error is not present.

createBraintreePaymentElements

const element = Spreedly.createBraintreePaymentElements({
  callbackFunction: callbackFunction,
  transactionToken: transactionToken,
  environmentKey: enviornmentKey,
  paymentElements: {paypal: 'paypal-payment-element'}* 
});

The Spreedly.createBraintreePaymentElements function allows transactions using Alternative Payment Methods on the Braintree Blue gateway. It begins the process by injecting the Braintree Payment Element form into the checkout page.

For more information, see the Alternative Payment Methods section in the Braintree Gateway Guide

Signature

Spreedly.createBraintreePaymentElements(options)

Arguments

Name Description
options An object that contains all other arguments available on Braintree below
❯ callbackFunction This is a callback function provided by the customer. When we receive a successful, cancelled or error response from Braintree we will return a object to that callback function. The response returned here will be used in Step 3.
❯ transactionToken The Spreedly transaction token returned by the pending transaction from Step 1.
❯ paymentElements An object with HTML DOM element that the Payment Element will be injected into. Send the payment elements you are trying to render.
❯ environmentKey The Spreedly environment key.

Return Value

if (element.error) { handle(error); }

element.error

The error field is a string if something went wrong, such as missing parameters or the different Braintree scripts not being on the page. These are mostly used during implementation to ensure that the call is being performed correctly. Any value here mean that the Payment Element has not been displayed. If no errors occur when mounting the Payment Element, this function returns undefined.

  {
    "state": "Successful",
    "nonce": "paymentMethodNonce",
    "payment_method": {
      "payment_method_type": "paypal"
    }
  }

If the customer successfully completes their payment after they click the respective button then a object will be returned. This object will contain state, nonce, payment_method and possibly other parameters.

  {
    "state": "Failed",
    "message": "undefined Error: PayPal payment options are invalid. at Tr.error…",
    "payment_method": {
      "payment_method_type": "paypal"
    }
  }

If an unexpected error occurs then a object will be returned to the callbackFunction. This objects will contain state, message and payment_method.

  {
    "state": "Cancelled",
    "message": "PayPal payment cancelled, {\n \"orderID\": \"EC-8XN05533WV243142V\"\n}",
    "payment_method": {
      "payment_method_type": "paypal"
    }
  }

If a customer cancels their payment then a object will be returned to the callbackFunction. This objects will contain state, message and payment_method.

Note this is just an example for PayPal but you can find examples for Venmo in our Alternative Payment Methods section of the Braintree Gateway Guide.