Take Payments

Point of Sale API Mobile Web Setup

Open the Square Point of Sale app from a custom mobile web application to process in-person payments using Square hardware.

Assumptions

This guide makes the following assumptions:

  • You have read the Point of Sale API Overview, which covers general functionality of the API.
  • You are familiar with HTML and Javascript.
  • You can create and run websites on localhost or a development server.
  • You are familiar with HTTP and JSON. If you are new to JSON, we recommend reading the JSON Getting Started Guide on Codular before continuing.

The example code in this guide assumes the following:

Step 1: Install the Square Point of Sale app

Install the latest version of the Square Point of Sale app from the Google Play Store (Android) or the App Store (iOS).

Step 2: Configure your web callback URL

You need to go into Application Dashboard and set the callback URL in the application control panel. Your callback URL is where the Point of Sale API sends notifications and payment information.

For example:

https://your-web-app.com/path/to/your/callback/

Note that/path/to/your/callback should be the path to the code that will process notifications and transaction information received from the Square Point of Sale app.

To register your callback URL:

  1. Go to the Point of Sale API tab of your application's settings in the Application Dashboard.
  2. In the Web section enter your Web Callback URL.
  3. Click "Save".

Step 3: Add code to initiate a transaction from your mobile web app

Mobile web transactions are initiated by clicking on a link to the to the Square Point of Sale app. Since the request URL includes details about the transaction, we recommend building the URL dynamically instead of hardcoding it. The link URL includes the transaction information as parameters and is formatted differently for Android and iOS applications.

Initiate a mobile web transaction: Android

Square Point of Sale app request URLs on Android are formatted as intent requests. For example:

<a href="intent:#Intent;
    action=com.squareup.pos.action.CHARGE;
    package=com.squareup;
    S.browser_fallback_url=https://my.website.com/index.html;
    S.com.squareup.pos.WEB_CALLBACK_URI=https://my.website.com/index.html;
    S.com.squareup.pos.CLIENT_ID=sq0ids-yourClientId;
    S.com.squareup.pos.API_VERSION=v2.0;
    i.com.squareup.pos.TOTAL_AMOUNT=100;
    S.com.squareup.pos.CURRENCY_CODE=USD;
    S.com.squareup.pos.TENDER_TYPES=com.squareup.pos.TENDER_CARD,com.squareup.pos.TENDER_CASH;
    end">Start Transaction</a>

Android requires URLs to be wrapped with Android start and end tokens when they contain key-value pairs delimited with semicolons. The Android start and end tokens are: intent:#Intent; and end.

To build your request URL:

  1. Create a Javascript file called open_pos.js.

  2. Add code to define some useful constants, configure your mobile web app, and set the transaction total.

// The URL where the Point of Sale app will send the transaction results.
var callbackUrl = "{YOUR CALLBACK URL}";

// Your application ID
var applicationId = "{YOUR APPLICATION ID}";

// The total and currency code should come from your transaction flow.
// For now, we are hardcoding them.
var transactionTotal = "{TRANSACTION TOTAL}";
var currencyCode = "USD";

// The version of the Point of Sale SDK that you are using.
Var sdkVersion = "v2.0";
  1. Add code to build the request URL. See the Mobile Web Technical Reference for a detailed list of all possible URL parameters.
function openURL(){
  // Configure the allowable tender types
  var tenderTypes =
   "com.squareup.pos.TENDER_CARD,
    com.squareup.pos.TENDER_CARD_ON_FILE,  
    com.squareup.pos.TENDER_CASH,  
    com.squareup.pos.TENDER_OTHER";

  var posUrl =
    "intent:#Intent;" +
    "action=com.squareup.pos.action.CHARGE;" +
    "package=com.squareup;" +
    "S.com.squareup.pos.WEB_CALLBACK_URI=" + callbackUrl + ";" +
    "S.com.squareup.pos.CLIENT_ID=" + applicationId + ";" +
    "S.com.squareup.pos.API_VERSION=" + sdkVersion + ";" +
    "i.com.squareup.pos.TOTAL_AMOUNT=" + transactionTotal + ";" +
    "S.com.squareup.pos.CURRENCY_CODE=" + currencyCode + ";" +
    "S.com.squareup.pos.TENDER_TYPES=" + tenderTypes + ";" +
    "end";

  window.open(posUrl);
}

  1. Add this script tag to your HTML head to load your open_pos.js file.
<head>
  <!-- Loads callback javascript -->
  <script type="text/javascript" src="/open_pos.js"></script>
</head>
  1. Add a button to your mobile web application that runs open-POS.js.
<button onclick="open_pos.js">
Start Transaction
</button>

Initiate a mobile web transaction: iOS

To initiate a Square Point of Sale transaction from your website, call the Square Point of Sale app with a URL using the following format:

square-commerce-v1://payment/create?data={REPLACE ME}
  1. Add code to create a percent-encoded JSON object that contains the information Square Point of Sale needs to process the transaction request.
<script>
  var dataParameter = {
    amount_money: {
      amount:        "500",
      currency_code: "USD"
    },

    // Replace this value with your application's callback URL
    callback_url: "https://www.example.com",

    // Replace this value with your application's ID
    client_id: "MY_APPLICATION_ID",

    version: "1.3",
    notes: "notes for the transaction",
    options: {
      supported_tender_types: ["CREDIT_CARD","CASH","OTHER","SQUARE_GIFT_CARD","CARD_ON_FILE"]
    }
  };

  window.location =
    "square-commerce-v1://payment/create?data=" +
    encodeURIComponent(JSON.stringify(dataParameter));
</script>

Step 4: Add code to your callback file to process the transaction response

When the transaction completes and device reactivates the mobile web app, the Square Point of Sale app will also send a POST request to your mobile web app. The POST parameters provide information about whether the associated transaction succeeded or failed along with its accompanying metadata.

We need to add code to our callback file that processes the result.

  1. Declare your parameters.
  2. Process the result from Square.
  3. Print the result to screen.

You will be adding code to your callback file to process the response from the Square Point of Sale app. If you do not already have a callback file, you can make a file called callback.html and paste in the following template code.

<html>

  <head>
    <!-- Loads callback javascript -->
    <script type="text/javascript" src="/callback.js"></script>

  </head>

  <!-- Calls printResponse() when this page loads -->
  <body onload="printResponse()">

    <h1>Callback!</h1>
    <div id="url">
          <!-- empty URL for displaying response -->
    </div>
  </body>

</html>

Step 4.A: Initialize your transaction variables

Make a file called callback.js. This is where we will put our Javascript code that handles the response. In your callback.js file, declare the possible parameter keys that the Square Point of Sale app might return to your app.

For Android devices, you will need to declare the following variables:

//If successful, Square Point of Sale returns the following parameters.
const clientTransactionId = "com.squareup.pos.CLIENT_TRANSACTION_ID";
const transactionId = "com.squareup.pos.SERVER_TRANSACTION_ID";

//If there's an error, Square Point of Sale returns the following parameters.
const errorField = "com.squareup.pos.ERROR_CODE";

For iOS devices, you will need to declare the following variables:

//If successful, Square Point of Sale returns the following parameters.
const clientTransactionId = "client_transaction_id";
const transactionId = "transaction_id";

//If there's an error, Square Point of Sale returns the following parameters.
const errorField = "error_code";

Step 4.B: Process the result

The Square Point of Sale app packages the transaction details differently for iOS and Android devices.

Android

Square Point of Sale apps installed on Android devices will send the transaction results back as parameters in a URL.

  1. Add a function called getUrlParams that grabs the URL parameters and puts them in an array.
//Get the URL parameters and puts them in an array
function getUrlParams(URL) {
    var vars = {};
    var parts = URL.replace(/[?&]+([^=&]+)=([^&]*)/gi,
    function(m,key,value) {
      vars[key] = value;

    });
    return vars;
  }

iOS

Square Point of Sale apps installed on IOS devices will send back a URL with a single parameter called data which contains the transaction details in a JSON block.

//get the data URL and encode in JSON
function getTransactionInfo(URL) {
    var data = decodeURI(URL.searchParams.get("data"));

    console.log("data: " + data);
    var transactionInfo = JSON.parse(data);
    return transactionInfo;
  }

Depending on the result of the transaction, the data object includes some or all of the following fields:

If an error occurs during a Point of Sale API transaction, the JSON data object will return the error_code field.

Step 4.C: Do something with the transaction details

  1. Add functions that handle the success and error responses. If it's successful, handleSuccess() will save the parameters to resultString. If it's an error, handleError() will save the error code and description to a resultString.
// Makes a result string for success situation
function handleSuccess(transactionInfo){
  var resultString ="";

  if (clientTransactionId in transactionInfo) {
    resultString += "Client Transaction ID: " + transactionInfo[clientTransactionId] + "<br>";
  }
  if (transactionId in transactionInfo) {
    resultString += "Transaction ID: " + transactionInfo[transactionId] + "<br>";
  }
   else {
    resultString += "Transaction ID: NO CARD USED<br>";
  }
  return resultString;
}


// Makes an error string for error situation
function handleError(transactionInfo){
  var resultString ="";

  if (errorField in transactionInfo) {
    resultString += "Client Transaction ID: " + transactionInfo[clientTransactionId] + "<br>";
  }
  if (transactionId in transactionInfo) {
    resultString += "Transaction ID: " + transactionInfo[transactionId] + "<br>";
  }
   else {
    resultString += "Transaction ID: PROCESSED OFFLINE OR NO CARD USED<br>";
  }
  return resultString;
}

  1. Add a function that grabs the URL returned by Square and grabs the URL parameters using getUrlParams(). It then uses an if statement to call the right handler, then prints the resultString.
// Determines whether error or success based on urlParams, then prints the string
function printResponse() {
  var responseUrl = window.location.href;
  var transactionInfo = getTransactionInfo(responseUrl);
  var resultString = "";

  if (errorField in transactionInfo) {
    resultString = handleError(transactionInfo);
  } else {
    resultString = handleSuccess(transactionInfo);
  }

  document.getElementById('url').innerHTML = resultString;
}

See the Mobile Web Technical Reference for more information on Android and iOS error codes.

Step 5: Test your code

Android

  1. Initialize the Point of Sale app before testing your first transaction:
    1. Log into the Square Point of Sale app with the business location and employee you want to accept payments with.
    2. If you are using the Square contactless and chip reader, connect it to Square Point of Sale. You will get an error if you call the Point of Sale API without initializing the Point of Sale app first.
  2. Open your web application in an emulator or on your mobile device and click "Start transaction" to bring up the Point of Sale app.
  3. To test the cancellation callback, cancel the transaction in the Point of Sale app.
  4. To test the success callback, complete a cash payment and tap the checkmark to indicate you are done.

iOS

You cannot install the Square Point of Sale app on a virtual xCode machine. For this reason, you will need to test your code on a real iOS device.

You can also test your code that processes the data by creating a test response URL instead of receiving it from Square.

  1. Add a test URL to your callback code.
// Test response URL
const responseUrl = new URL(
  '/create?data={' +
    '"transaction_id":"transaction123",' +
    '"client_transaction_id":"40",' +
    '"status":"ok"' +
  '}',
  'https://squareup.com'
);
  1. Comment out the line in printResponse() that gets the response URL from Square.
// var responseUrl = window.location.href;
Prev
< Point of Sale API Overview
Next
Mobile Web Technical Reference >

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