Take Payments

Square Payment Form Overview

Square's payment form provides a secure, PCI-compliant way to accept credit card and digital wallet payments.

Square hosts a small Javascript library (SqPaymentForm) that looks for HTML placeholders and replaces them with iframes to create a secure payment form. The payment form accepts payment cards details then generates an encrypted payment token, known as a nonce. Nonces are used with Square's Transactions API to collect eCommerce payments.

Requirements and limitations

  • Sites must use the Square-hosted version of the SqPaymentForm library. Applications referencing a copy of the Javascript library hosted on a non-Square server will be disabled without notice.
  • Square's payment form must be generated on a webpage that uses HTTPS. Credit card and Masterpass payments may be tested with localhost without using HTTPS, but HTTPS is required for all Apple Pay and and Google Pay transactions.
  • Apple Pay on the Web requires domain registration with Apple. SqPaymentForm will not render the Apple Pay button unless Apple indicates the site domain is valid.
  • Nonces created with digital wallets cannot be used to store a customer card on file.
  • Shipping address validation is only available for digital wallets that support address selection in their UI (e.g., Apple Pay on the Web).
  • Square's API sandbox does not support Apple Pay on the Web or Google Pay at this time.

How to use it — the SqPaymentForm data model

The SqPaymentForm data model includes three primary elements:

  • Configuration fields — data fields that define HTML placeholder names, enable/disable payment features, and control presentation of the form fields.
  • 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).

Configuration Fields

SqPaymentForm renders the form based on the configuration of its data 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.
googlePay placeholder JSON object Sets the <button> ID of the placeholder for the Google Pay button.
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 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 InputStyle objects Define the internal styles applied to the rendered iframes.

Placeholder JSON objects

The JSON object for placeholder fields has two string values:

  • elementId — the document object model (DOM) id of the placeholder element. This field is required.
  • placeholder — a text string that appears in the iframe when it is first rendered. This field is optional, and only applies to input field placeholders (e.g., cardNumber).
field-name: {
  elementId: 'DOM ID',
  placeholder: 'OPTIONAL TEXT'
},

Placeholders are disabled by setting the associated field to false. For example:

masterpass: false

InputStyle objects

The inputStyles field accepts an array of of InputStyle objects that define styles based on window width for the interior of the iframe input fields (e.g., font family, color). Typically, the first entry in the style array sets the default styles and subsequent style objects modify those styles based on the width of the screen used to view the payment form. For example:

inputStyles: [

  // This object does not provide values for mediaMaxWidth or mediaMinWidth.
  // These styles are applied to screens of all sizes, unless overridden
  // by another input style below.
  {
    fontSize: '24px',
    padding: '3px'
  },

  // These styles are ONLY applied to inputs when the screen width is 400px
  // or smaller. Note that because it doesn't specify a value for padding,
  // the padding value in the previous object is preserved.
  {
    mediaMaxWidth: '400px',
    fontSize: '18px'
  }
],

As with CSS, the 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:

  • mediaMinWidth — The minimum window width in pixels that this set of styles applies to. The default value is "0px".
  • mediaMaxWidth — The maximum window width in pixels that this set of styles applies to. The default value is "infinite".
  • backgroundColor — Corresponds to the background-color CSS property and accepts hexadecimal, RGB, and CSS built-in color values.
  • boxShadow — Corresponds to the box-shadow CSS property.
  • color — Corresponds to the color CSS property and accepts hexadecimal, RGB, and CSS built-in color values.
  • fontFamily — 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 — Corresponds to the font-size CSS property and accepts pixel (px), point (pt), and proportional (em) values.
  • fontWeight — Corresponds to the font-weight CSS property.
  • lineHeight — Corresponds to the line-height CSS property and accepts pixel (px), point (pt), and proportional (em) values.
  • padding — Corresponds to the padding CSS property and accepts pixel (px), point (pt), and proportional (em) values.
  • placeholderColor — Corresponds to the color CSS property of the ::placeholder pseudo-element and accepts hexadecimal, RGB, and CSS built-in color values. Note that placeholderColor can only be passed in as a default inputStyle.
  • placeholderFontWeight — Corresponds to the font-weight CSS property of the ::placeholder pseudo-element. Note that placeholderFontWeight can only be passed in as a default inputStyle.

Callback functions

The SqPaymentForm object includes the following callback functions:

  • cardNonceResponseReceived — Called when SqPaymentForm receives the result of a nonce generation request. The result will be a valid credit card or wallet nonce or an error.
  • createPaymentRequest — Passes transaction information to the digital wallet provider to create a wallet nonce. Called when a digital wallet button in the payment form is clicked.
  • inputEventReceived — Called when a form interaction event occurs while a buyer is filling out the payment form.
  • methodsSupported — Called by Square's JS library when the page renders to decide which, if any, digital wallet button should be rendered in the payment form.
  • paymentFormLoaded — Called when all payment form iframes are successfully added to the webpage.
  • unsupportedBrowserDetected — Called when SqPaymentForm detects the page is rendered in an unsupported browser.
  • validateShippingContact — Called when the user pays with a digital wallet that supports address selection, requestShippingAddress is true in the PaymentRequest object, and the user selects/changes shipping information in the digital wallet UI.

Each of these callback functions can be customized to control how SqPaymentForm interacts with the webpage in which it is embedded and the browser in which the page is rendered.

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's 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",
    phone:"14255551212"
  },
  currencyCode: "USD",
  countryCode: "US",
  total: {
    label: "MERCHANT NAME",
    amount: "85.00",
    pending: false
  },
  lineItems: [
    {
      label: "Subtotal",
      amount: "60.00",
      pending: false
    },
    {
      label: "Shipping",
      amount: "19.50",
      pending: true
    },
    {
      label: "Tax",
      amount: "5.50",
      pending: false
    }
  ]
}

paymentRequest Fields

Name Type Description
requestShippingAddress boolean required
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 required
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 SqContact JSON object. optional
Default shipping contact information that will be displayed in the digital wallet UI.
countryCode string required
2-letter ISO 3166-1 alpha-2 country code
currencyCode string required
3-letter ISO 4217 currency code
lineItems array of SqLineItem JSON object required
The list of items included in the transaction. This information is typically displayed in the digital wallet UI.
total SqLineItem JSON object required
The merchant name, status, and total cost of the transaction. This information is typically displayed in the digital wallet UI.

SqLineItem JSON object

The SqLineItem JSON object has the following fields:

  • label — 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 — the cost of the object as a string representation of a float with 2 decimal places. (e.g., "15.00"). For a line, 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 — a boolean indicating whether or not the value in the amount field represents an estimated or unknown cost. Typically, this field is false.

SqContact JSON object

The SqContact JSON object has the following fields:

  • familyName — a string containing the last name of the contact.
  • givenName — a string containing first name of the contact.
  • email — a string containing email address of the contact.
  • country — a 2-letter string containing the ISO 3166-1 country code of the contact address.
  • countryName — a string containing the full country name of the contact. countryName is a read-only attribute and based on the 2-letter country code in country.
  • region — a string containing the applicable administrative region (e.g., province, state) of the contact address.
  • city — a string containing the city name of the contact address.
  • addressLines — an array of strings containing the street address lines of the contact address.
  • postalCode — a string containing the postal code of the contact address.
  • phone — a string containing the telephone number of the contact.

All contact fields are optional and partial contact information is allowed.

How it works — Payment Form process flow

SqPaymentForm looks for placeholder HTML elements to generate a secure payment form that supports payments from credit cards, Apple Pay on the Web, Google Pay, and Masterpass. In general, the steps for rendering a payment form and requesting a nonce are:

  1. A customer opens the page, which loads the SqPaymentForm library.
  2. SqPaymentForm checks to see if the browser is compatible. If not, the unsupportedBrowserDetected callback triggers, which ends the process.
  3. The methodsSupported callback triggers, which checks to see which of the available digital wallets are enabled and supported.
  4. SqPaymentForm replaces the HTML placeholders with iframes and the paymentFormLoaded callback triggers.
  5. The customer clicks on a digital wallet button or clicks "Pay with card".
    • If a digital wallet is clicked, the createPaymentRequest callback triggers. The validateShippingContact callback is also triggered if the digital wallet supports address selection and the user selects or changes a shipping address in the digital wallet UI.
    • If "Pay with card" is clicked, Javascript on the page calls the SqPaymentForm.requestCardNonce() function.
  6. The cardNonceResponseReceived callback triggers.
  7. Javascript on the page handles the nonce response:
    • If nonce generation succeeds, set the hidden nonce field and submit the form.
    • If nonce generation fails, handle the errors and provide feedback to the customer.
Process flow

The cardNonceResponseReceived callback

The cardNonceResponseReceived callback includes the following parameters:

  • errors — an array of JSON objects that describe any errors that occurred during nonce creation or null if creation succeeded. 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 — a string representing the nonce that was created or null if an error occurred. Nonce values expire after 24 hours.
  • cardData — a JSON object containing non-confidential information about the customer's 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: APPLE_PAY, GOOGLE_PAY, MASTERPASS, NONE
  • billingContact — a SqContact JSON object containing the billing contact information provided by a digital wallet UI that supports address selection.
  • shippingContact — a SqContact JSON object containing the shipping contact information provided by a digital wallet UI that supports address selection.

Nonce generation errors

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.

The validateShippingContact callback

The validateShippingContact callback is triggered when requestShippingAddress is true in the PaymentRequest object sent to a digital wallet that supports address selection and the user selects (or modifies) a shipping address in the digital wallet UI.

  • If validation succeeds, validateShippingContact should return null.
  • If validation fails, validateShippingContact should return a SqValidationErrors JSON object.

The validateShippingContact callback is customizable and used to take additional action to verify the contact information provided by the digital wallet. For example, a US wine merchant can use validateShippingContact to verify they can ship alcohol to the state indicated in the shipping address.

SqValidationErrors JSON object

A SqValidationErrors object includes the following fields:

  • country — an array of 1 or more human-readable strings explaining why the country provided is invalid.
  • region — an array of 1 or more human-readable strings explaining why the region provided is invalid.
  • city — an array of 1 or more human-readable strings explaining why the city provided is invalid.
  • addressLines — an array of 1 or more human-readable strings explaining why the address lines provided is invalid.
  • postalCode — an array of 1 or more human-readable strings explaining why the postal code provided is invalid.

All fields in the SqValidationErrors object are optional, but at least one field must be set if the shipping address provided in validateShippingContact fails validation.

The inputEventReceived callback

The inputEventReceived callback operates independently from the main nonce generation workflow. The callback is customizable and used to take additional action when one of the following event types is 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.

The inputEventReceived callback includes an inputEvent parameter that provides actionable information about the event. For example:

{
  cardBrand: "masterCard",
  elementId: "sq-card-number",
  eventType: "focusClassRemoved",
  field: "cardNumber",
  currentState: {
    hasErrorClass: false,
    hasFocusClass: false,
    isCompletelyValid: true,
    isPotentiallyValid: true
  },
  previousState: {
    hasErrorClass: false,
    hasFocusClass: true,
    isCompletelyValid: false,
    isPotentiallyValid: true
  }
}

The fields of the inputEvent parameter are updated each time the customer interacts with the form:

Name Type Description
cardBrand string An enum value indicating the most likely brand of the customer's card, as indicated by the current value of the credit card number input field: americanExpress, discover, discoverDiners, JCB, masterCard, unionPay, unknown, visa.
elementId string The id of the payment form field that the event applies to.
eventType string The inputEventReceived event detected
field string The SqPaymentForm field that the event applies to: cardNumber, postalCode, cvv, or expirationDate.
currentState Input state JSON object The current state of the payment form field that the event applies to.
previousState Input state JSON object The state of the payment form field immediately before the event occurred. Compare this field with currentStatefield to determine what may have changed

Input state JSON objects

Each input state JSON object includes the following Boolean fields:

  • hasErrorClass — if the field is true, the form input has an invalid value, and the corresponding error CSS class was applied to the input.
  • hasFocusClass — if the field is true, the form input has focus, and the corresponding focus CSS class was applied to the input.
  • isPotentiallyValid — if the field is true, the value of the input field meets most validation requirements, but the value does not meet the expected length for the input.
  • isCompletelyValid — if the field is true, the value of the input meets ALL validation requirements for the input, including the length and character-type requirement.

The values of isPotentiallyValid and isCompletelyValid will change as the form input changes and can be used in combination to determine if there is a problem with the form input. For example, isPotentiallyValid will be true for the credit card number input field when the current value is "123", even though the value is not long enough for an actual credit card because it only contains numeric characters. In comparison, isCompletelyValid will be false until the credit card number input field is both the correct length and only consists of numeric characters.

Next
Payment Form Setup >

Contact Developer Support, join our Slack channel, or ask for help on Stack Overflow