Square payment form

Data Model

Data Model Overview

The SqPaymentForm data model includes four primary elements:

  • SqPaymentForm functions - SqPaymentForm helper functions that optimize payment form behavior for single-page web applications.
  • SqPaymentForm Configuration fields - SqPaymentForm 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 on the Web).

sqPaymentForm functions

sqPaymentForm function reference.

build function

Manually builds the payment form.

Replaces placeholder tags with corresponding iframe hosted SqPaymentForm input fields

build: function ()

Remarks

To manage the payment form initialization manually, set the autoBuild configuration option to false, and call the build function on the page where you want to initialize the payment form:

SqPaymentForm only replaces placeholder tags with input fields. when the DOMContentLoaded event is fired.

Use this function if SqPaymentForm is initialized after the page has fired the DOMContentLoaded event.

Examples


paymentForm.build();
              

recalculateSize function

Forces SqPaymentForm to re-render iframes.

recalculateSize: function ()

Remarks

Re draws the payment form iframes. This function must be called when the payment form placeholder tags are contained in a div tag that was hidden when the page DOM was loaded. After making the containing div visible, call recalculateSize

Examples


paymentForm.recalculateSize();
              

destroy function

Removes SqPaymentForm event listeners from a page.

destroy: function ()

Remarks

The SqPaymentForm object registers multiple event listeners on your webpage. These listeners go away when control is passed to a new page, but if you have a single-page web application, those listeners might remain longer than you want.

To manually remove the listeners from your webpage, add the function call where you want to clean up after the payment form.

Examples


paymentForm.destroy();
              

isSupportedBrowser function

Detect unsupported host browser.

Use this method to detect an unsupported browser before instantiating SqPaymentForm

isSupportedBrowser: function () {}

Return Value

boolean.

Examples


if (SqPaymentForm.isSupportedBrowser()) {
  var paymentForm = new SqPaymentForm({ ... });
} else {
  // browser not supported
}
         

setPostalCode function

The setPostalCode function sets the postal code based on information previously entered (e.g., from a billing address).

setPostalCode: function (postalCode) {}

Parameters

Name Type Description
postalCode string

Postal code that is displayed in the payment form.

Remarks

Setting postalCode programmatically will make entering payment information more convenient for your customers.

Calling paymentForm.setPostalCode outside paymentFormLoaded will fail, even if the form has fully loaded. A successful call to paymentForm.setPostalCode also triggers the postalCodeChanged input event in the inputEvenReceived callback function.

>

Examples


paymentFormLoaded: function() {
      paymentForm.setPostalCode("POSTAL CODE FROM SHIPPING");
}
              

focus function

Sets input focus on the specified SqPaymentform input field.

focus: function (field) {}

Parameters

Name Type Description
field string

The input field to receive focus. The value must be one of:

  • cardNumber: the card number field
  • cvv: The CVV field
  • expirationDate: The expiration date field
  • postalCode: The postal code field

Remarks

Examples


    paymentFormLoaded: function() {
      paymentForm.focus("cardNumber");
    }
            

requestCardNonce function

Request a nonce from the SqPaymentForm object

requestCardNonce: function ()

Remarks

A nonce is available after the user clicks the "Pay with credit card" button on the payment form. The requestCardNonce callback is invoked by the payment form on the button click.

Call paymentForm.requestCardNonce() to get the nonce.

Examples

The following example gets the nonce from the payment form after a user has clicked the "Pay with credit card" button and the payment form invoked the requestCardNonce callback.


function requestCardNonce(event) {

  // Don't submit the form until SqPaymentForm returns with a nonce
  event.preventDefault();

  // Request a nonce from the SqPaymentForm object
  paymentForm.requestCardNonce();
}            

Callback functions

sqPaymentForm callback function reference.

cardNonceResponseReceived function

(required)

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 - Optional: 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

Nonce generation errors

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.
UNSUPPORTED_CARD_BRAND Card is not supported
Field/Message:
  • cardNumber: Card is not supported
UNKNOWN An unknown error occurred.
VALIDATION_ERROR The provided data is invalid
Field/Message:
  • cardNumber: Credit card number is not valid
  • expirationDate: Expiration date is not valid
  • postalCode: Expiration date is not valid
  • cvv: CVV is not valid

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

createPaymentRequest function

(required for Apple Pay, Google Pay, Masterpass)

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

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

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. This function will be invoked multiple times, once for each digital wallet you want to enable, with the methods object containing a single key (applePay, googlePay or masterpass) with a boolean value indicating whether the digital wallet is enabled or not.

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

  console.log(methods)
  // Only show the button if Apple Pay on the 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';
  }
}
              

paymentFormLoaded function

Invoked when SqPaymentForm is fully loaded.

paymentFormLoaded: function()

Examples


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

unsupportedBrowserDetected function

Invoked when the payment form is hosted in an unsupported browser. use the function to detect when the payment form is attempting to load in an unsupported browser. Use the callback to tell the user that the payment form cannot be loaded.

unsupportedBrowserDetected: function()

Examples


unsupportedBrowserDetected: function () {
      // update page element or show alert to tell user that payment form is not
      // supported in their browser.
}
              

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

Configuration Fields

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

Individual configuration fields are required for some payment form features and optional for others. Features include payment card entry fields, Apple Pay button, Google Pay button, and Masterpass button.

The Description column indicates the payment form feature where a field is required. For example, if a payment form implementation is to render only the Google Pay button then only the following configuration fields are required:

  • applicationId
  • locationId
  • googlePay

Configuration fields

Name Type Description
applePay placeholder JSON object.

Required for Apple Pay

Sets the <button> ID of the placeholder for the Apple Pay for Web button.

applicationId string

Required for all features

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.

Required for payment card

Sets the <div> ID and placeholder text of the input field placeholder for the credit card number.

cvv placeholder JSON object.

Required for payment card

Sets the <div> ID and placeholder text of the input field placeholder for the credit card's CVV.

expirationDate placeholder JSON object.

Required for payment card

Sets the <div> ID and placeholder text of the input field placeholder for credit card's expiration date.

googlePay placeholder JSON object.

Required for Google Pay

Sets the <button> ID and placeholder text of the placeholder for the googlePay button.

locationId string

required for Apple Pay, Google Pay

Identifies the location of the merchant that is taking the payment. Obtained from the Square Application Dashboard - Locations tab.

masterpass placeholder JSON object.

required for Masterpass

Sets the <button> ID and placeholder text of the placeholder for the Masterpass button.

postalCode placeholder JSON object.

Required for payment card

Sets the <div> ID and placeholder text of the postal code input field placeholder.

inputClass string

Required for payment card

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 examples

Payment form with Google Pay button

The following example initializes the payment form with only a Google Pay button.


var paymentForm = new SqPaymentForm({
  // Initialize Google Pay placeholder ID
  googlePay: {
    elementId: 'sq-google-pay'  //REPLACE ME
  },
  applicationId: "{REPLACE ME WITH YOUR APPLICATION ID}",
  locationId: "{REPLACE ME WITH YOUR LOCATION ID}",

    // SqPaymentForm callback functions
  callbacks: {

    /*
     * 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: 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: methodsSupported
     * `methodsSupported` will be called multiple times, once for each digital
     * wallet you want to enable.
     * The `methods` object will contain a single key (applePay, googlePay or
     * masterpass) with a boolean value indicating whether the digital wallet
     * is enabled or not. For example, if Google Pay is available, `methods`
     * will be the object: {googlePay: true}.
     */
    methodsSupported: function (methods) {

      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 Google Pay is enabled
      // Otherwise, display the wallet not enabled message.
      if (methods.googlePay === true) {
        googlePayBtn.style.display = 'inline-block';
        googlePayLabel.style.display = 'none';
      }
    }
  }
});
      

Payment form with payment card fields

The following example initializes the payment form with only payment card input fields, the optional inputStyles object, the required cardNonceReceived callback, and two optional callbacks.


var paymentForm = new SqPaymentForm({
  // Initialize the payment form elements
  applicationId: "{REPLACE ME WITH YOUR APPLICATION ID}",
  inputClass: 'sq-input',
  // Initialize the credit card placeholders
  cardNumber: {
    elementId: 'sq-card-number',
    placeholder: '• • • •  • • • •  • • • •  • • • •'
  },
  cvv: {
    elementId: 'sq-cvv',
    placeholder: 'CVV'
  },
  expirationDate: {
    elementId: 'sq-expiration-date',
    placeholder: 'MM/YY'
  },
  postalCode: {
    elementId: 'sq-postal-code',
    placeholder: '12345'
  },
  // 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: 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');
    }
  }
});
      

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 on the 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 string The cost of the object as a string representation of a float with 2 decimal places. (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.
phone string The telephone number of the contact.