Deprecated
This component is deprecated. See below for guidance about what to use instead.
Square Payment Form

Walkthrough: Integrate Square Payments in a Website

Warning

The "Square Payment Form" is deprecated. Please use the Web Payments SDK to take payments on a web client.

This topic provides a walkthrough with step-by-step instructions to set up a simple website integrated with Square for payments. We keep the exercise simple and build a basic form that only takes a credit card on a web page.

Overview Permalink Get a link to this section

The following example shows a basic form that only takes a credit card on a web page. Digital wallet examples are not shown.

payment formwalkthrough form@2x

Subsequent topics explain how to add digital wallets to your website. The SqPaymentForm technical reference is available when you need more information about one of the payment form library types or functions.

Processing payments in a website using Square is a two-step process:

  1. Generate a secure single-use payment token. Use the Square SqPaymentForm client-side library to accept credit card and digital wallet payment information and to generate a secure single-use payment token.

  2. Charge the payment source using the payment token. Use the Square Payments API to charge the payment source that the token represents.

Follow this process to set up a website and test the setup by taking a payment. The walkthrough also shows how to review the payment on the Seller Dashboard.

Before you begin, note the following:

  • The walkthrough uses a Node.js web server project template that Square provides. Node.js is used because it is easy to set up and test. After finishing this walkthrough, you can explore similar examples in other languages provided on GitHub. For more information, see connect-api-examples.

  • The walkthrough uses the Square Sandbox environment for testing. In the Sandbox, you do not charge real credit cards, but instead use a test card that Square provides for Sandbox testing. After taking a payment, you see how the payment appears in the Sandbox Seller Dashboard.

  • If you are new to the Square payment form, you should follow the step-by-step instructions. A complete sample is available on GitHub for download if you want to check your project code at the end of this walkthrough.

Get ready Permalink Get a link to this section

To prepare for the walkthrough:

  • Install Node.js and npm (a Node.js package manager).

  • Get your application credentials from the Square Developer Dashboard.

  • Download the project template created for this exercise.

Install Node.js and npm Permalink Get a link to this section

When you install Node.js, you also get npm. For instructions, see Node.js.

Get Sandbox application credentials Permalink Get a link to this section

The walkthrough uses the Square Sandbox environment for testing. Therefore, you use your Sandbox credentials.

Get your sandbox application credentials from the Square Developer Dashboard. Use the Square Sandbox environment for testing so that you do not charge your real credit card.

  1. Open the Developer Dashboard.

  2. Choose the application you want to use in the sandbox. If you do not have an application, create one. The application provides the credentials you need.

  3. Choose Credentials on the left navigation pane.

SandboxCredentials

  1. Make a note of the following values: Sandbox Application ID and Sandbox Access Token.

  2. On the Locations page, choose a location ID to use in the first step of integration.

SandboxLocations

Use a client application ID to obtain a payment token in step 1: 1.1.3 and on the server side, the personal access token to create a payment using the Payments API in step 2.

Download the project template Permalink Get a link to this section

For this exercise, start with a predefined project template to set up your initial web server.

  1. Download or clone the Node.js project template:

    • Download the zip file and unzip the content to a local directory.

    • Clone the GitHub repository to a local directory.

      Note

      Cloned and downloaded projects create different directory names:

      • Cloned. Sqpaymentform-nodejs-starterkit

      • Downloaded. Sqpaymentform-nodejs-starterkit-master

      • Downloaded the full sample. Sqpaymentform-nodejs-starterkit-sample

  2. Open a command line.

  3. Change to the project directory.

  4. Review the directory. Update the code in the following files in the project directory:

    • index.html is an empty static HTML page where you embed SqPaymentForm.

    • mysqpaymentform.css is a sample CSS file (stylesheet) to customize the look of the card entry fields on the page.

    • server.js contains the server-side component that charges the payment source (step 2).

  5. Run the following commands:

    a. Install dependencies:

    npm install
    

    b. Start the server:

    npm start
    
  6. Open a browser and enter http://localhost:3000 to verify that the node server is running. You should see the following: PaymentFormLocatHost3000V3

Now you are ready to build a web page that embeds SqPaymentForm.

Step 1: Generate a secure single-use payment token Permalink Get a link to this section

In this step:

  • Build a web page with SqPaymentForm embedded in it.

  • Test the page by submitting card information and verifying that you get a payment token.

1.1: Embed SqPaymentForm in a static web page Permalink Get a link to this section

Add the following components to the index.html page:

  • Required CSS and JavaScript references.

  • A <div/> with credit card fields.

  • A <script/>, which manages the SqPaymentForm object and user interaction using a JavaScript initializing block and <div/> tags in the form.

1.1.1: Add script references Permalink Get a link to this section

Open index.html and add the following references in the <head/> section.

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

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

Note the following about these references:

  • js.squareupsandbox.com/v2/paymentform is the Square JavaScript library used in testing the payment form in the Sandbox.

  • mysqpaymentform.css is the file provided as part of the project you downloaded.

Important

The SqPaymentForm library can only be hosted in a Square server (squareup.com or squareupsandbox.com). An application that loads the library from any other domain is disabled without notification.

1.1.2: Add an HTML div Permalink Get a link to this section

Add the following HTML <div/> in the <body/> section of the same index.html.

   <div id="form-container">
     <div id="sq-card-number"></div>
     <div class="third" id="sq-expiration-date"></div>
     <div class="third" id="sq-cvv"></div>
     <div class="third" id="sq-postal-code"></div>
     <button id="sq-creditcard" class="button-credit-card" onclick="onGetCardNonce(event)">Pay $1.00</button>
   </div> <!-- end #form-container --> 
   <!-- TODO: Add script from step 1.1.3 -->

In the form, note the following:

  • Each credit card field is an empty <div/> with an ID. SqPaymentForm replaces each <div/> with an input element that runs securely on the Square domain. This allows the form to take credit card input while keeping your code outside of PCI scope.

  • The onclick event handler (onGetCardNonce) calls the SqPaymentForm.requestCardNonce library function to get a payment token.

1.1.3: Add JavaScript to index.html Permalink Get a link to this section

In this section, add code to the HTML page to configure and initialize the SqPaymentForm object. <script/> is added in the <body/> because SqPaymentForm can only be initialized after the DOM is fully loaded.

Copy and paste the following code into index.html after <!-- TODO: Add script from step 1.1.3 -->:

   <script type="text/javascript">

     //TODO: paste code from step 2.1.1

     // Create and initialize a payment form object
     const paymentForm = new SqPaymentForm({
       // Initialize the payment form elements

       //TODO: Replace with your sandbox application ID
       applicationId: "REPLACE_WITH_APPLICATION_ID",
       inputClass: 'sq-input',
       autoBuild: false,
       // Customize the CSS for SqPaymentForm iframe elements
       inputStyles: [{
           fontSize: '16px',
           lineHeight: '24px',
           padding: '16px',
           placeholderColor: '#a0a0a0',
           backgroundColor: 'transparent',
       }],
       // Initialize the credit card placeholders
       cardNumber: {
           elementId: 'sq-card-number',
           placeholder: 'Card Number'
       },
       cvv: {
           elementId: 'sq-cvv',
           placeholder: 'CVV'
       },
       expirationDate: {
           elementId: 'sq-expiration-date',
           placeholder: 'MM/YY'
       },
       postalCode: {
           elementId: 'sq-postal-code',
           placeholder: 'Postal'
       },
       // SqPaymentForm callback functions
       callbacks: {
           /*
           * callback function: cardNonceResponseReceived
           * Triggered when: SqPaymentForm completes a card payment token request
           */
           cardNonceResponseReceived: function (errors, nonce, cardData, billingContact, shippingContact, shippingOption) {
           if (errors) {
               // Log errors from payment token generation to the browser developer console.
               console.error('Encountered errors:');
               errors.forEach(function (error) {
                   console.error('  ' + error.message);
               });
               alert('Encountered errors, check browser developer console for more details');
                return;
           }
           //TODO: Replace alert with code in step 2.1
           alert(`The generated payment token is:\n${nonce}`);
        }
      }
    });
    //TODO: paste code from step 1.1.4
   </script>

In the JavaScript code, the callback cardNonceResponseReceived alerts the user that a payment token is generated and returned by the SqPaymentForm object. In step 2.1, the payment token is POSTed to a server-side component to charge the payment source. The server-side component is reviewed in step 2.

1.1.4: Add JavaScript to handle "Pay $1.00" button click event “onclick” Permalink Get a link to this section

In this section, add a callback function to handle the pay button click event. The event handler calls requestCardNonce to get the payment card token from the SqPaymentForm object.

Copy and paste the following code into index.html after //TODO: paste code from step 1.1.4:

//TODO: paste code from step 1.1.5
// onGetCardNonce is triggered when the "Pay $1.00" button is clicked
function onGetCardNonce(event) {

  // Don't submit the form until SqPaymentForm returns with a payment token
  event.preventDefault();
  // Request a payment token from the SqPaymentForm object
  paymentForm.requestCardNonce();
}

1.1.5: Add JavaScript to build the form Permalink Get a link to this section

In this section, add JavaScript to force the SqPaymentForm object to render the payment form on the page.

Copy and paste the following code after //TODO: paste code from step 1.1.5:

paymentForm.build();

//TODO: paste code from step 2.1.2

1.2: Provide your application ID Permalink Get a link to this section

For SqPaymentForm to load successfully, open index.html and find //TODO: Replace with your Sandbox application ID.

Replace REPLACE_WITH_APPLICATION_ID with your Sandbox application ID. SqPaymentForm requires a valid application ID to return a payment token.

// TODO: Replace with your sandbox application ID
applicationId: "REPLACE_WITH_APPLICATION_ID";

1.3: Test the payment form and verify the secure token Permalink Get a link to this section

Complete the following steps to test the payment form:

  1. Save all files.

  2. Start the npm server, if it is not running:

    npm start
    
  3. Open a browser, and then open the payment form on localhost by entering http://localhost:3000 in the address bar.

  4. Fill the form with the following Sandbox test credit card from the test values set, and then choose Pay $1.00.

    • Card Number: 4111 1111 1111 1111

    • MM/YY: 12/21 (you can provide any month and year in the future)

    • CVV: 111

    • Postal: 11111 (you can provide any postal code)

    This is one of the test cards that Square provides for use in the Sandbox environment.

  5. Verify that you get a payment token as shown in the following example:

PaymentFormTestNonceRcvdv2

Application flow summary Permalink Get a link to this section

In this section, you do not perform actions. The section explains how the code you developed in step 1 works. You can read or skip ahead to step 2 to charge the payment source.

When the page loads, it renders the payment form defined in index.html. The page also downloads and executes the SqPaymentForm JavaScript library. This is a library that provides the SqPaymentForm object. For more information about the library, see SqPaymentForm object model.

The embedded JavaScript code does the following:

  • Initializes the SqPaymentForm with configuration fields and callback functions.

    Each credit card input form field requires a corresponding configuration field. For example, the SqPaymentForm initialization defines the card number input as shown in this inputTarget field.

     cardNumber: {
       elementId: 'sq-card-number',
       placeholder: 'Card Number'
     }
    

    It maps the SqPaymentForm.cardNumber configuration field to corresponding form field sq-card-number. The SqPaymentForm initialization also includes callback implementations; for example, the SqPaymentForm.cardNonceResponseReceived. The callback executes after SqPaymentForm completes a request for a payment token.

  • Provides code for the event handler onGetCardNonce that executes when you choose Pay $1.00.

After the payment form is built, it replaces DOM elements with iframes. The iframes take the buyer-entered credit card information and call the requestCardNonce function to get a payment token. This allows you to take payments through Square.

When a buyer enters information in the form and chooses Pay $1.00, the onGetCardNonce event handler executes. This code generates a payment token by calling the SqPaymentForm.requestCardNonce function and passes the payment token back to the client by calling the SqPaymentForm.cardNonceResponseReceived callback. The client displays an alert box with the generated payment token.

Step 2: Charge the payment source using the payment token Permalink Get a link to this section

The index.html file sends the payment token to server.js by using the fetch API. Server.js uses it to create a payment. This server-side component uses the Square Node.js SDK library to call the Square Payments API to charge the payment source using the payment token. In step 2, you add the fetch code to index.html and update server.js with your access token.

2.1: Add JavaScript to send the payment token to the backend Permalink Get a link to this section

In this section, you make a final change to index.html. Replace the alert that notifies on the payment token received with code that actually sends the payment token to server.js.

  1. In index.html, replace //TODO: paste code from step 2.1.1 with the following code that generates an idempotency key when the payment form page is loaded. This client-generated key prevents the same payment from being created multiple times.

    const idempotency_key = uuidv4();
    
  2. In index.html, replace //TODO: paste code from step 2.1.2 with the following code that generates an idempotency key in the UUID format.

    //Generate a random UUID as an idempotency key for the payment request
    // length of idempotency_key should be less than 45
    function uuidv4() {
       return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
         var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
         return v.toString(16);
       });
    }
    
    

    Note

    The uuidv4 helper function generates a UUID, which should be less than 45 characters in length. The return value of the function is POSTed to the backend along with the payment token and is used as the idempotency key of the CreatePayment request. As long as the UUID is not regenerated, the payment form cannot send a duplicate payment processing request.

  3. In index.html, find //TODO: Replace alert with code in step 2.1 in the code you added in step 1.1.3, and replace the alert with the following code.

  4. Replace REPLACE_WITH_LOCATION_ID with a location ID from the Developer Dashboard for your application.

    fetch('process-payment', {
      method: 'POST',
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        nonce: nonce,
        idempotency_key: idempotency_key,
        location_id: "REPLACE_WITH_LOCATION_ID"
      })   
    })
    .catch(err => {
      alert('Network error: ' + err);
    })
    .then(response => {
      if (!response.ok) {
        return response.json().then(
          errorInfo => Promise.reject(errorInfo));
      }
      return response.json();
    })
    .then(data => {
      console.log(data);
      alert('Payment complete successfully!\nCheck browser developer console for more details');
    })
    .catch(err => {
      console.error(err);
      alert('Payment failed to complete!\nCheck browser developer console for more details');
    });
    

2.2: Configure the backend with your access token Permalink Get a link to this section

The JavaScript code in server.js is already complete, but it is not set with your Sandbox access token. In this step, replace the placeholder with your token.

  1. Open server.js.

  2. Update the file by providing your sandbox access token.

    accessToken = 'REPLACE_WITH_ACCESS_TOKEN';
    
  3. Review the following code fragments:

    • Create a PaymentsApi object and call the CreatePayment endpoint to charge the payment source.

      app.post('/process-payment', async (req, res) => {
        const requestParams = req.body;
      
        // Charge the customer's card
        const paymentsApi = client.paymentsApi;
        const requestBody = {
          sourceId: requestParams.nonce,
          amountMoney: {
            amount: 100, // $1.00 charge
            currency: 'USD'
          },
          locationId: requestParams.location_id,
          idempotencyKey: requestParams.idempotency_key,
        };
      
        try {
          const response = await paymentsApi.createPayment(requestBody);
          res.status(200).json({
            'title': 'Payment Successful',
            'result': response.result
          });
        } catch(error) {
          let errorResult = null;
          if (error instanceof ApiError) {
            errorResult = error.errors;
          } else {
            errorResult = error;
          }
          res.status(500).json({
            'title': 'Payment Failure',
            'result': errorResult
          });
        }
      });
      
    • Note that the requestBody specifies the payment token value and the amount to charge.

        const requestBody = {
          sourceId: requestParams.nonce,
          amountMoney: {
            amount: 100, // $1.00 charge
            currency: 'USD'
          },
          locationId: requestParams.location_id,
          idempotencyKey: requestParams.idempotency_key,
        };
      

2.3: Test the payment flow from client to server Permalink Get a link to this section

This time you generate a payment token and charge the payment source using the generated payment token.

  1. Open a browser and enter http://localhost:3000.

  2. Provide the card information:

    • Card Number: 4111 1111 1111 1111

    • MM/YY: 12/21 (you can provide any month and year in the future)

    • CVV: 111

    • Postal: 11111 (you can provide any postal code)

  3. Choose Pay $1.00. After receiving the Payments.CreatePayment endpoint request, Square processes the payment and returns a response. A sample response fragment is shown:

        {
         "title":"Payment Successful",
         "result":{
             "payment": {
                 "id": "YNvVT...",
                 "created_at": "2018-10-17T20:33:59.603Z",
                 "updated_at": "2018-10-17T20:34:00.012Z",
                 "amount_money": {
                   "amount": 100,
                   "currency": "USD"
                 },
                 "status": "COMPLETED",
                 "source_type": "CARD",
                 "card_details": {
                   "status": "CAPTURED",
                   "card": {
                       "card_brand": "VISA",
                       "last_4": "1111",
                       "exp_month": 12,
                       "exp_year": 2021,
                       "fingerprint": "sq-1-9PP0tWf..."
                   },
                   "entry_method": "KEYED",
                   "cvv_status": "CVV_ACCEPTED",
                   "avs_status": "AVS_ACCEPTED",
                   "auth_result_code": "VVp3sH"
                 },
                 "reference_id": "123456"
             }
         }
        }
    
  1. Review the payment in the Sandbox Seller Dashboard. The payment is credited to the Sandbox test account whose access token is used in the application that you just built. To see the payment in the Sandbox Seller Dashboard, go to the Developer Dashboard.

    1. Choose Open on the default test account to access the Sandbox Seller Dashboard. image-launch sandbox-02@2x

    2. Choose Transactions.

      image-payment form sandbox-03@2x

Deploy the application to production Permalink Get a link to this section

In this walkthrough, you used the Sandbox environment to test the payment form using a fake credit card number. This section explains how you deploy the application in production by doing the following:

  • Replace the Sandbox access token and application ID with a production access token and application ID.

  • Update your code to send requests to Square production endpoints.

  • Take payments with a valid credit card. In production, Square actually charges the card.

To deploy the preceding walkthrough in production, do the following:

  1. Get production application credentials.

    In the Get Sandbox application credentials section, you obtained Sandbox credentials. Follow the steps to open the Developer Dashboard, but this time choose Production mode, and then copy the production application ID and access token.

    Note

    This walkthrough assumes that your account is activated to accept payments. If not, you need to activate the account. If the Credentials tab in the Developer Dashboard indicates that account activation is required, follow the steps to activate the account. After activation, you can start taking payments.

  2. Update script references.

    In the ADD SCRIPT REFERENCES section, you added script references in index.html. Update the domain string in the JavaScript reference from js.squareupsandbox.com to js.squareup.com.

  3. Provide your production application ID.

    SqPaymentForm requires a valid application ID to return a payment token. In the Provide your application ID section, you provided a Sandbox application ID. Update the code by providing your production application ID.

  4. Configure your backend server to use a production access token.

    In the Configure the backend with your access token section, you provided a Sandbox access token. Replace it with the production access token.

When you have completed these steps, your application is ready to run in production.

If you want to test the application in a production environment (squareup.com), you must use an actual payment card. Note that Square actually charges payment cards in production so if you must test in production, charge minimum amounts.

Shopping cart example Permalink Get a link to this section

The previous sections show you the client and server code to integrate the payment form. These isolated examples are best understood when seen in the context of a real-world shopping cart example.

Note that the example code for the payment form client in this topic does not send the amount to charge along with the payment token, idempotency key, and location ID. This is because payment amounts should always be provided by the business logic that your application runs on the backend.

For a shopping cart example that uses the payment form, see Order-Ahead Sample Application. This quick start sample builds a shopping cart with the Catalog API, creates an order with the Orders API, and collects a payment card with the payment form.