Take a Card Payment with the Web Payments SDK

Use the Web Payments SDK Quickstart sample project to set up a web application that is integrated with the Square Web Payments SDK for taking payments.

The following video demonstrates how to build an end-to-end payment flow with the credit card payment method, and shows the code you use to build the flow. For an optimal viewing experience, expand the video window to a desired size or watch the video on YouTube. For a detailed overview of building with the card payment method, see the following sections in this topic.

Link to section

Overview

To accept a card payment from a buyer, you need a web client where the buyer enters payment card information and a backend that takes a payment with the card. The SDK produces a secure one-time-use payment token based on the card. Your web client sends the payment token to your backend where the payment is taken. In summary, a payment is taken with these steps:

  1. Generate a payment token - Use the Web Payments SDK client library to render a card entry form and generate a payment token that your web client sends to your backend server.
  2. Create a payment with the token - On your backend, use the Square Payments API to create a payment.

This topic shows you where to add HTML and JavaScript to your web client to integrate the Web Payments SDK and take a payment on your backend.

You can find a full example of the Card payment code in GitHub.

Important

If you're not familiar with building an application using Square's client-side SDKs, Square recommends completing this guide using the GitHub project before you attempt to integrate the Web Payments SDK into your application.

The following shows the card payment method rendered in a web page:

A graphic showing the Web Payments SDK card payment method rendered on a web page.

The payment method doesn't initially render input fields for the name or the billing address. When you initially set up the payment method, you don't need to include input fields for contact information (name and billing information). You only need to first set up payment processing with fields for the credit card number, expiration date, the CVV (card verification value), and if required for your region, a zip or postal code.

The form automatically recognizes the credit card type as soon as you enter the credit card number, and the form updates the credit card icon as a result to reflect the type being used.

To request the buyer to provide contact information and other additional information for the payment, you can add additional payment form fields to the page layout.

Link to section

Clone the quickstart project template

Start by cloning the quickstart project template into a folder on your computer.

Test the application

The project template isn't initially integrated with the SDK and doesn't render the card payment form.

  1. Follow the GitHub repo README instructions to get the development server running.

  2. Open a browser to http://localhost:3000 to verify that the server is running.

    Your web page looks like the following page:

    A graphic showing the default Quickstart web page that confirms that the sample is running.

Success

If your web page renders as shown in the previous image, you're ready to write the code that adds the Card payment method to the page.

The walkthrough asks you to update the code in these project files:

  • The public/index.html file is an empty static HTML page where you add the Web Payments SDK and application logic.

  • The public/app.css file is the stylesheet that contains some preset styles to help with the page layout.

  • The top-level server.js file contains the server call to the CreatePayment endpoint for charging the payment source. The quickstart application must include server.js to make the server call; otherwise, the application cannot create a payment. The quickstart project also includes tests in the server.tests.js file.

    Important

    • The value in server.js line 45 sets the currency for the quickstart to US dollars. If your default test account is based in another country, be sure to update server.js with the currency code for your country before you run the quickstart.
    • If you're using a non-US account, you must change the currency to match the country in which you're accepting the payment.
Link to section

Add the Web Payments SDK to the web client

Get the web client ready to accept a payment card and send the resulting token to the server component of the quickstart application.

Link to section

Step 1: Get application credentials

You need your Sandbox credentials because the quickstart application is configured to send requests to the Square Sandbox instead of your production Square account.

  1. Open the Developer Dashboard and click the plus symbol under Applications to create a new application.
  2. Open the application and choose the Credentials page.
  3. Set the Developer Dashboard mode to Sandbox to get a Sandbox application ID.
  4. Copy the Sandbox Application ID and Sandbox Access Token.
  5. Choose the Locations page and copy the Sandbox location ID.
  6. Paste the application ID, location ID, and Sandbox access token into a temporary text file.

Important

The Sandbox access token is a secure secret. Don't share it with anyone or upload it to the cloud.

An animation showing the process for getting application credentials in the Developer Dashboard.

Link to section

Step 2: Configure the quickstart access token

The quickstart server code calls the CreatePayment endpoint and needs to be updated to use your Sandbox access token.

  1. In the project root folder, create a copy of the .env.example file and name it .env.sandbox.

    The dotenv library is used to manage secrets that shouldn't be made public. The .env.sandbox file should never be committed.

  2. Open the copied file to edit.

  3. Define SQUARE_ACCESS_TOKEN with your Sandbox access token from the Developer Dashboard.

    SQUARE_ACCESS_TOKEN={SANDBOX_ACCESS_TOKEN}
  4. Restart your server for the Sandbox test environment (npm run dev) to use this new value.

You need a Sandbox application ID and Sandbox location ID in the following steps. You should paste these values into a text file or leave the Developer Dashboard open in another browser tab so that you can copy the values as needed.

Link to section

Step 3: Add pay elements to the page

  1. Replace the body of public/index.html with this HTML:

    <form id="payment-form"> <div id="card-container"></div> <button id="card-button" type="button">Pay $1.00</button> </form> <div id="payment-status-container"></div>

    This HTML adds an element (div id="card-container") that the Web Payments SDK attaches the card element to and adds a button that starts the tokenization process.

    Did you know?

    The SDK also enables the Apple Pay, Google Pay, ACH (bank transfer), Square gift card, and Cash App Pay payment methods.

Link to section

Step 4: Attach the Card payment method to the pay elements

The following JavaScript instantiates the SDK, provides the Card payment object, attaches it to the page, and generates the payment token:

  1. Add an empty <script> tag to the <head> of index.html after <script type="text/javascript" src="https://sandbox.web.squarecdn.com/v1/square.js"></script>.

    <script> </script>
  2. Add the following global constants inside the <script> tag, substituting the IDs from the Developer Dashboard for the placeholder ({YOUR_SANDBOX_APPLICATION_ID} and {YOUR_SANDBOX_LOCATION_ID}) values:

    const appId = '{YOUR_SANDBOX_APPLICATION_ID}'; const locationId = '{YOUR_SANDBOX_LOCATION_ID}';
  3. Add the following code inside the <script> tag:

The code does the following:

  1. Initializes the Web Payments SDK by calling Square.payments(appId, locationId).
  2. Initializes the Card payment method by calling the Payments .card() method and attaching the payment method to the page DOM by calling the Card .attach() method.

Note

The Card payment method of the Web Payments SDK automatically infers whether to display the ZIP code, postal code, or postcode based on the issuing country of the buyer's credit card. Depending on the card that's used, the SDK automatically removes the postal code if the card's issuing country doesn't require the postal code for the payment.

Test the application

  1. Navigate to http://localhost:3000/ in your browser.

    A graphic showing the Quickstart web page after all walkthrough steps are completed and a Pay $1.00 button.

Success

You should now be able to see the payment card input rendered on your page.

If you need to clear the contents of the card entry fields for the buyer, call card.destroy() to destroy the object and then call the initializeCard(payments) function again to initialize and attach the card to your application DOM.

Link to section

Step 5: Get the payment token from the Card payment method

Before you can take a payment, you need to configure your developer credentials, which can be found in the Developer Dashboard.

This example uses the Square Sandbox to accept a payment. You should use the Card-present success state values. However, if you choose to use your own payment card, the Sandbox doesn't charge it.

  1. Add the following code after the initializeCard function inside the <script> tag:

  2. Add the following code to the DOMContentLoaded event listener in step 4.3 by replacing // Step 5.2: create card payment with the following code:

Link to section

Complete example

The complete DOMContentLoaded Event Listener should look like the following code:

The code does the following:

  1. Binds the Card tokenization to the trigger event, which is clicking the Pay button in this case.
  2. Submits the tokenized card information and payment token by calling the CreatePayment endpoint on the backend.
Link to section

Test the application

  1. Navigate to http://localhost:3000/ in your browser.

  2. Input the card number 5105 1051 0510 5100 from the Card-present success state values. Any CVV or postal code works.

  3. Choose the Pay $1.00 button.

    An animation showing the behavior of the card entry payment method for the Web Payments SDK as credit card information is being added and the Pay $1.00 button is being selected.

You should see a green check mark and Payment successful on the page. The payment is credited to your developer test account. The next section shows how to find the payment in the Sandbox Seller Dashboard.

Look at your Developer Dashboard for a debug log of the payment information.

Did you know?

You can use any value from the Test Square APIs in the Sandbox provided by Square.

Link to section

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

  2. Choose Transactions.

    An animation showing how to open the Seller Dashboard and view a transaction from the Developer Dashboard.

Link to section

Add Strong Customer Authentication

To add security to the payment method, add the Strong Customer Authentication (SCA) security protocol layer to the application, and verify the identity of the payment card holder by using the verifyBuyer function.

Important

Your application should always attempt to create a payment with a verification token when a token is returned. It should also be prepared to respond to a payment failure in a small number of cases where a payment is rejected despite receiving a buyer verification token.

  1. Update the storeCard function to take the verificationToken parameter.

  2. Define the verifyBuyer function with billing contact details after the displayResults function.

    Your production application should collect the billing address of the buyer. Although providing an empty billingContact is acceptable, by providing as much billing contact information as possible, you increase the chances of a successful authentication. This example uses an object that is declared with a hard-coded billing address. Your application might collect a billing address at payment time or, if the buyer is a customer on the seller Square account, from the buyer's customer record.

    Note

    The Web Payments SDK produces a payment token that can be used to make a payment with the presented card or to store the card on file. These operations are represented by two intents: CHARGE to make a payment and STORE to store the card.

    The code in the following steps adds the billing contact values needed by SCA (with the payments.verifyBuyer function) to verify the authenticity of the card holder.

    The verifyBuyer function creates a StoreVerifyBuyerDetails object that verifies a card to be stored on file and provides the buyer and purchase details needed by 3DS.

  3. Add the verifyBuyer function to the handleStoreCardMethodSubmission function and update the storeCard method call to include verificationToken.

  4. Test the application.

    1. Navigate to http://localhost:3000/ in your browser.

    2. Use one of the test cards in the following table with a challenge type of “Modal with Verification Code":

      BrandNumberCVVChallenge typeVerification code
      Visa4800 0000 0000 0004111No ChallengeN/A
      Mastercard5222 2200 0000 0005111No ChallengeN/A
      Discover EU6011 0000 0020 1016111No Challenge123456
      Visa EU4310 0000 0020 1019111Modal with
      Verification Code
      123456
      Mastercard5248 4800 0021 0026111Modal with
      Verification Code
      123456
      Mastercard EU5500 0000 0020 1016111Modal with
      Verification Code
      123456
      American Express EU3700 000002 010141111Modal with
      Verification Code
      123456
      Visa4811 1100 0000 0008111No Challenge with
      Failed Verification
      N/A

    After you submit, you see the following window where you enter the verification code:

    A graphic showing the SCA cardholder authentication window that appears when the verifyBuyer function is called.

  5. Verify that the application passed in the verification token with a successful response. Check the application's API log again in your developer account.

Note

You can see a complete code example in the Web Payments Quickstart in GitHub.

Link to section

Deploy the application

This section explains how to deploy your application in production with the following tasks:

  • Replace your Sandbox access token and application ID with production values.
  • Update your code to make API calls to Square production endpoints.

Important

  • Your account must be activated to accept payments. Be sure to activate your account before continuing this walkthrough. If the Developer Dashboard Credentials page indicates that your account isn't activated, follow the steps to activate it.

Deployment tasks include 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 copy the production application ID and access token.
  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 sandbox.web.squarecdn.com/v1/square.js to web.squarecdn.com/v1/square.js.
  3. Provide your production application ID - The Web Payments SDK 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 quickstart access token" section, you provided a Sandbox access token in the env.sandbox file. Replace it with the production access token.

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. Therefore, if you must test in production, charge minimum amounts.

Did you know?

For future application Sandbox tests or application deployments:

  • If you have a Sandbox access token, use the sandbox.web.squarecdn.com/v1/square.js Sandbox URL for Sandbox tests.
  • If you have a production access token, use the web.squarecdn.com/v1/square.js production URL for deployments.

After you declare the access token and URL, the Web Payments SDK initializes the square.js script each time you run the application. As a result, Square takes care of the payment processing tasks according to the access token and URL you specified.

Link to section

Next steps

Now that you're taking payments with credit and debit cards, you can add additional payment methods or customize the appearance of the Card payment method.

With card information and SCA, you can also save and charge card information on file with additional code for your application. For more information, see:

The Web Payments SDK technical reference also provides a complete reference about supported payment methods, objects, enums, errors, and code examples.