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

Render a Gift Card Form

Warning

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

Prerequisites and assumptions Permalink Get a link to this section

To build with a Square payment form for Gift Cards, the following must be true:

  • You have a Square account enabled for payment processing. If you have not enabled payment processing on your account (or you are not sure), visit squareup.com/activate.

  • You are using HTTPS. HTTPS is required for all production Square API calls. HTTP calls are only supported for developing and testing on localhost.

  • You are using the Square-hosted version of the SqPaymentForm library. Applications referencing a copy hosted from a non-Square server are disabled without notice.

Additionally, this guide makes the following assumption:

  • Your backend supports a checkout experience, maintains a checkout payment balance, and can provide an order or reference ID.

Before you start Permalink Get a link to this section

To prepare for the steps in this guide, complete the following:

  • Get your application credentials from the Square Developer Dashboard. Use the sandbox environment for testing because the Square Sandbox provides support for gift card test values .

    1. Open the Developer Dashboard, and then choose the application you are testing.

    2. Change the Sandbox setting from Production to Sandbox to put your application into sandbox mode.

    3. Copy the personal access token.

What you build Permalink Get a link to this section

You update an HTML page to render a Gift Card form that lets a buyer submit a Square Gift Card to pay for the items in the checkout page. This guide assumes that the checkout page has created an Order or its equivalent to represent the purchase. The HTML page submits a Gift Card nonce, waits for a response from the server, and alerts the buyer when an additional payment is needed.

To enable a payment page to accept Square Gift Cards, follow these steps:

  1. Add <div> tags to your checkout page where you want the Gift Card form to appear.

  2. Initialize an instance of SqPaymentForm with Gift Card configuration field values.

  3. Add a button to your checkout page for the Gift Card form to submit a request on a SqPaymentForm object to get a nonce.

  4. Add POST request code to send the payment nonce to your backend where it is processed as a payment.

Important

If you are adding Gift Cards to a payment page that already uses an instance of SqPaymentForm for credit and debit cards, you must initialize a second SqPaymentForm object to manage the Gift Card form.

You can initialize the Gift Card form with the same style class name that you are using for the credit card payment form.

Step 1: Add the SqPaymentForm library and CSS references Permalink Get a link to this section

To add the Square Sandbox SqPaymentForm library to your page, add the following <script> and <link> to your checkout page:

  <head>
    
    <!-- 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">
    
  </head>

You can get an example of mysqpaymentform.css from the Square Payment Form Node.js starter kit sample on GitHub.

Important

Square Gift Cards are not currently supported in the Sandbox (beta). If you set the payment form library source to https://js.squareupsandbox.com/v2/paymentform, nonces generated using production Square Gift Cards are rejected by the Payments API in the Sandbox testing environment.

Step 2: Add div tags Permalink Get a link to this section

Add the label, <div> tag, and button to your checkout page <body> where you want SqPaymentForm to replace it with the Gift Card entry form:

<body>
  <label>Gift Card</label>
  <div id="gift-card">
    <div id="sq-gift-card"></div>
  </div>
  <button class="button-credit-card" onclick="submitGiftCardClick(event)">Submit</button>

  <div id="success" style="display: none;">
    <p>Submitted payment!</p>
  </div>
  <!-- Todo: Add <script> in Step 3 -->
</body>  

Step 3: Initialize the Gift Card payment form Permalink Get a link to this section

Copy the following code into your project checkout HTML page and replace <!-- Todo: Add <script> in Step 3 -->:

  <script type="text/javascript">
      const orderID = "CHECKOUT_ORDER_ID";
      const giftCardForm = createGiftCardForm();
      giftCardForm.build();

      function createGiftCardForm() {
        //Initialize the payment form for gift cards
        return new SqPaymentForm({
          applicationId: "REPLACE_WITH_APPLICATION_ID",
          inputClass: 'sq-input',

          giftCard: {
            elementId: 'sq-gift-card',
            placeholder: "* * * *  * * * *  * * * *  * * * *"
          },

          inputStyles: [
            {
              color: "black"
            },
            {
              mediaMaxWidth: "600px",
              fontSize: "26px"
            },
            {
              mediaMinWidth: "601px",
              fontSize: "26px"
            }
          ],

          callbacks: {
            cardNonceResponseReceived: function(errors, nonce, paymentData, contacts) {
              if (errors) {
            //   Log errors from nonce generation to the browser developer console.
                console.error('Encountered errors on gift card nonce received:');
                errors.forEach(function (error) {
                  console.error('  ' + error.message);
                });
                alert('Encountered errors, check console for more details');
                return;
              } else {
                postData(nonce, orderID ).then( function(response) {
                  if (response.status !== undefined && response.status === "'FAILED`") {
                    alert('Card denied:' + response.errors[0].code);
                    return;
                  }
                  //If there is a balance remaining on the purchase, collect a
                  // credit or debit card and pass the ID of the Order so that the
                  //payment card nonce is posted in the context of the order
                  if ( response.balance !== undefined && response.balance > 0) {
                    //Notify buyer of remaining balance and ask for another card.
                    alert('Gift card authorized. Additional payment of '
                    + response.balance  + 'needed.');
                  } else if (response.balance !== undefined && response.balance == 0) {
                    alert('Payment completed.')
                    // Display results of the call.
                    let successDiv = document.getElementById('success');
                    successDiv.style.display = 'block';
                  }
                }).catch( function(error) {
                  console.error('postData Exception' + error.message);
                  alert('Encountered errors, check browser developer console for more details');
                });
              }
            }
          }
        });
      }
//Todo: Copy code from Step 4
//Todo: Copy code from Step 5
</script>

Step 4: Request the Gift Card nonce Permalink Get a link to this section

Copy the following code into index.html and replace //Todo: Copy code from Step 4 to generate a payment nonce from the Gift Card entered by the buyer. This is an asynchronous operation whose result is returned in the cardNonceResponseReceived callback that you added in the previous step.

      function submitGiftCardClick(event) {
        event.preventDefault();
        giftCardForm.requestCardNonce();
      }

Step 5: POST the nonce to your backend Permalink Get a link to this section

Copy the following code into index.html and replace //Todo: Copy code from Step 5 to POST the Gift Card nonce to your backend and wait for results:


       //POST the Gift Card nonce to a backend service to be processed as a payment
      function postData(nonce, order_id) {
        if (nonce === 'undefined' ) {
          throw new TypeError('`nonce` is required');
        }
        if (order_id === 'undefined') {
          throw new TypeError('`order_id` is required');
        }

        let payment = {
          "nonce": nonce,
          "orderID" : order_id
        };

        return fetch("process-giftcard", {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          redirect: 'follow',
          referrer: 'no-referrer',
          body: JSON.stringify(payment),
        }).then(
          response => response.json()
        );
      }

Did you know?

If your application server payment endpoint must be stateless, your payment page should get the checkout order ID and send it with the payment nonce. This lets your server associate the nonce with the order backing the checkout. If additional payments are needed, the order ID can be used to associate the payments with the same order.

Your backend process must be able to take payments with Gift Cards using the Gift Card nonce and should respond to your checkout page with any outstanding purchase balance.