Square payment form

SqPaymentForm

Object Model Overview

The SqPaymentForm object model includes these primary elements:

  • SqPaymentForm functions - SqPaymentForm helper functions that optimize payment form behavior for single-page web applications.
  • SqPaymentForm Callback functions - functions triggered when specific events happen. The behavior of these functions is fully customizable.
  • SqPaymentForm Configuration fields - SqPaymentForm data fields that define HTML placeholder names, enable/disable payment features, and control presentation of the form fields.
  • Digital wallet paymentRequest 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).
  • Apple Pay paymentDetailsUpdate objects - Used specifically for Apple Pay payments and used to update payment details when a shipping option or shipping contact is changed.
  • Data types - Various Square data types to support payment details, shipping options, and Strong Customer Authentication buyer verification types.

sqPaymentForm functions

sqPaymentForm function reference.

build

Manually builds the payment form.

Replaces InputTarget 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

Forces SqPaymentForm to re-render iframes.

recalculateSize: function ()

Remarks

Re draws the payment form iframes. This function must be called when the payment form InputTarget 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

Removes SqPaymentForm event listeners from a page.

destroy: function ()

Remarks

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

done

Makes a partial update to the payment request in response to a shipping contact or shipping option update in the Apple Pay sheet. Takes a paymentDetailsUpdate as the input.

done: function (paymentDetailsUpdate)

Remarks

done can only be called once inside of shippingContactChanged and shippingOptionChanged.

Examples


done({ total: newTotal });
              

isSupportedBrowser

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

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

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

Request a nonce from the SqPaymentForm

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

verifyBuyer

Verify the identity of the buyer.

Note: A TypeError is thrown if any function argument is missing or invalid.

verifyBuyer: function (source, verificationDetails, callback(err,verificationResult) {} ) {}

Parameters

Name Type Description
source string Required: Card nonce or card ID
verificationDetails SqVerificationDetails

Required: All available buyer verification details

callback function(err,result)

Required: Called when verification is complete

The callback is invoked with the following arguments:

  • errors: Error: Error messages
  • SqVerificationResult: object: Represents the result of the buyer verification. verificationResult.token can be used with the Transactions.Charge and Customers.CreateCustomer endpoints.

Remarks

When the cardholder bank and merchant account are in the European economic area, verification is done by invoking the 3DS 2.0 flow.

Examples

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


   /*
     * callback function: cardNonceResponseReceived
     * Triggered when: SqPaymentForm completes a card nonce request
     */
    cardNonceResponseReceived: function (errors, nonce, cardData) {
      // Assign the nonce value to the hidden form field
      document.getElementById('card-nonce').value = nonce;
      const verificationDetails = {
        amount: '100.00',
        intent: "CHARGE",  //Allowed values: "CHARGE", "STORE"
        billingContact: {
          familyName: "Smith",
          givenName: "John",
          email: "jsmith@example.com",
          country: "GB",
          city: "London",
          addressLines: ["1235 Emperor's Gate"],
          postalCode: "SW7 4JA",
          phone: "020 7946 0532"
        }
      };
      try {
        paymentform.verifyBuyer(
          nonce,
          verificationDetails,
          callback(err,verification) {
            if (err == null) {
              document.getElementById('buyerVerification-token').value = verification;
            }
        });
        // POST the nonce form to the payment processing page
        document.getElementById('nonce-form').submit();
      } catch (typeError) {
        //TypeError thrown if illegal arguments are passed
      }
    }
                

Callback functions

sqPaymentForm callback function reference.

Note: Callback functions are not asynchronous. Any function called within a callback must be synchronous or thenable. If a thenable function is called, the async/await pattern must not be used. Instead, get asynchronous results by calling the returned promise.then() function.

cardNonceResponseReceived

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

Parameters

Name Type Description
errors array of error

Collection of error messages returned by Square endpoint.

Each error 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 for the recipient of the purchased product or service

shippingOption SqShippingOption

Apple Pay only: Shipping option selected by the buyer in the Apple Pay payment sheet.

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

(required for Apple Pay, Google Pay, Masterpass)

Invoked when a digital wallet payment button is clicked.

Use this callback function to construct a paymentRequest 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.

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

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

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 methods 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

Invoked when SqPaymentForm is fully loaded.

paymentFormLoaded: function()

Remarks

This callback is used to set the state of Payment Form entry fields after the form has loaded. For example, use paymentForm.setPostalCode to set the postal code based on information previously entered (e.g., from a billing address).

Examples


paymentFormLoaded: function() {
  /* HANDLE AS DESIRED */
  paymentForm.setPostalCode("POSTAL CODE FROM BILLING");
}
          

unsupportedBrowserDetected

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

shippingContactChanged

Invoked when requestShippingAddress is true in PaymentRequest and the buyer selects a shipping address in the Apple Pay sheet or enters a new shipping address.

Use this callback to validate a the buyer shipping contact. If validation indicates a problem, return an error message for the buyer. Update payment request details if a change in shipping address requires it.

shippingContactChanged: function (shippingContact, done)

Parameters

Name Type Description
shippingContact SqContact

Redacted shipping contact that buyer selected in the Apple Pay payment sheet.

done done

Use to update the payment amount after taxes, service fees, or similar charges are recalculated. Pass a PaymentDetailsUpdate that contains payment request updates to send.

Return Value

Examples




shippingContactChanged: function (shippingContact, done) {
 var valid = true;
 var shippingErrors = {};

 if (!shippingContact.postalCode) {
   shippingErrors.postalCode = "postal code is required";
   valid = false;
 }
 if (!shippingContact.addressLines) {
   shippingErrors.addressLines = "address lines are required";
   valid = false;
 }

 if (!valid) {
   done({shippingContactErrors: shippingErrors});
   return;
 }

 // Shipping address unserviceable.
 if (shippingContact.country !== 'US' || shippingContact.country !== 'CA') {
   done({error: 'Shipping to outside of the U.S. and Canada is not available.'});
   return;
 }

 // Update total, lineItems, and shippingOptions for Canadian address.
 if (shippingContact.country === 'CA') {
   done({
     total: {
       label: "MERCHANT NAME",
       amount: "UPDATED AMOUNT",
       pending: false
     },
    // Note: lineItems REPLACES the set of the line items in the PaymentRequest
     lineItems: [
       ...

       {
         label: "Tax",
         amount: "UPDATED AMOUNT",
         pending: false
       }
     ],
     shippingOptions: [
       {
         id: "1",
         label: "SHIPPING LABEL",
         amount: "SHIPPING AMOUNT"
       }
     ]
   });
   return;
 }

 // No changes are necessary.
 done();
}
              

shippingOptionChanged

Invoked when the buyer selects a shipping option in the Apple Pay sheet.

Use this callback to respond to a shipping option change.

shippingOptionChanged: function (shippingOption, done)

Parameters

Name Type Description
shippingOption SqShippingOption

The shipping option that the buyer selects in the Apple Pay payment sheet.

done done

Use to update the payment amount after taxes, service fees, or similar charges are recalculated. Pass a PaymentDetailsUpdate that contains payment request updates to save.

Examples


// Update total and line Items after user selects a shipping option
shippingOptionChanged: function(shippingOption, done) {
   // Creates a new array of line items that includes only 1 line
   // item. The item for a shipping option. Production code would get the
   // array of line items from the original PaymentRequest and add/update a line
   // item for the shippingOption argument of this callback.
   const newLineItems = [{
     label: shippingOption.label,
     amount: shippingOption.amount,
     pending: false
   }];
   const newTotal = {
     label: "MERCHANT NAME",

     // TODO: total amount to be calc'd based on difference between old and new
     // amount of this shippingOption.amount if shippingOption.amount was updated.
     // -- OR --
     // Increase total amount if the line item for this shippingOption is new.
     amount: "SOME_AMOUNT + shippingOption.amount",
     pending: false
   };

  done({
   // Note: newLineItems REPLACES the set of the line items in the PaymentRequest
   // newTotal REPLACES the original payment total.
   lineItems: newLineItems,
   total: newTotal
 });
};
              

Anonymous Functions

Anonymous callback function reference.

function(err, result)

Gets the result of the operation and any errors on failure.

function (err, result)

Parameters

Name Type Description
err Error

Errors related to an update failure.

result SqVerificationResult

An object representing the results of the verification. Can be used with Transactions.Charge and Customers.CreateCustomerCard endpoints.

Examples


verifyBuyer(nonce, verificationDetails, (err, result) => {
   if (err) {
     //handle errors
     return;
   }
   console.log(result.token);
 });
              

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 InputTarget

Required for Apple Pay

Sets the <button> ID of the InputTarget 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 InputTarget

Required for payment card

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

cvv InputTarget

Required for payment card

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

expirationDate InputTarget

Required for payment card

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

giftCard InputTarget

Required for Square Gift Card input

Sets the <div> ID of the InputTarget for the Gifft Card number input field.

Note: If this configuration field is set in the SqPaymentForm initialization block, cardNumber, cvv, expirationDate, postalCode, and digital wallet fields must not be set.

googlePay InputTarget

Required for Google Pay

Sets the <button> ID and placeholder text of the InputTarget 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 InputTarget

required for Masterpass

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

postalCode InputTarget

Required for payment card

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

inputClass string

Required for payment card

Sets the CSS class that defines external styles for text-input iframes.

inputStyles InputStyle[]

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 InputTarget 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 inputTargets
  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');
    }
  }
});
      

Payment form with Gift Card input

The following example initializes the payment form with only a Gift Card input field.


var paymentForm = new SqPaymentForm({
  // Initialize Gift Card InputTarget ID
  giftCard: {
    elementId: 'sq-gift-card',
    placeholder: "GIFT CARD NUMBER"
  },
  applicationId: "{REPLACE ME WITH YOUR APPLICATION ID}",
  locationId: "{REPLACE ME WITH YOUR LOCATION ID}",

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

Configuration Field Data Types

InputTarget

Represents document object model (DOM) location and inital text of a payment form input field.

Fields

Name Type Description
elementId string The (DOM) id of the InputTarget element.
placeholder string a text string that appears in the iframe when it is first rendered. Only applies to input field inputTargets (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

Digital wallet services (e.g., Apple Pay on the Web) expect payment requests in a specific format. The result is that the money fields in the createPaymentRequest function are different from the internal Square Money data type. 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
    }
  ],
  shippingOptions: [
    {
      id: "1",
      label: "SHIPPING LABEL",
      amount: "SHIPPING COST"
    }
  ]
}
    

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.
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.
shippingContact (optional) SqContact Default shipping contact information that will be displayed in the digital wallet UI.
shippingOptions (optional) array of SqShippingOption A shipping option provided by the merchant.
countryCode string 2-letter ISO 3166-1 alpha-2 country code
currencyCode string 3-letter ISO 4217 currency code
lineItems array of SqLineItem The list of items included in the transaction. This information is typically displayed in the digital wallet UI.
total SqLineItem The merchant name, status, and total cost of the transaction. This information is typically displayed in the digital wallet UI.

PaymentDetailsUpdate

Sets values for a partial update of the payment request.


{
 total: {
   label: "MERCHANT NAME",
   amount: "TOTAL AMOUNT",
   pending: false
 },
 lineItems: [
   {
     label: "Subtotal",
     amount: "SUBTOTAL AMOUNT",
     pending: false
   },
   {
     label: "Tax",
     amount: "TAX AMOUNT",
     pending: false
   }
 ],
 shippingOptions: [
   {
     id: "1",
     label: "SHIPPING LABEL",
     amount: "SHIPPING COST"
   }
 ]
}
    

paymentDetailsUpdate Fields

Name Type Description
error (optional) string Use this error if the shipping address is valid but the item cannot be shipped to that address.
shippingContactErrors (optional) SqShippingErrors Allows for granular validation errors for addressLine, country, city, region and postal code.
total (optional) SqLineItem Change the total amount of the transaction
lineItems (optional) array of SqLineItem To update the line items - most common updates are to add the cost of shipping and the sales tax based on the buyer’s shipping address.
shippingOptions (optional) array of SqShippingOption This is updated in response to the customer choosing a new shipping address

SqPaymentForm Data Types

The data types that support payment requests, shipping option and contact changed callback parameters, and Strong Customer AuthenticationverifyBuyer function.

SqLineItem

Represents a payment line item

Fields

Name Type Description
label string A human-readable string that explains the purpose of line item. This is typically the name of the charge or object purchased. If the line item is the total payment, this is usually the merchant name.
amount string The cost a purchased item 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 item, 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 items.
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. This field is returned in upppercase and maps to the Apple Pay countryCode field.
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.

SqShippingOption

A payment request shipping option

SqShippingOption can be declared in the payment request or inside the shippingContactChanged callback. If it is declared in both places, the declaration in the callback will be used by SqPaymentForm.

Fields

Name Type Description
id string A unique ID to reference this shipping option.
label string A short title for this shipping option. Shown in the Apple Pay interface
amount string The cost of this shipping option as a string representatin of a float. The value can be "0.00".

SqShippingErrors

Represents validation errors in specific parts of a physical address.

If a dictionary member is present, the corresponding part of a physical address has a validation error. Use the string value to describe the validation error and how a buyer can fix the error.

Fields

Name Type Description
addressLines (optional) string The physical address address lines are not valid.
city (optional) string The physical address city is not valid.
country (optional) string The physical address country is not valid.
region (optional) string The physical address region is not valid.
postalCode (optional) string The physical address postal code is not valid.

SqVerificationDetails

The data that is used to verify the identity of the buyer.

Note: verifyBuyer throws a TypeError when called with a SqVerificationDetails object in an invalid state.

Fields

Name Type Description
billingContact SqContact Required: All billing details for the buyer.
amount string

The amount of the transaction.

Required when intent is CHARGE. Must be unset when intent is STORE

currencyCode string

The currency for the transaction.

Note: This must be an ISO 4217 currency code and used in the merchant location.

Required when intent is CHARGE. Must be unset when intent is STORE

intent string

intent must have one of the following values:

  • CHARGE
  • STORE

intent indicates how the application intends to process the payment card on the backend. The card can be charged or stored for a future purchase.

SqVerificationResult

Represents a successful verification.

Fields

Name Type Description
token string The token representing a verified buyer.
userChallenged boolean true if the buyer was challenged for additional authentication factors.