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.
  1. Create a new PHP file and save it in your web root directory as get_permissions.php.
  2. Add code to your website to configure your application ID and the specific permissions you want to request. Use that information to serve an authorization link to the user that calls the Authorize endpoint and displays the Square permission form.
  1. Set $applicationId as your application ID. You can find this value in your Application Dashboard. Note: The Square OAuth API is not currently supported in sandbox so you cannot use a sandbox application ID with the example code in this guide.
  2. Set $permissions with the list of permissions you want to request in the OAuth UI. 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.
$permissions = urlencode("PAYMENTS_WRITE PAYMENTS_READ");

The permissions list must be URL encoded. For example, replacing spaces with %20. When users click the authorization link they see a Square permissions form asking for the permissions in the list.

Oauth permission form

If your users click Allow on the Square permission form, Square will send an authorization token to your application.

Step 3: Use the authorization code to request an Oauth token from the Obtain Token endpoint

The OAuth UI returns an authorization token you can exchange for an OAuth access token. OAuth tokens let your application take action on behalf of the associated Square account.

  1. Create a php file and save it in your web root directory as request_token.php. This should go on a password-protected area of your website, such as an admin panel.
  2. Get your OAuth application credentials. Go to your Application Dashboard and choose the application you want to work with. You will need:
    • Application ID — You can find your application ID on the Credentials tab.
    • Application Secret — You can find your application secret in the OAuth tab.
  3. Set the application ID and application secret In your new file
# Include the Square Connect API resources.
require '/local/path/to/Square/Connect/SDK/autoload.php';

# Replace with your application ID and application secret.
$applicationId = '{REPLACE ME}';
$applicationSecret = '{REPLACE ME}';

$squareDomain = 'https://connect.squareup.com';

  1. Add a function that verifies that authorization token. If the API response is empty, the function throws an exception.
# Verify the authz token returned by Square
function getAuthzToken($authorizationResponse) {

  # Extract the returned authorization code from the URL
  $authorizationCode = $callbackResponse['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 ;
}

  1. Add another function to exchange the authorization token for an access token. If the API response is empty, this function throws an exception.
# Exchange the authorization token for an Oauth token
function getOAuthToken($authorizationCode, $applicationId, $applicationSecret) {

  # Headers to provide to OAuth API endpoints
  $oauthRequestHeaders = array (
    'Authorization' => 'Client ' . $applicationSecret,
    'Accept' => 'application/json',
    'Content-Type' => 'application/json'
  );

  $oauthRequestBody = array(
    'client_id' => $applicationId,
    'client_secret' => $applicationSecret,
    'code' => $authorizationCode
  );

  $response = Unirest\Request::post(
    _SQUARE_URI . '/oauth2/token',
    $oauthRequestHeaders,
    json_encode($oauthRequestBody)
  );

  # If the exchange failed, log the error and throw an exception
  if (!property_exists($response->body, 'access_token')) {
      error_log('Token exchange failed!');
      throw new \Exception("Error Processing Request: Token exchange failed!", 1);
  }

  return $response->body->access_token;
}

  1. Add code that calls your functions to walk through the OAuth flow.
# Call the function
try {
  $authorizationCode = getAuthzToken($_GET);
  $oauthToken = getOAuthToken(
                  $authorizationCode,
                 $applicationId,
                 $applicationSecret);
  # 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 4: Test your code on localhost

  1. Open a terminal window and navigate to your website's root directory. Then, enter the following command:
php -S localhost:8000

This command starts the built-in PHP web included by default with most PHP libraries. The built-in web server is useful for testing but not intended for production use. Read PHP: Built-in webserver for more about this command.

  1. Visit localhost:8000/get_permissions.php in your browser.
  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:8000/request_token.php

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

Optional: Renew an OAuth token

To renew an OAuth token, send a request to the Renew Token endpoint. OAuth tokens expire 30 days after they are issued. You can renew OAuth tokens from 24 hours after its issued to 15 days after they expire.

  1. Set the client_id and application_secret parameters. You can find this values in your Application Dashboard.
# Your application's ID and secret, available from your application dashboard
$applicationId = '{REPLACE ME}';
$applicationSecret = '{REPLACE ME}';
$redirectUri = '{REPLACE ME}';
$connectHost = 'https://connect.squareup.com';

  1. Create an array for your request headers.
# Create an array for your request headers.
$oauthRequestHeaders = array (
  'Authorization' => 'Client ' . $applicationSecret,
  'Accept' => 'application/json',
  'Content-Type' => 'application/json'
);

  1. Add a callback function that creates a renew token request body, then makes a POST call to the Renew Token endpoint.
# Renew OAuth token.
function renewOAuthToken($authorizationCode, $applicationId, $applicationSecret, $oauthRequestHeaders) {

  # Headers to provide to OAuth API endpoints.
  = array (
    'Authorization' => 'Client ' . $applicationSecret,
    'Accept' => 'application/json',
    'Content-Type' => 'application/json'
  );

  $oauthRequestBody = array(
    # The OAuth token you want to renew.
    'access_token' => $oauthToken,
  );

  $response = Unirest\Request::post(
    $squareDomain . '/oauth2/clients/$applicationId/access-token/renew
',
    $oauthRequestHeaders,
    json_encode($oauthRequestBody)
  );

  # If the exchange failed, log the error and throw an exception.
  if (!property_exists($response->body, 'access_token')) {
      error_log('Renew token failed');
      throw new \Exception("Error Processing Request: Token exchange failed!", 1);
  }

  return $response->body->access_token;
}

If your request is successful, the Renew Token endpoint will return a renewed OAuth token.

Optional: Revoke an OAuth token

Users should be able to revoke access to their accounts. To revoke an OAuth token, send a request to the Revoke Token endpoint.

  1. Add code to your site that allows users to revoke access to their accounts. Make sure this code goes in the same password-protected area as the your main OAuth flow.
        <form action="revoke_token.php" method="post" onsubmit=paymentFormSubmit() >
            <h2>Revoke Access to your Account</h2>
            <p> If you want to close your account or revoke this application's access to your Square merchant account, click this button.</p>

            <input type="submit" id="submit" value="Revoke Access" class="btn btn-primary"/>
        </form>

  1. Create a PHP file called revoke_token.php. This file will run when the user clicks the "Revoke Access" button that you added in the previous step.
  2. Set the client_id and application_secret parameters. You can find this values in your Application Dashboard.
# Your application's ID and secret, available from your application dashboard
$applicationId = '{REPLACE ME}';
$applicationSecret = '{REPLACE ME}';

$connectHost = 'https://connect.squareup.com';

  1. Add code to call the OAuth API and revoke the access token. To make this call, you need to use an access token or a merchant ID. The example code below uses an access token and assumes you have already retrieved and decrypted the OAuth token.
# Revokes access token
function revokeToken() {
  global $connectHost, $oauthRequestHeaders, $applicationId, $applicationSecret,
    $accessToken;
    # Provide the code in a request to the Revoke Token endpoint
    $revokeRequestBody = array(
      'client_id' => $applicationId,
      'access_token' => $accessToken,
    );
    $response = Unirest\Request::post($connectHost . '/oauth2/revoke',
      $oauthRequestHeaders, json_encode($revokeRequestBody));

    # Prints "Success!" if you successfully revoke the token.
    if ($response->body->success == true) {
      echo "Success!";
      # Otherwise, prints "Failure".
    } else {
      echo "Failure";
    }
}

  1. If your request is successful, the Revoke Token will revoke the OAuth token and your code will print "Success!"

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 Obtain Token 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 Obtain Token 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 Obtain Token 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