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.
  • You are using the Square Connect PHP SDK.
  • You are using PHP version 5.4 or later.

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. Download the PHP configuration file template from GitHub 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.
 1if (!defined(_SQ_DOMAIN)) {
 2    define('_SQ_DOMAIN', "https://connect.squareup.com") ;
 3}
 4
 5if (!defined(_SQ_SANDBOX_TOKEN)) {
 6    define('_SQ_SANDBOX_TOKEN', "REPLACE_ME") ;
 7}
 8
 9if (!defined(_SQ_SANDBOX_APP_ID)) {
10    define('_SQ_SANDBOX_APP_ID', "REPLACE_ME") ;
11}
12
13if (!defined(_SQ_APP_ID)) {
14    define('_SQ_APP_ID', "REPLACE_ME") ;
15}
16
17if (!defined(_SQ_APP_SECRET)) {
18    define('_SQ_APP_SECRET', "REPLACE_ME") ;
19}
20
21if (!defined(_SQ_AUTHZ_URL)) {
22    define('_SQ_AUTHZ_URL', "/oauth2/authorize") ;
23}
  1. Add code to your config file to create and configure a new default API client object:
// Create and configure a new API client object
$defaultApiConfig = new \SquareConnect\Configuration();
$defaultApiConfig->setAccessToken(getAccessToken());

$defaultApiClient = new \SquareConnect\ApiClient($defaultApiConfig);
  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. Import the configuration file:
require_once('path/to/sq_config.php');
  1. 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).
// Set the permissions
$permissions = urlencode(
                  "PAYMENTS_WRITE " .
                  "PAYMENTS_READ"
               );

// Display the OAuth link
echo '<a href="https://' .
     _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. Import the configuration file:
require_once('path/to/sq_config.php');
  1. Add a function (getAuthzCode) to extract the authorization code.
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.
// Exchange the authorization code for an OAuth token
function getOAuthToken($authorizationCode) {

  // Create an OAuth API client
  $oauthApi = new SquareConnect\Api\OAuthApi($defaultApiClient);
  $body = new \SquareConnect\Model\ObtainTokenRequest();

  // Set the POST body
  $body->setClientId(_SQ_APP_ID);
  $body->setClientSecret(_SQ_APP_SECRET);
  $body->setCode($authorizationCode);

  try {
      $result = $oauthApi->obtainToken($body);
  } catch (Exception $e) {
      error_log 'Exception when calling OAuthApi->obtainToken: ' . $e->getMessage();
      throw new Exception("Error Processing Request: Token exchange failed!", 1);
  }

  return $result->getAccessToken();
}

Step 4: Add code to start the OAuth flow

  1. Add code to request_token.php 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 are not familiar with running a local web server, see Running local web servers for information about testing on your local environment before continuing.

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

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