Square Payment Form

Build the Payment Form

Embed Square Payment Form on your website to collect credit cardand digit wallet information securely.

Web
Client Side

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 Payment Form must be generated on a webpage that uses HTTPS. Debit, credit, and Masterpass payments may be tested with localhost without using HTTPS, but HTTPS is required for all Apple Pay transactions.
  • Apple Pay on the Web requires domain registration with Apple. payment form 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 sandbox does not support Apple Pay on the Web at this time.
  • Square Payment Form auto-populates fields (except CVV field) if the buyer has enabled autofill in the browser settings and stored credit card details in the browser. Most browsers do not permit auto-population of the CVV field for security reasons.

Step 1: Download basic payment form templates from GitHub

Download the payment form integration template files from GitHub and save them in your project. Your download choice depends on whether your payment page will support payment card only, payment card and digital wallet, or digital wallet only.

Payment form integration template files provide all of the JavaScript, HTML, and stylesheets that you need for a payment form integration.

Step 2: Add script references to your payment page head

To include the SqPaymentForm library and implementation files, add the following references to your page:

<!-- link to the SqPaymentForm library -->
<script type="text/javascript" src="https://js.squareup.com/v2/paymentform">
</script>

<!-- link to the local SqPaymentForm initialization -->
<script type="text/javascript" src="path/to/sqpaymentform-basic.js">
</script>

<!-- link to the custom styles for SqPaymentForm -->
<link rel="stylesheet" type="text/css" href="path/to/sqpaymentform-basic.css">

Each of the references serves a specific purpose:

  • js.squareup.com/v2/paymentform — Square's canonical JavaScript library for SqPaymentForm. The payment form will not work without this reference.
  • sqpaymentform-basic.js — a local JavaScript file to configure and initialize the SqPaymentForm object.
  • sqpaymentform-basic.css — a local CSS file (stylesheet) to customize the look of the payment form.

Step 3: Add the HTML form to your payment page

Open the sqpaymentform-basic.html file that you downloaded in Step 1. Add the form container <div id="form-container"> and its child elements into the body of your payment page.

<div id="form-container">
   ...
</div> <!-- end #form-container -->

Step 4: Render SqPaymentForm

In your page, write JavaScript logic that calls isSupportedBrowser to check for browser support and then calls build to render the payment form if the host browser is supported.

Where you call your JavaScript code depends on what kind of web app you are building:

  • Payment form in a "payment" page: The payment form is the only content in a page that is loaded to take a payment. Display the payment form in the DOMContentLoaded event for the body of your payment page.
1  document.addEventListener("DOMContentLoaded", function(event) {
2    if (SqPaymentForm.isSupportedBrowser()) {
3      paymentForm.build();
4      paymentForm.recalculateSize();
5    }
6  });
  • Payment form in a hidden <div> on checkout page : Display the payment form on the JavaScript action that reveals the payment feature in your page. Be sure that the HTML placeholder elements are loaded in the page before calling the helper.
  <!--Your payment page declaration-->
 <div id="orderSummary">
 ...
  <button id='show-paymentform' onclick='buildForm()'>Pay now</button>

    <!--Square template form-container div-->
    <div id="form-container">
    ...   
    </div>
    <!--end Square template form-container div-->
 ...   
 </div>
 <script type="text/javascript">
  function buildForm() {
    if (SqPaymentForm.isSupportedBrowser()) {
      var paymentDiv = document.getElementById("form-container");
      if (paymentDiv.style.display === "none") {
          paymentDiv.style.display = "block";
      }
      paymentForm.build();
      paymentForm.recalculateSize();
    } else {
      // Show a "Browser is not supported" message to your buyer
    }
  }
 </script>
 <!--end Your payment page declaration-->

Step 5: Set Application and Location IDs

SqPaymentForm will not load properly unless the applicationId is set with a valid Square Application ID. If you are using one of the digital wallet templates, the locationId variable must also be set.

We recommend using sandbox IDs for testing and development. To get your sandbox IDs:

  1. Open your Application Dashboard.
  2. Click on the application you want to use for the payment form.
  3. On the Credentials tab of the application control panel, copy the Sandbox Application ID.
  4. On the Locations tab of the application control panel, copy one of the Location ID values from the list of Sandbox locations.

Now update your copy of sqpaymentform-basic.js by replacing REPLACE_ME with the application and location IDs from the dashboard:

 1// Set the application ID
 2var applicationId = "REPLACE_ME";
 3
 4// Set the location ID
 5var locationId = "REPLACE_ME";
 6
 7// Create and initialize a payment form object
 8var paymentForm = new SqPaymentForm({
 9  ...
10});

Step 6: Set the <form> action parameter

In the sqpaymentform-basic.html template, Replace path/to/payment/processing/page in the action parameter with the path to your payment processing page.

 1<div id="sq-ccbox">
 2  <!--
 3    You should replace the action attribute of the form with the path of
 4    the URL you want to POST the nonce to (for example, "/process-card")
 5  -->
 6  <form id="nonce-form" novalidate action="path/to/payment/processing/page" method="post">
 7    Pay with a Credit Card
 8
 9    ...
10
11    <!--
12      After a nonce is generated it will be assigned to this hidden input field.
13    -->
14    <input type="hidden" id="card-nonce" name="nonce">
15  </form>
16</div>

Step 7: Test the payment form

The example HTML, JavaScript, and CSS should run without modification once the application and location IDs are set.

Test with a credit card

If you have downloaded the basic templates without digital wallet support, the testing guidance in this section applies to your payment form integration.

To confirm the form renders properly and verify nonce generation succeeds for credit cards, open your new payment page. You should see a minimal HTML page:

Diagram sqpaymentform basic

If your page does not look similar to the screenshot above, follow the Troubleshooting the payment form steps and try again.

Start by filling in the Pay with a Credit Card form with a credit card number that includes non-numeric characters (e.g., A53B759734545858). SqPaymentForm performs basic real-time validation on information entered in the iframe fields. The .sq-input--error CSS class will be applied to the "Card Number" field to highlight the error.

Now fill in the Pay with a Credit Card form with test card information and click "Pay with Card":

  • Card Number: 4532759734545858
  • CVV: any three non-consecutive numbers
  • Expiration Date: any month and year in the future
  • Postal Code: 94103

Test with a digital wallet payment

If you are integrating a digital wallet-only payment form, the form renders with the digital wallets supported in your browser. If you are not using the Safari browser on a Mac or iOS device, the Apple Pay button will not be rendered.

Click an active digital wallet button and complete the payment authorization. Upon authorization, a nonce is produced by SqPaymentForm.

Diagram sqpaymentform digital wallet only

Get test results

If a nonce is produced by SqPaymentForm then it is used to set the value of the HTML card-nonce and then submitted to the form action path that you set in step 6.

If SqPaymentForm could not produce a nonce, an alert should appear that displays the error returned by SqPaymentForm from Square's servers. If an alert doesn't appear, check the browser's JavaScript console for information about the error encountered.

A nonce is an encrypted payment token. It is generated by payment form and holds information to identify the payment tender for an online payment. The generated nonce is used with Square's Transactions API to create charges.

Step 8: Take a payment

Create a backend payment processing page to accept the nonce sent from the payment form in Step 6.

  1. The backend page accepts the nonce posted by the payment form.
    // Fail if the payment form didn't send a value for `nonce` to the server
    $nonce = $_POST['nonce'];
    if (is_null($nonce)) {
      error_log("No nonce was passed to processcard.php.");
      echo "Invalid card data";
      http_response_code(422);
      return;
    }
  1. The backend page takes a payment by making a request on the Transactions API endpoint to POST a payment.
    //Charge the card for the order using the nonce.
    $transactions_api = new \SquareConnect\Api\TransactionsApi();
    $note = sprintf("{'fn':'%s', 'em':'%s' }", $fullName, $email); //Add a note to capture fullname and email.
    $charge = new \SquareConnect\Model\ChargeRequest();
    $charge->setCardNonce($nonce);
    $charge->setIdempotencyKey(com_create_guid());
    $charge->setAmountMoney("100");
    $charge->setNote($note);
    //If this call fails, let the top level catch block handle the exception.
    $chargeResult = $transactions_api->charge($locationId, $charge);

The following example shows the previous PHP Connect v2 client library call as a curl command.

curl --header "Content-Type: application/json" \
     --header "Authorization: YOUR_ACCESS_TOKEN" \
     --header "Accept: application/json"\
     --request POST \
     --data '{
        "idempotency_key": "UUID",
        "amount_money": {
          "amount": CHARGE_AMOUNT,
          "currency": "CURRENCY_CODE"
        },
        "card_nonce": "CARD_NONCE_FROM_PAYMENT_FORM"
      }' \
      https://connect.squareup.com/v2/locations/{YOUR_LOCATION_ID}/transactions

The nonce, charge amount, currency code, and a UUID idempotency key are the minimum set of data values needed to create a payment. The idempotency key should be generated as a UUID by the backend payment page. The nonce, charge amount, and currency code are provided by the payment form.

Read the Transactions API Setup guide to see PHP code examples that show how to develop a payment processing page or learn about payment processing with a Square payment processing sample in one of the following languages:

Next
Transactions API Overview >

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