Build with the API

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.


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


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.

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 the authorization URL:
1if (!defined(_SQ_AUTHZ_URL)) {
2    define('_SQ_AUTHZ_URL', "/oauth2/authorize") ;
  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();

$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:
  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 " .

// Display the OAuth link
echo '<a href="https://' .
     '?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 code 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 access tokens enable your application take action on behalf of the associated Square account.

Step 4: Exchange an authorization code for an OAuth access 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:
  1. Add a function (getAuthzCode) to exchange the authorization code for an OAuth access token. If the API response is empty the function throws an exception.
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 access token. If the API response is empty, this function throws an exception.
function getOAuthToken($authorizationCode) {

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

  // Set the POST body

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

  $accessToken = $result->getAccessToken();
  $refreshToken = $result->getRefreshToken();
  // Return both the access token and refresh token
  return array($accessToken, $refreshToken);

Step 5: 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);
  list($accessToken, $refreshToken) = getOAuthToken($authorizationCode);
  # Use the OAuth access token and refresh token. For testing, we will simply write it to the log
  error_log('OAuth access token: ' . $accessToken);
  error_log('OAuth refresh token: ' . $refreshToken);  
  error_log('Authorization succeeded!');
} catch (Exception $e) {
  echo $e->getMessage();

Step 6: 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.

Refresh expired OAuth access tokens

Square OAuth access tokens expire after 30 days with an additional grace period of 15 days. After expiration, applications must generate a new access token using the refresh token received when the authorization was granted. For more information, see Renew OAuth Token.

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.


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