OAuth API

Build with OAuth API

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

Web
Backend

Prerequisites and assumptions
Permalink Get a link to this section

To build with the OAuth API the following must be true:

  • You are using HTTPS. HTTPS is required for all production Square API calls. HTTP calls are only supported for developing and testing on localhost.


Additionally this guide makes the following assumptions:

  • You have read the What It Does page for this product.

  • You can create and run websites on localhost or a development server. If you are new to testing webpages locally, we recommend reading Running Local Web Servers before continuing.

  • You are familiar with basic web development. If you are new to web development, we recommend reading Getting started with the Web by Mozilla.org before continuing.

  • You are using a Connect API config file.


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.

Information you will need
Permalink Get a link to this section

To use the steps in this guide you will need the following information:

  • While testing: Your sandbox application ID. Enable Sandbox Settings and find your sandbox application ID on the Credentials setting page of your Square application.

  • In production: Your application ID. Find your application ID on the Credentials setting page of your Square application.

Step 1: Configure your OAuth redirect URL
Permalink Get a link to this section

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.

  1. Click the OAuth tab, then set your redirect URL. For now, put http://localhost:8000/request_token.php. We will create the file that this URL points to later.

  2. Click Save.

Step 2: Configure your OAuth information
Permalink Get a link to this section

  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 and to create and configure a new default API client object:

if (!defined(_SQ_AUTHZ_URL)) {
    define('_SQ_AUTHZ_URL', "/oauth2/authorize") ;
}
...
// Create and configure a new API client object
$defaultApiConfig = new \SquareConnect\Configuration();

//Set Connect Endpoint to Sandbox environment
// comment this setHost call out if you want to use the production environment
$defaultApiConfig->setHost("https://connect.squareupsandbox.com");


$defaultApiConfig->setAccessToken(getAccessToken());

$defaultApiClient = new \SquareConnect\ApiClient($defaultApiConfig);
$defaultApiClient

Step 3: Add a link to the Square permission form
Permalink Get a link to this section

Create a new file to serve the webpage that will start the OAuth flow. 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).

Important

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.

Copy the code below into a file called request_token.php:

require_once('path/to/sq_config.php');
...
// Set the permissions
$permissions = urlencode(
                  "PAYMENTS_WRITE " .
                  "PAYMENTS_READ"
               );

// Display the OAuth link
// Use _SQ_DOMAIN if you want to authorize in the production environment
echo '<a href="https://' .
     _SQ_SANDBOX_DOMAIN . _SQ_AUTHZ_URL .
     '?client_id=' . _SQ_APP_ID .
     '&scope=' . $permissions. '">Authorize this application</a>';

Step 4: Add a function to request an authorization code
Permalink Get a link to this section

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

Note

The Client Credentials flow is not supported by Square eCommerce APIs.

Copy the example code below to request_token.php. The example code imports the Connect configuration file and creates a function (getAuthzCode) to exchange the authorization code for an OAuth access token. If the API response is empty the function throws an exception.

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 ;
}

Step 5: Create a function to exchange an authorization code for an OAuth access token
Permalink Get a link to this section

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 Tokens.

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
  $body->setClientId($applicationId);
  $body->setClientSecret($applicationSecret);
  $body->setGrantType("authorization_code");  
  $body->setCode($authorizationCode);

  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);
}

Note

The client_secret must be supplied in the POST body of the OAuth API request. The optional redirect_uri parameter is ignored. The Application Dashboard OAuth settings page requires that you provide a Redirect URL. When the Redirect URL is provided in the registration, OAuth 2 specifies that it should be ignored in requests to Square API endpoints.

Step 6: Add code to start the OAuth flow
Permalink Get a link to this section

Add code to request_token.php to call your functions and walk through the OAuth exchange. Your application should store the access token securely. The example code below prints the access code for testing.

# 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();
  error_log($e->getMessage());
}

Step 7: Test your code on localhost
Permalink Get a link to this section

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.

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.

Did you know?

The permission form only displays if you do not have a current access token. If you want to test your site repeatedly, follow the optional step for revoking tokens and be sure to revoke your token before testing again.

To test in the v2 Sandbox environment, complete steps 1-6. If you are testing in production, complete only steps 4-6.

  1. Set your application dashboard to Sandbox Settings mode before completing the following steps.

  2. Add a new Sandbox Test Account:

    a. Click New Account on the dashboard home page.
    b. Give the account a name and pick a country.
    c. Uncheck Automatically create authorizations for all my current apps.

  3. Click Launch on the new test account to open the sandbox seller dashboard for the account. When you start the OAuth flow, an authorization will be created for the sandbox test account that you created.

  4. Open a browser and navigate to your new OAuth page: localhost/path/to/get_permissions.php.

  5. Click the authorization link on your webpage. It should redirect you to the Square permission form: oauth-permission-form

  6. Click Allow. This should send you back to the redirect URL you configured in Step 1.

Best practices
Permalink Get a link to this section

  • Store OAuth tokens securely. Application clients should never interact with OAuth tokens and OAuth tokens should never be stored in plaintext.

  • Adhere to the principle of least privilege. Applications should never request more than the minimum permissions needed to function properly.

  • Use OAuth for authorization whenever possible. OAuth tokens let users control access to their own accounts and strengthens application security.

Next steps

Now that you have a basic build in place, expand on it with these recipes!