Square Payment Form

Data Model

Data Model Overview

The SqPaymentForm data model includes three primary elements:

  • SqPaymentForm Configuration fields - data fields that define HTML placeholder names, enable/disable payment features, and control presentation of the form fields.
  • SqPaymentForm Callback functions - functions triggered when specific events happen. The behavior of these functions is fully customizable.
  • Digital wallet paymentRequest objects - Data objects used specifically for digital wallet payments and formatted in accordance with the requirements of various wallet services (e.g., Apple Pay for Web).

Callback functions

sqPaymentForm callback function reference.

methodsSupported function

Invoked when page is loaded

Called by SqPaymentForm when the page renders to decide which, if any, digital wallet button should be rendered in the payment form.

methodsSupported: function (methods)

Parameters

Name Type Description
methods object

The collection of electronic wallet payment methods

Examples


methodsSupported: function (methods) {
  var applePayBtn = document.getElementById('sq-apple-pay');
  var applePayLabel = document.getElementById('sq-apple-pay-label');
  var masterpassBtn = document.getElementById('sq-masterpass');
  var masterpassLabel = document.getElementById('sq-masterpass-label');
  var googlePayBtn = document.getElementById('sq-google-pay');
  var googlePayLabel = document.getElementById('sq-google-pay-label');

  console.log(methods)
  // Only show the button if Apple Pay for Web is enabled
  // Otherwise, display the wallet not enabled message.
  if (methods.applePay === true) {
    applePayBtn.style.display = 'inline-block';
    applePayLabel.style.display = 'none';
  }
  // Only show the button if Masterpass is enabled
  // Otherwise, display the wallet not enabled message.
  if (methods.masterpass === true) {
    masterpassBtn.style.display = 'inline-block';
    masterpassLabel.style.display = 'none';
  }
  if (methods.googlePay === true) {
    googlePayBtn.style.display = 'inline-block';
    googlePayLabel.style.display = 'none';
  }
}
              

createPaymentRequest function

Invoked when a digital wallet payment button is clicked.

Use this callback function to construct a paymentRequest object to be returned to sqPaymentForm. The sqPaymentForm exchanges the paymentRequest for a nonce. Use cardNonceResponseReceived to get the returned nonce.

createPaymentRequest: function ()

Return Value

PaymentRequest object.

Examples


createPaymentRequest: function () {
  return {
      requestShippingAddress: true,
      requestBillingInfo: true,
      shippingContact: {
        familyName: "Buyer",
        givenName: "The",
        email: "thebuyer@example.com",
        country: "USA",
        region: "CA",
        city: "San Francisco",
        addressLines: [
          "123 Main St"
        ],
        postalCode: "94114"
      },
      currencyCode: "USD",
      countryCode: "US",
      total: {
        label: "devs-Acceptance",
        amount: "5",
        pending: false
      }
  };
}
         

validateShippingContact function

Invoked when a shipping address is selected/changed in a digital wallet UI that supports address selection. requestShippingAddress is true in the PaymentRequest object, and the user selects/changes shipping information in the digital wallet UI.

validateShippingContact: function (contact)

Parameters

Name Type Description
contact sqContact

Shipping contact information that is displayed in the digital wallet UI.

Return Value

validationErrorObject object.

Examples


validateShippingContact: function (contact) {

  var validationErrorObj;
  /* ADD CODE TO SET validationErrorObj IF ERRORS ARE FOUND */
  return validationErrorObj;
}
              

cardNonceResponseReceived function

Invoked when SqPaymentForm receives the result of a nonce generation request. The result will be a valid credit card or wallet nonce, or an error.

cardNonceResponseReceived: function (errors, nonce, cardData, billingContact, shippingContact)

Parameters

Name Type Description
errors array of objects

Collection of error messages returned by Square endpoint.

Each JSON object has three fields:

  • type - a programmatic description of error.
  • message - a human-readable description of the error.
  • field - the input field that caused the error.
nonce string

Tokenized payment card information. The nonce is a string representing the nonce that was created or null if an error occurred. Nonce values expire after 24 hours.

cardData object

Contains non-confidential information about the customer credit card or null if an error occurred:

  • card_brand: an enum value indicating the brand of the credit card used:
    • americanExpress
    • discover
    • discoverDiners
    • JCB
    • masterCard
    • unionPay
    • unknown
    • visa
  • last_4: the last 4 digits of the card number
  • exp_month: the 2-digit month of the expiration date
  • exp_year: the 4-digit year of the expiration date
  • billing_postal_code: the postal code provided, or null if postal code is disabled.
  • digital_wallet_type: an enum value indicating the type of digital wallet that contains the credit card:
    • applePay
    • masterpass
    • none
billingContact SqContact

Contact information for the card holder

shippingContact SqContact

Contact information the recipient of the purchased product or service

Remarks

The most common nonce generation errors are:

  • VALIDATION_ERROR - The provided data is invalid.
  • INVALID_APPLICATION_ID - The application ID provided when initializing the payment form is invalid.
  • MISSING_APPLICATION_ID - An application ID was not provided when initializing the payment form.
  • MISSING_CARD_DATA - One or more card data fields was not filled out in the payment form.
  • TOO_MANY_REQUESTS - Your application has generated too many nonce generation requests in too short a time. Try again later.
  • UNAUTHORIZED - Your application is not authorized to use the Connect API to accept online payments.
  • UNKNOWN - An unknown error occurred.

Examples


cardNonceResponseReceived: function (errors, nonce, cardData, billingContact, shippingContact) {
  if (errors) {
    // Log errors from nonce generation to the Javascript console
    console.log("Encountered errors:");
    errors.forEach(function (error) {
      console.log('  ' + error.message);
    });

    return;
  }
  alert('Nonce received: ' + nonce); /* FOR TESTING ONLY */

  // Assign the nonce value to the hidden form field
  document.getElementById('card-nonce').value = nonce;

  // POST the nonce form to the payment processing page
  document.getElementById('nonce-form').submit();
}
            

inputEventReceived function

Invoked when visitors interact with SqPaymentForm iframe elements.

inputEventReceived: function (inputEvent)

Parameters

Name Type Description
inputEvent SqInputEventData

A collection of error messages returned by Square endpoint that provides actionable information about the event.

Remarks

The inputEventReceived callback operates independently from the main nonce generation workflow. The callback is customizable and used to take additional action when any of the following inputEvent events are detected.

  • focusClassAdded - A form field gained focus, and the corresponding focus CSS class was added to the element.
  • focusClassRemoved - A form field lost focus, and the corresponding focus CSS class was removed from the element.
  • errorClassAdded - A form field has an invalid value, and the corresponding error CSS class was added to the element.
  • errorClassRemoved - An invalid value on a form field was corrected, and the corresponding error CSS class was removed from the element.
  • cardBrandChanged - The payment form detected a new likely credit card brand based on the card number.
  • postalCodeChanged - The current value of the postal code form field changed.

Examples


inputEventReceived: function(inputEvent) {
  switch (inputEvent.eventType) {
    case 'focusClassAdded':
      /* HANDLE AS DESIRED */
      break;
    case 'focusClassRemoved':
      /* HANDLE AS DESIRED */
      break;
    case 'errorClassAdded':
      /* HANDLE AS DESIRED */
      break;
    case 'errorClassRemoved':
      /* HANDLE AS DESIRED */
      break;
    case 'cardBrandChanged':
      /* HANDLE AS DESIRED */
      break;
    case 'postalCodeChanged':
      /* HANDLE AS DESIRED */
      break;
  }
}
              

paymentFormLoadedfunction

Invoked when SqPaymentForm is fully loaded.

paymentFormLoaded: function()

Examples


paymentFormLoaded: function() {
  /* HANDLE AS DESIRED */
}
          

Configuration Fields

SqPaymentForm renders the form based on the configuration of its data fields:

Configuration fields

Name Type Description
applePay placeholder JSON object. Sets the <button> ID of the placeholder for the Apple Pay for Web button.
applicationId string Identifies the calling form with a verified application ID generated from the Square Application Dashboard.
autoBuild boolean When false, fields will not be generated automatically. Instead, fields must be generated manually.
cardNumber placeholder JSON object. Sets the <div> ID and placeholder text of the input field placeholder for the credit card number.
cvv placeholder JSON object. Sets the <div> ID and placeholder text of the input field placeholder for the credit card's CVV.
expirationDate placeholder JSON object. Sets the <div> ID and placeholder text of the input field placeholder for credit card's expiration date.
masterpass placeholder JSON object. Sets the <button> ID and placeholder text of the placeholder for the Masterpass button.
postalCode placeholder JSON object. Sets the <div> ID and placeholder text of the postal code input field placeholder.
inputClass string Sets the CSS class that defines external styles for text-input iframes.
inputStyles Array of SqContact JSON objects. objects Define the internal styles applied to the rendered iframes.

Configuration field example

sqPaymentForm Initializing parameters can be encapsulated by one or more JSON objects which can be declared in a single file and then referenced from the JavaScript file where sqPaymentForm is initialized.

In the following example, the initializing JSON object is declared and given default values.


var paymentFormPlaceholders = {
  // Initialize Apple Pay placeholder ID
  applePay: {
    elementId: 'sq-apple-pay'  //REPLACE ME
  },

  // Initialize Masterpass placeholder ID
  masterpass: {
    elementId: 'sq-masterpass' //REPLACE ME
  },

  googlePay: {
    elementId: 'sq-google-pay' //REPLACE ME
  },

  // Initialize the credit card placeholders
  cardNumber: {
    elementId: 'sq-card-number', //REPLACE ME
    placeholder: '•••• •••• •••• ••••'
  },
  cvv: {
    elementId: 'sq-cvv', //REPLACE ME
    placeholder: 'CVV'
  },
  expirationDate: {
    elementId: 'sq-expiration-date', //REPLACE ME
    placeholder: 'MM/YY'
  },
  postalCode: {
    elementId: 'sq-postal-code' //REPLACE ME
  }
};
      

The following example declares a payment form parameters object that includes:

  • Application identifiers
  • Input styles
  • Callback functions


var paymentFormParams = {
  // Initialize the payment form elements
  applicationId: "{REPLACE ME WITH YOUR APPLICATION ID}",
  locationId: "{REPLACE ME WITH YOUR LOCATION ID}",
  inputClass: 'sq-input',

  // Customize the CSS for SqPaymentForm iframe elements
  inputStyles: [
    {
      backgroundColor: 'rgba(0,0,0,1)',
      boxShadow: '5px 10px 0px 0px rgb(255,255,255)',
      color: 'rgba(255,255,255,1)',
      fontFamily: 'Arial',
      fontSize: '15px',
      fontWeight: '100',
      padding: '2px',
      placeholderColor: 'rgba(255,255,255,1)'
    },
    {
      mediaMaxWidth: '800px',
      fontSize: '10px'
    },
    {
      mediaMaxWidth: '800px',
      mediaMinWidth: '600px',
      fontSize: '1px',
      backgroundColor: 'rgba(118,170,233,1)'
    },
  ],

  // SqPaymentForm callback functions
  callbacks: {

    /*
     * callback function: methodsSupported
     * Triggered when: the page is loaded.
     */
    methodsSupported: function (methods) {

      var applePayBtn = document.getElementById('sq-apple-pay');           //REPLACE ME
      var applePayLabel = document.getElementById('sq-apple-pay-label');   //REPLACE ME
      var masterpassBtn = document.getElementById('sq-masterpass');        //REPLACE ME
      var masterpassLabel = document.getElementById('sq-masterpass-label'); //REPLACE ME
      var googlePayBtn = document.getElementById('sq-google-pay');         //REPLACE ME
      var googlePayLabel = document.getElementById('sq-google-pay-label'); //REPLACE ME


      console.log(methods)
      // Only show the button if Apple Pay for Web is enabled
      // Otherwise, display the wallet not enabled message.
      if (methods.applePay === true) {
        applePayBtn.style.display = 'inline-block';
        applePayLabel.style.display = 'none';
      }
      // Only show the button if Masterpass is enabled
      // Otherwise, display the wallet not enabled message.
      if (methods.masterpass === true) {
        masterpassBtn.style.display = 'inline-block';
        masterpassLabel.style.display = 'none';
      }
      if (methods.googlePay === true) {
        googlePayBtn.style.display = 'inline-block';
        googlePayLabel.style.display = 'none';
      }
    },


    /*
        * callback function: createPaymentRequest
        * Triggered when: a digital wallet payment button is clicked.
        */
    createPaymentRequest: function () {
      return {
        requestShippingAddress: true,
        requestBillingInfo: true,
        shippingContact: {
          familyName: "Buyer",
          givenName: "The",
          email: "thebuyer@example.com",
          country: "USA",
          region: "CA",
          city: "San Francisco",
          addressLines: [
            "123 Main St"
          ],
          postalCode: "94114"
        },
        currencyCode: "USD",
        countryCode: "US",
        total: {
          label: "devs-Acceptance",
          amount: "5",
          pending: false
        }
      };
    },

    /*
     * callback function: validateShippingContact
     * Triggered when: a shipping address is selected/changed in a digital
     *                 wallet UI that supports address selection.
     */
    validateShippingContact: function (contact) {

      var validationErrorObj;
      /* ADD CODE TO SET validationErrorObj IF ERRORS ARE FOUND */
      return validationErrorObj;
    },

    /*
     * callback function: cardNonceResponseReceived
     * Triggered when: SqPaymentForm completes a card nonce request
     */
    cardNonceResponseReceived: function (errors, nonce, cardData, billingContact, shippingContact) {
      if (errors) {
        // Log errors from nonce generation to the Javascript console
        console.log("Encountered errors:");
        errors.forEach(function (error) {
          console.log('  ' + error.message);
        });

        return;
      }

      // Assign the nonce value to the hidden form field
      document.getElementById('card-nonce').innerText = nonce; //REPLACE ME
    },

    /*
     * callback function: unsupportedBrowserDetected
     * Triggered when: the page loads and an unsupported browser is detected
     */
    unsupportedBrowserDetected: function () {
      /* PROVIDE FEEDBACK TO SITE VISITORS */
    },

    /*
     * callback function: inputEventReceived
     * Triggered when: visitors interact with SqPaymentForm iframe elements.
     */
    inputEventReceived: function (inputEvent) {
      switch (inputEvent.eventType) {
        case 'focusClassAdded':
          $('#focus-class-added').text(inputEvent.elementId);
          break;
        case 'focusClassRemoved':
          $('#focus-class-removed').text(inputEvent.elementId);
          break;
        case 'errorClassAdded':
          $('#error-class-added').text(inputEvent.elementId);
          break;
        case 'errorClassRemoved':
          $('#error-class-removed').text(inputEvent.elementId);
          break;
        case 'cardBrandChanged':
          $('#card-brand-changed').text(inputEvent.cardBrand);
          break;
        case 'postalCodeChanged':
          $('#postal-code-changed').text(inputEvent.postalCodeValue);
          break;
      }
    },

    /*
     * callback function: paymentFormLoaded
     * Triggered when: SqPaymentForm is fully loaded
     */
    paymentFormLoaded: function () {
      var text = $('#payment-form-loaded').text();
      $('#payment-form-loaded').text(text + ' - loaded');
    }
  }
};
      

In the following example, sqPaymentForm is initialized with the previous JSON object.


require paymentform-utils.js
// Create and initialize a payment form object
var paymentForm = new SqPaymentForm({

  // Initialize the payment form placeholders
  applePay: paymentFormPlaceholders.applePay,
  masterpass: paymentFormPlaceholders.masterpass,
  googlePay: paymentFormPlaceholders.googlePay,
  cardNumber: paymentFormPlaceholders.cardNumber,
  cvv: paymentFormPlaceholders.cvv,
  expirationDate: paymentFormPlaceholders.expirationDate,
  postalCode: paymentFormPlaceholders.postalCode,

  //Initialize application identifiers
  applicationId: paymentFormParams.applicationId,
  locationId: paymentFormParams.locationId,

  //Initialize payment form styles
  inputClass: paymentFormParams.inputClass,
  inputStyles: paymentFormParams.inputStyles,

  //Initialize payment form callbacks
  callbacks: paymentFormParams.callbacks
});
      

Configuration Field Data Types

placeholder

Represents an input string placeholder

Fields

Name Type Description
elementId string The document object model (DOM) id of the placeholder element.
placeholder string a text string that appears in the iframe when it is first rendered. Only applies to input field placeholders (e.g., cardNumber).

InputStyle

Represents a style based on window width for the interior of the iframe input fields (e.g., font family, color).

As with CSS, InputStyle objects are applied in the order they are defined. If a particular property is set by multiple InputStyle objects for the same window width, the last defined property takes precedence.

SqPaymentForm currently supports the following InputStyle properties:

Fields

Name Type Description
mediaMinWidth string The minimum window width in pixels that this set of styles applies to. The default value is "0px".
mediaMaxWidth string The maximum window width in pixels that this set of styles applies to. The default value is "infinite".
backgroundColor string Corresponds to the background-color
boxShadow string Corresponds to the box-shadow CSS property.
color string Corresponds to the color CSS property and accepts hexadecimal, RGB, and CSS built-in color values.
fontFamily string Corresponds to the font-family CSS property and accepts common web safe font names (e.g., Arial, Helvetica). Custom web fonts are not currently supported.
fontSize string orresponds to the font-size CSS property and accepts pixel (px), point (pt), and proportional (em) values.
fontWeight string Corresponds to the font-weight CSS property.
lineHeight string Corresponds to the line-height CSS property and accepts pixel (px), point (pt), and proportional (em) values.
padding string Corresponds to the padding CSS property and accepts pixel (px), point (pt), and proportional (em) values.
placeholderColor string Corresponds to the color CSS property of the ::placeholder pseudo-element and accepts hexadecimal, RGB, and CSS built-in color values.
placeholderFontWeight string corresponds to the font-weight CSS property of the ::placeholder pseudo-element. Note that placeholderFontWeight can only be passed in as a default inputStyle.

PaymentRequest Objects

Digital wallet services (e.g., Apple Pay for Web) expect payment requests in a specific format. The result is that the fields in the createPaymentRequest function are different from Square internal data types. For example, the monetary value for amount in the payment form is a float rather than an integer and the line items in a digital wallet payment are not related to Square's Order object.


{
  requestShippingAddress: true,
  requestBillingInfo: true,
  shippingContact: {
    familyName: "CUSTOMER LAST NAME",
    givenName: "CUSTOMER FIRST NAME",
    email: "mycustomer@example.com",
    country: "USA",
    region: "CA",
    city: "San Francisco",
    addressLines: [
      "1455 Market St #600"
    ],
    postalCode: "94103"
  }
  currencyCode: "USD",
  countryCode: "US",
  total: {
    label: "MERCHANT NAME",
    amount: "TOTAL AMOUNT",
    pending: false
  },
  lineItems: [
    {
      label: "Subtotal",
      amount: "SUBTOTAL AMOUNT",
      pending: false
    },
    {
      label: "Shipping",
      amount: "SHIPPING AMOUNT",
      pending: true
    },
    {
      label: "Tax",
      amount: "TAX AMOUNT",
      pending: false
    }
  ]
}
    

paymentRequest Fields

Name Type Description
requestShippingAddress boolean Lets customers select a shipping address from the digital wallet UI. The requestShippingAddress field is only valid for digital wallets that support address selection. The selected address is returned as a SqContact JSON object.
requestBillingInfo boolean Lets customers select a billing address from the digital wallet UI. The requestBillingInfo field is only valid for digital wallets that support address selection. The selected address is returned as a SqContact JSON object.
shippingContact (optional) SqContact JSON object. Default shipping contact information that will be displayed in the digital wallet UI.
countryCode string 2-letter ISO 3166-1 alpha-2 country code
currencyCode string 3-letter ISO 4217 currency code
lineItems array of SqLineItem JSON objects. The list of items included in the transaction. This information is typically displayed in the digital wallet UI.
total SqLineItem JSON object. The merchant name, status, and total cost of the transaction. This information is typically displayed in the digital wallet UI.

SqPayment Data Types

SqLineItem

Represents a payment line item

Fields

Name Type Description
label string A human-readable string that explains the purpose of the amount. For a line item, this is typically the name of the charge or object purchased. For the total field, this is typically the merchant name.
amount float The cost of the object as a float (e.g., 15.00). For a line item, this is typically the cost of the object, a subtotal, or additional charge (e.g., taxes, shipping). For the total field, this is the total charge of the transaction and should equal the sum of the line item amounts.
pending (optional) boolean A boolean indicating whether or not the value in the amount field represents an estimated or unknown cost. Typically, this field is false.

SqContact

Represents a payment request shipping contact

Fields

Name Type Description
familyName string Last name of the contact
givenName string First name of the contact.
email string Email address of the contact.
country string A 2-letter string containing the ISO 3166-1 country code of the contact address.
countryName string The full country name of the contact. countryName is a read-only attribute and based on the 2-letter country code in country.
region string The applicable administrative region (e.g., province, state) of the contact address.
city string The city name of the contact address.
addressLines array of strings The street address lines of the contact address.
postalCode string The postal code of the contact address.