API Basics

OAuth Setup Guide

Set up the Square OAuth API to securely manage application permissions and access to other Square merchant accounts.

To learn more about OAuth and how the Square OAuth API works, please see the Square OAuth API Overview.

Prerequisites

HTTPS is required for all Square API calls. HTTP is supported only for developing and testing on localhost.

Assumptions

This guide makes the following assumptions:

  • You have read the OAuth API Overview, which covers general functionality of the API.
  • You are familiar with HTML and PHP.
  • 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.

Working example

In order to provide concrete instruction, this guide is based on the following:

  • We are building a merchant site. While OAuth is commonly associated with mobile development, it can also be used with web applications to improve security for the associated Square account.
  • The merchant site is being developed on a local machine (i.e. using localhost). The Square OAuth API permits HTTP connections from localhost, but requires HTTPS for production connections.
  • The merchant site uses PHP version 5.4 or later. PHP was selected for the example code because it is a common web language and relatively approachable for new developers, but the Transactions API is language agnostic and the setup steps are comparable across languages.

If your situation is different from the working example outlined here, you should still be able to follow along with the steps in this guide.

Step 1: Configure your OAuth redirect URL

When the user clicks Allow on the Square permission form, Square will send a response to the redirect URL configured for your application. You need to go into your Application Dashboard and set the redirect URL in the application control panel.

To set your redirect URL:

  1. Open your Application Dashboard. If you have multiple applications, click the one you want to work with.
  2. Click the OAuth tab, then set your redirect URL. For now, put
    http://localhost:8000/request_token.php. In Step 3, we'll create the request_token.php file that this URL points to.
  3. Click Save.

Step 2: Configure your OAuth information

  1. Create a new configuration file and save it in your web root directory as sq_config.php.
  2. Add code to the configuration file to set some useful constants, your application ID, and application secret.
if (!defined(_SQ_DOMAIN)) {
    define('_SQ_DOMAIN', "https://connect.squareup.com") ;
}

if (!defined(_SQ_AUTHZ_URL)) {
    define('_SQ_AUTHZ_URL', "/oauth2/authorize") ;
}

if (!defined(_SQ_EXCHANGE_URL)) {
    define('_SQ_EXCHANGE_URL', "connect.squareup.com") ;
}

if (!defined(_SQ_DOMAIN)) {
    define('_SQ_DOMAIN', "connect.squareup.com") ;
}

if (!defined(_SQ_APP_ID)) {
    define('_SQ_APP_ID', "{REPLACE_ME}") ;
}
if (!defined(_SQ_APP_SECRET)) {
    define('_SQ_APP_SECRET', "{REPLACE_ME}") ;
}

You can find your application information in the Application Dashboard under the Credentials and OAuth setting pages for your application:

  • Application ID — You can find your application ID on the Credentials tab.
  • Application Secret — You can find your application secret in the OAuth tab.
  1. Create a new file and save it in your web root directory as get_permissions.php. This is the page that will start the OAuth flow.
  2. Add code to your new file to configure the permissions you want to request and use that information to serve an authorization link to your user. See the Oauth permissions guide for a full list of available permissions. For now, we will use basic read and write permissions for transaction processing (PAYMENTS_READ and PAYMENTS_WRITE).
// Include the configuration file
require_once('path/to/sq_config.php');

// Set the permissions
$permissions = urlencode(
                  "PAYMENTS_WRITE " .
                  "PAYMENTS_READ"
               );

// Display the OAuth link
echo '<a href="' .
     _SQ_DOMAIN . _SQ_AUTHZ_URL .
     '?client_id=' . _SQ_APP_ID .
     '&scope=' . $permissions. '">Authorize this application</a>";

The permissions list must be URL encoded. For example, replacing spaces with %20. When users click the authorization it calls the Authorize endpoint and displays the Square OAuth permission form asking for the permissions in the list.

Oauth permission form

The Square OAuth permission form returns an authorization token to the redirect URL you configured in Step 1. You must exchange the authorization code (a short-lived credential) for an OAuth access token (a long-lived authorization credential). OAuth tokens let your application take action on behalf of the associated Square account.

Step 3: Exchange an authorization code for an Oauth token

  1. Create a new file and save it as request_token.php to handle the credential exchange. The exchange code should live in password-protected area of your website, such as an admin panel.

  2. Add a function (getAuthzCode) to extract the authorization code.

// Include the configuration file
require_once('path/to/sq_config.php');

function getAuthzCode($authorizationResponse) {

  // Extract the returned authorization code from the URL
  $authorizationCode = $authorizationResponse['code'];

  # If there is no authorization code, log the error and throw an exception
  if (!$authorizationCode) {
    error_log('Authorization failed!');
    throw new \Exception("Error Processing Request: Authorization failed!", 1);
  }

  return $authorizationCode ;

Read about fixing common errors for troubleshooting hints.

  1. Add another function (getOAuthToken) to exchange the authorization code for an OAuth token. If the API response is empty, this function throws an exception.
// Include the configuration file
require_once('path/to/sq_config.php');

# Exchange the authorization code for an OAuth token
function getOAuthToken($authorizationCode) {

  $oauthRequestHeaders = array(
    "Content-Type: application/json",
    "Accept: application/json"
  );
  $oauthRequestBody = array(
    'client_id' => _SQ_APP_ID,
    'client_secret' => _SQ_APP_SECRET,
    'code' => $authorizationCode
  );
  $encodedData = json_encode($oauthRequestBody);

  $curlHandle = curl_init(_SQ_DOMAIN . _SQ_EXCHANGE_URL);
  curl_setopt($curlHandle, CURLOPT_POST, true);
  curl_setopt($curlHandle , CURLOPT_HTTPHEADER, $oauthRequestHeaders );
  curl_setopt($curlHandle, CURLOPT_POSTFIELDS, $encodedData);
  curl_setopt($curlHandle, CURLOPT_RETURNTRANSFER, true);

  $response = json_decode(curl_exec($curlHandle), true) ;
  curl_close($curlHandle);

  if  (
        ($response == null) ||
        (!is_array($response)) ||
        (!array_key_exists('access_token', $response))
      ) {
    error_log('Get access token failed');
    throw new Exception("Error Processing Request: Token exchange failed!", 1);
  } else {
      $accessToken = $response['access_token'];
  }
  return $accessToken;
}

Step 4: Add code to start the OAuth flow

  1. Add code that calls your functions to walk through the OAuth exchange.
# Call the function
try {
  $authorizationCode = getAuthzCode($_GET);
  $oauthToken = getOAuthToken($authorizationCode);

  # Use the OAuth token. For testing, we will simply write it to the log
  error_log('OAuth token: ' . $oauthToken);
  error_log('Authorization succeeded!');
} catch (Exception $e) {
  echo $e->getMessage();
  error_log($e->getMessage());
}

Step 5: Test your code on localhost

If you don't have a local web server, see Running local web servers for information about testing on your local environment.

To test your code:

  1. Open a browser and type in the URL for your new get_permissions.php file. For example: localhost/path/to/get_permissions.php.
  2. Click the authorization link on your webpage. It should redirect you to the Square permission form.
  3. Click Allow. This should send you back to the redirect URL you configured in Step 1: localhost/path/to/request_token.php

OAuth allows HTTP calls from localhost for testing purposes. API calls from any other webserver must use HTTPS. See the HTTPS Overview to learn more about HTTPS and how to enable it on your website.

Fixing common errors

If an OAuth endpoint returns an error message instead of the values you expect, check here for the cause and most likely solution.

Invalid client or client secret

Likely cause: An incorrect application secret was provided in a request to the ObtainToken endpoint.

Make sure you have copied the entire application secret from the OAuth tab in the application control panel, and that the application ID and application secret you are using are from the same application.

Invalid code

Likely cause: An incorrect authorization code was provided in a request to the ObtainToken endpoint. The two most common causes of this are:

  • The authorization code in your Obtain Token request does not match the authorization code provided by the OAuth UI.
  • The authorization code has expired because it was issued more than 5 minutes before calling Obtain Token..

Call the ObtainToken endpoint to generate a new authorization code and try again.

Unauthorized

Likely cause: The API request used an incorrect OAuth token.

Confirm all of the following is true:

  • You are using a valid, unexpired OAuth token.
  • Your OAuth token includes all the permissions required by the endpoint.
  • You are calling the API with HTTPS and including your OAuth token in the header with the following format: Authorization: Bearer ACCESS_TOKEN
Next
HTTPS Overview >

Ask for help on Stack Overflow or join our Slack channel