OAuth API

Build with OAuth API

Web
Backend

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.

Square SDK dependency
Permalink Get a link to this section

If you have not installed the Square PHP SDK yet, download Composer and dependencies to complete this walkthrough. After you've downloaded Composer, install the SDK with the following command from your project directory: composer.phar require square/connect

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.

  2. Set the Application Dashboard into Sandbox Settings mode if you intend to test your OAuth flow in the v2 Sandbox environment.

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

  2. Click Save.

The application ID from the Credentials page and the application secret from the OAuth page will be needed in Step 2.

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. Set your application ID and secret with values from the Application Dashboard from step 1.

  3. Update the code in sq_config.php to set sandbox and production credentials in place of all instances of REPLACE_ME. Replace the values for:

    • _SQ_SANDBOX_LOCATION_ID

    • _SQ_SANDBOX_TOKEN

    • _SQ_SANDBOX_APP_ID

    • _SQ_SANDBOX_APP_SECRET

    • _SQ_LOCATION_ID

    • _SQ_APP_ID

    • _SQ_APP_SECRET

    • _SQ_TOKEN

Read Create a config file for Square APIs and SDKs for more information about using sq_config.php in your app.

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

Create a new file called authorize.php and copy the code below into it:

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

  $useSandbox = TRUE;

  // Display the OAuth link
  // Use _SQ_DOMAIN if you want to authorize in the production environment
  $connectV2Client = $credentialManager->getConnectClient($useSandbox);
  $appId = $credentialManager->getApplicationId($useSandbox);

  echo ($useSandbox == FALSE) ? "<a href=\"https://"._SQ_DOMAIN._SQ_AUTHZ_URL
      ."?client_id=$appId&scope=$permissions\">Click here</a> to authorize the application."
      : "<a href=\"https://"._SQ_SANDBOX_DOMAIN._SQ_AUTHZ_URL
      ."?client_id=$appId&scope=$permissions\">Click here</a> to authorize the application in the sandbox.";
             
?>       

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

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.

Create a new file called oauth_flow.php and copy the code below into the file:

<?php
require_once('path/to/sq_config.php');

  $useSandbox = TRUE;
  $credentialManager = new CredentialManager();
  $connectV2Client = $credentialManager->getConnectClient($useSandbox);
    
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 ;
}

//TODO: Replace with code from Step 5.

?>       

Did you know?

The code in each step will be added to oauth_flow.php. Each code example has a place holder for the next step. For example, //TODO: Replace with code from Step 5.

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.

Copy the code below into the oauth_flow.php file at //TODO: Replace with code from Step 5.:

function getOAuthToken($authorizationCode) {


  # Your application's ID and secret, available from your application dashboard
  $applicationId = $credentialManager->getApplicationId($useSandbox);
  $applicationSecret = $credentialManager->getAppSecret($useSandbox);

  // Create an OAuth API client
  $oauthApi = new SquareConnect\Api\OAuthApi($connectV2Client);
  $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);
}
//TODO: Replace with code from Step 6.

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

Copy the code below into the oauth_flow.php file at //TODO: Replace with code from Step 6.:

# 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/authorize.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.

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


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.

Next steps

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