OAuth API

OAuth API: Walkthrough

This walkthrough sets up a basic website that implements the Square OAuth flow. We keep it simple and build a basic web page that links to the Square authorization page and a server-side web page that handles the authorization callback. This set of pages enables a seller to authorize your application and for your application to get an access token to make calls on that seller's behalf.

Implementing the Square OAuth flow for your application is a four-step process:

  1. Set up your application in the Developer Dashboard.

  2. Link to the Square authorization page with your application ID and the permissions you want the seller to grant. When the seller chooses Allow on the authorization page, the seller is redirected to the callback that you specified for your application. The redirect passes an authorization code as one of the query parameters.

  3. Exchange the authorization code for OAuth tokens. The callback reads the authorization code and uses it along with your application credentials to call the Obtain Token endpoint to get the OAuth access token and refresh token. You use the access token to make calls on behalf of the seller.

  4. Maintain access using the refresh token. An OAuth access token expires after 30 days. To maintain access, you call Obtain Token using the refresh token to get a new OAuth token.

In this walkthrough, you follow this process to set up a website that implements the Square OAuth flow. You then test the setup by using a Sandbox seller account to go through the flow from the standpoint of a seller authorizing your application. The walkthrough also shows you how a seller views your application in the App Marketplace in the Seller Dashboard.

Before you begin, note the following:

  • The walkthrough uses an example PHP web server project. After finishing this walkthrough, you can explore similar examples in other languages on GitHub. For more information, see connect-api-examples.

  • The Square Sandbox environment is used for testing. In the Sandbox, you do not work with real Square accounts. The Sandbox enables you to see how OAuth works in a developer account (Default Test Account) that contains the application and how a seller account interacts with the OAuth process, without impacting your production environment.

Get ready Permalink Get a link to this section

To prepare for this walkthrough, you:

  • Create an application.

  • Set up Sandbox accounts.

  • Download the example project.

Create an application Permalink Get a link to this section

You can use an existing application, but for this walkthrough you create a new one.

  1. Go to the Developer Dashboard.

  2. Choose Create your first application to create an application. If you have one or more existing applications, click the + (plus sign) in the empty application card.

  3. In the Application Name box, type the name: My Example App.

  4. Choose Save.

Create a seller sandbox account Permalink Get a link to this section

In this walkthrough, you use Sandbox accounts to try out OAuth. Your Square account comes with a Sandbox account named Default Test Account. This is the Sandbox account for your developer account. You need to create another Sandbox account to serve as a seller account to test authorizing your application (My Example App) in the Default Test Account.

Create a Sandbox account as a seller test account:

  1. Open the Developer Dashboard.

  2. In the Sandbox Test Accounts section, choose Add.

  3. For Account Name, specify Seller Test Account.

  4. For Country, choose one that matches the country you specified when you created your Square account.

  5. Clear the Automatically create authorizations for all my current apps check box.

  6. Choose Create.

The Developer Dashboard should look something like the following:

OAuth : Walkthrough : figure 1

Download the project template Permalink Get a link to this section

For this exercise, you start with a predefined project to set up your initial web server.

  1. Download the connect-api-examples project using one of the following options:

    • Download the ZIP file and unzip the content to a local directory.

    • Clone the GitHub repository to a local directory.
      The connect-api-examples repository contains the OAuth PHP project you use for this walkthrough. It also has the OAuth project implemented in other languages as well as examples of other API use cases.

  2. Open a command line.

  3. Within the project directory, change to the connect-examples/oauth/php/ sub-directory.

  4. Review the directory. You work with code in the following files:

    • sandbox_request_token.php is a basic web page that has a configured link to the Square authorization page so that a Sandbox seller account can authorize your application.

    • sandbox_callback.php is the page that the authorization page redirects to and where your application exchanges the authorization code for OAuth tokens.

    • sandbox_messages.php contains helper functions to give easy access to tokens and display error messages.

  5. In the directory, create the sandbox_config.php file, which is a configuration file that contains the credentials and IDs for your application.

  6. Install the Square PHP SDK in your project directory. Follow the installation instructions.

  7. Run the following command to start the server:

    php -S localhost:8000
    
  1. Verify that the PHP server is running. Open a browser window and enter http://localhost:8000/sandbox_request_token.php. You should see the following:

oauth : walkthrough : Figure 2

Now you are ready to build a basic web application that implements the Square OAuth flow.

Step 1: Set up your application Permalink Get a link to this section

To implement the Square OAuth flow, you need to get or set the following in the Developer Dashboard:

  • Get the application ID. In the OAuth specification, this is the client ID.

  • Get the application secret. In OAuth, this is the client secret.

  • Set the redirect URL for the callback endpoint where your application receives the authorization code so you can exchange it for an OAuth access token.

The application ID is needed as a query parameter for the Square authorization page that you link to so a seller can authorize your application. The Square authorization page sends the authorization code for the seller to the callback endpoint specified by your application's redirect URL. Your implementation of that callback needs the application ID and application secret (along with the authorization code) to call the Obtain Token endpoint to exchange the authorization code for an OAuth access token.

Get your credentials and set the redirect URL:

  1. Open the Developer Dashboard.

  2. Choose Open on the card for the My Example App application.

  3. At the top of the page, set the dashboard mode to Sandbox.

  4. Choose OAuth in the left navigation pane. The OAuth page is shown.

  5. In the Sandbox Redirect URL box, enter the URL for the callback you implement to complete the OAuth flow:

     http://localhost:8000/sandbox_callback.php
    

    This walkthrough uses localhost in the Square Sandbox. You can use HTTP for localhost but an actual web server implementation must use HTTPS.

  6. In the Sandbox Application ID box, copy the application ID.

  7. In the Sandbox Application Secret box, choose Show, and then copy the application secret.

  8. Choose Save.

  9. Create the sandbox_config.php file and add the following code. Follow the instructions in the file to replace the appropriate REPLACE_ME placeholders with the Sandbox application ID and Sandbox application secret. The file should look like the following:

    <?php
    require 'vendor/autoload.php';
    
    // To keep it simple and because we are using sandbox,
    // this example uses a named constant to store the application secret.
    // In production, you should encrypt sensitive data such as the application secret and OAuth tokens.
    // For more information on best practices, see the Square API OAuth documentation.
    
    // Sandbox application ID is used for the following:
    // --The client_id query parameters for the Square Authorization Page URL
    // --The client_id value in the POST body when calling Obtain Token
    // REPLACE_ME = the sandbox application ID from the application's OAuth tab in the Developer Dashboard.
    define('_SQ_SANDBOX_APP_ID', "REPLACE_ME");
    
    // Sandbox application secret is the client secret required to call Obtain Token.
    // REPLACE_ME = the sandbox application secret from the application's OAuth tab.
    define('_SQ_SANDBOX_APP_SECRET', "REPLACE_ME");
    ?>
    

    Note that OAuth Sandbox credentials begin with a sandbox prefix and that the base URL for calling Sandbox endpoints is https://connect.squareupsandbox.com. When you implement for production, you need production credentials and use https://connect.squareup.com as the base URL. In addition, you should avoid putting the application secret directly in your source code. Instead, you should encrypt the secret and use a method, such as environment variables, to reference the secret in your application.

  10. Save the file.

Step 2: Link to the Square authorization page Permalink Get a link to this section

A seller initiates the OAuth flow by being redirected to the Square authorization page. Usually, this is done using a link on a web page or within your mobile or native application. The link sends the seller to the Square authorization page so the seller's identity can be verified using Square sign-in and so the owner can grant the permissions to your application. The link's URL looks like the following:

https://connect.squareupsandbox.com/oauth2/authorize?client_id=sandbox-sq0idb-RNyTfyZYZsDnUoXpLz-HGg&scope=MERCHANT_PROFILE_READ+PAYMENTS_WRITE_ADDITIONAL_RECIPIENTS+PAYMENTS_WRITE+PAYMENTS_READ

The client_id parameter is the Sandbox application ID that you collected in step 1. The scope is the set of permissions that you want the seller to grant to your application. The permissions in the list are separated by a URL-encoded space (%20 or +).

Let’s look at the scope that we set for this walkthrough:

  • MERCHANT_PROFILE_READ enables calls to List Merchants and Retrieve Merchant endpoints. It is useful to be able to call these endpoints so you can verify seller information tied to the OAuth token.

  • PAYMENTS_WRITE and PAYMENTS_READ enable you to create, cancel, and retrieve payments using the Payments API. Later in our walkthrough, you call Create Payment with an OAuth token.

  • PAYMENTS_WRITE_ADDITIONAL_RECIPIENTS enables you to add an application fee to a payment. The application fee is taken from the payment taken on behalf of the seller and added to your developer account. The seller gets the balance of the payment (less the Square transaction fee). The application fee is specified as part of a Create Payment call.

The sandbox_request_token.php file contains the link to the Square authorization page. It URL-encodes the list of space-delimited permissions and creates the link using the Sandbox base URL, authorization page path, Sandbox application ID, and the encoded permissions. The md5 function is used to generate a random string that is stored in the session's cookie and passed in the state parameter. This example uses the session's cookie to store the state value. The state parameter is returned by the Square authorization page so that the callback specified by the Sandbox redirect URL can use that value to compare it to the string stored in session cookie. The state parameter helps protect against cross-site request forgery (CSRF).

The session parameter is omitted because Sandbox only supports a setting of true, which is the default. For production, this value should be false. For more information about using the session parameter in production, see session parameter guidelines in OAuth Production Best Practices

<?php
require_once('sandbox_config.php');

// Specify the permissions and url encode the spaced separated list.
$permissions = urlencode(
                 "ITEMS_READ " .
                 "MERCHANT_PROFILE_READ " .
                 "PAYMENTS_WRITE_ADDITIONAL_RECIPIENTS " .
                 "PAYMENTS_WRITE " .
                 "PAYMENTS_READ"
              );

// Set the Auth_State cookie with a random md5 string to protect against cross-site request forgery.
// Auth_State will expire in 60 seconds after the page is loaded.
$state = md5(time());
setcookie("Auth_State", $state, time()+ 60);

// Display the OAuth link.
echo '<p><a href="' . _SQ_SANDBOX_BASEURL . "/oauth2/authorize" .
    '?client_id=' . _SQ_SANDBOX_APP_ID .
    '&scope=' . $permissions .
    '&state=' . $state .
    '">SANDBOX: Authorize this application</a></p>';
?>

Step 3: Exchange the authorization code for OAuth tokens Permalink Get a link to this section

After the seller allows (or denies) your application the permissions requested, the Square authorization page redirects to the redirect URL that you specified on the OAuth page. The URL has a query string that contains an authorization code or an error (a denial returns an error). The main code block handles the query string sent to the page. If there is an authorization code, the obtainOAuthToken function is called to exchange the authorization code for OAuth tokens. In this step, we review the code for the sandbox_callback.php page.

3.1 Handle the authorization callback Permalink Get a link to this section

The main code block looks like the following:

// Handle the response.
try {
   // Verify the state to protect against cross-site request forgery.
   if ($_COOKIE["Auth_State"] !== $_GET['state']) {
     displayStateError();
     return;
   }

   // When the response_type is "code", the seller clicked Allow
   // and the authorization page returned the auth tokens.
   if ("code" === $_GET["response_type"]) {
     // Get the authorization code and use it to call the obtainOAuthToken wrapper function.
     $authorizationCode = $_GET['code'];
     list($accessToken, $refreshToken, $expiresAt, $merchantId) = obtainOAuthToken($authorizationCode);
     // Because we want to keep things simple and we're using Sandbox,
     // we call a function that writes the tokens to the page so we can easily copy and use them directly.
     // In production, you should never write tokens to the page. You should encrypt the tokens and handle them securely.
     writeTokensOnSuccess($accessToken, $refreshToken, $expiresAt, $merchantId);
   }
   elseif ($_GET['error']) {
     // Check to see if the seller clicked the Deny button and handle it as a special case.
     if(("access_denied" === $_GET["error"]) && ("user_denied" === $_GET["error_description"])) {
       displayError("Authorization denied", "You chose to deny access to the app.");
     }
     // Display the error and description for all other errors.
     else {
       displayError($_GET["error"], $_GET["error_description"]);
     }
   }
   else {
     // No recognizable parameters were returned.
     displayError("Unknown parameters", "Expected parameters were not returned");
   }
} catch (Exception $e) {
 // If the obtainToken call fails, you'll fall through to here.
 displayError("Exception", $e->getMessage());
}

The main purpose of this code block is checking the query parameters. To ensure that the response corresponds to the request made in this session, the first if statement checks the state parameter against the value stored in the cookie. If the values do not match, the displayStateError function is called to display a message indicating that the state check failed and this block is exited. If the state check succeeds, there is a check for the response_type parameter. If the response_type parameter is set to code, it means there is an authorization code returned in the code parameter. The page gets the authorization code and passes it to the obtainOAuthToken function, which returns the OAuth access token and refresh token. For this walkthrough, those tokens are displayed on the web page so you can get them easily. In production, you should never display the tokens. Instead, you should encrypt them and store them securely. For more information, see OAuth Production Best Practices .

If there is no response_type parameter set, error states are handled (including the case where the seller chooses Deny) and an error message is displayed.

3.2 Exchange the authorization code for tokens Permalink Get a link to this section

The obtainOAuthToken function looks like the following:

// The obtainOAuthToken function shows you how to obtain a OAuth access token
// with the OAuth API with the authorization code returned to OAuth callback.
use Square\Exceptions\ApiException;
use Square\SquareClient;
use Square\Environment;
use Square\Http\HttpResponse;
use Square\Models\ObtainTokenReques;
// The obtainOAuthToken function shows you how to obtain a OAuth access token
// with the OAuth API with the authorization code returned to OAuth callback.
function obtainOAuthToken($authorizationCode) {
  // Initialize Square PHP SDK OAuth API client.
  $apiClient = new SquareClient([
    'environment' => Environment::SANDBOX,
  ]);
  $oauthApi = $apiClient->getOAuthApi();
  // Initialize the request parameters for the obtainToken request.
  $body_grantType = 'authorization_code';
  $body = new ObtainTokenRequest(
    _SQ_SANDBOX_APP_ID,
    _SQ_SANDBOX_APP_SECRET,
    $body_grantType
  );
  $body->setCode($authorizationCode);
  // Call obtainToken endpoint to get the OAuth tokens.
  try {
      $response = $oauthApi->obtainToken($body);
      if ($response->isError()) {
        $code = $response->getErrors()[0]->getCode();
        $category = $response->getErrors()[0]->getCategory();
        $detail = $response->getErrors()[0]->getDetail();
        throw new Exception("Error Processing Request: obtainToken failed!\n" . $code . "\n" . $category . "\n" . $reason, 1);
      }
  } catch (ApiException $e) {
      error_log($e->getMessage());
      error_log($e->getHttpResponse()->getRawBody());
      throw new Exception("Error Processing Request: obtainToken failed!\n" . $e->getMessage() . "\n" . $e->getHttpResponse()->getRawBody(), 1);
  }
  // Extract the tokens from the response.
  $accessToken = $response->getResult()->getAccessToken();
  $refreshToken = $response->getResult()->getRefreshToken();
  $expiresAt = $response->getResult()->getExpiresAt();
  $merchantId = $response->getResult()->getMerchantId();
  // Return the tokens along with the expiry date/time and merchant ID.
  return array($accessToken, $refreshToken, $expiresAt, $merchantId);
}

The obtainOAuthToken function takes the authorization code and calls the Obtain Token endpoint to get the OAuth access token and refresh token. To exchange an authorization code, the Obtain Token endpoint takes your application ID, your application secret, a grant_type of authorization_code, and the authorization code.

3.3 Test your authorization flow Permalink Get a link to this section

We test the two main flows that are possible based on a seller's actions in the Square authorization page: deny and allow authorization for your application.

  1. Open the Developer Dashboard.

  2. In the Sandbox Test Accounts section, find the seller test account you created, and then choose Open.

    The Sandbox Seller Dashboard for the seller account opens in a new tab. The Seller Dashboard is what the seller uses to manage the Square account on the web. In the Sandbox, the seller needs to be signed in to see the Square authorization page. You sign in to a seller test account by launching the Seller Dashboard for that account. In production, you can also control whether you force the seller to sign in explicitly by setting the session parameter to false (recommended). For more information, see OAuth Production Best Practices .

  3. In the left pane, choose Apps.

    OAuth : Walkthrough : figure 3

    The Apps page is where your application is displayed after your application completes the OAuth flow for a seller. No apps are shown in the list because Seller Test Account has not yet authorized any applications.

  4. Save all the files you have worked on in the OAuth walkthrough.

  5. Start the PHP server, if it is not running:

    php -S localhost:8000
    
  1. Open a browser window and open sandbox_request_token.php on localhost by entering http://localhost:8000/sandbox_request_token.php in the address bar.

  2. Choose the Authorize this application link. The Square authorization page loads and looks like the following:

    OAuth : How it works : fig 1

    Note that permissions you requested in the authorization URL are listed on the page. You can test both the Deny and Allow flows in the next steps.

  3. Choose Deny. The authorization page sends the browser to the page specified by your application's Redirect URL setting. The URL looks like the following:

    http://localhost:8000/sandbox_callback.php?error=access_denied&error_description=user_denied

    The URL has two query parameters. The error value of access_denied indicates that authorization was denied. The error_description indicates that the reason for the denial was because the user chose the Deny button. The sandbox_callback.php page reads the query parameters, handles this error case, and displays error details that say: You chose to deny access to the app

  4. In the browser address bar, go to http://localhost:8000/sandbox_refresh_token.php, refresh the page to reset the state in the cookie, choose Authorize this application, and then choose Allow. The authorization page redirects to your application's callback page with a URL that looks like the following:

    http://localhost:8000/sandbox_callback.php?code=sandbox-sq0cgb-xJPZ8rwCk7KfapZz815Grw&response_type=code
    

    The URL has two query parameters. The response_type parameter tells you what is being returned. You should check response_type to ensure that its value is code. The code parameter is the authorization code that you exchange for an OAuth access token. The sandbox_callback.php page reads the query parameters, uses the authorization code to get OAuth tokens, and displays: Authorization succeeded.

    The page looks something like the following:

oauth : walkthrough : Figure 5

Because you are testing in the Sandbox, the example writes the access and refresh tokens to the page to make it easy for you to use the tokens.

Important

In production, you should not write the tokens in clear text and you certainly should not display them on a web page. You should encrypt the tokens and store them securely in a database or other type of storage solution.

  1. Copy the OAuth access token and refresh token from the callback page. You use the OAuth tokens to call the Create Payment and Obtain Token endpoints and to get a new access token using the refresh token in the next steps.

  2. See what an authorized application looks like for the seller. Open the Developer Dashboard, find the seller test account you created in the Sandbox Test Accounts section, choose Open, and then choose Apps in the left pane.

OAuth : Walkthrough : figure 6

In the Sandbox, the application ID is displayed as the name (in production, the application name is displayed). The seller can revoke access to your application by choosing the X in the Square account access section.

  1. Choose the application link to see the authorized permissions for this application.

OAUTH walkthroiugh step 3.3 - 11b

You have successfully received OAuth tokens from a Sandbox seller account and have seen the process from both the developer and seller perspectives. Now you can use your token to call some Square APIs.

3.4 Use your token to call a Square API on behalf of the seller Permalink Get a link to this section

After you get your tokens, you can use the OAuth access token to call the Square API endpoints that your application has permissions for. To keep this simple, use API Explorer to call the Create Payment endpoint to take a $100.00 payment with a $5.00 app fee that goes to your Square developer account and the rest going to the seller.

  1. Go to Square API Explorer. oauth : walkthrough : Figure 6.6

  2. Make sure Sandbox is selected, paste the access token that you obtained in the OAuth process into the Access token box, and then choose Save.

    API Explorer uses this access token to make calls on behalf of the seller.

  3. Set the following parameters in the Body:

    1. For amount_money, choose Add, enter 10000 for the amount, and then set the currency to what you selected as your country when you created your Square account.

      Note that money is represented in the lowest denomination for a currency, which for USD is cents. So the amount of 10000 is $100.00.

    2. For idempotency_key, choose Generate to create a unique value to ensure that this payment is only made once. For more information, see Idempotency .

    3. For source_id, choose cnon:card-nonce-ok. This simulates a card nonce that represents a credit card that can be used for payment. For more information about card nonces, see Online Payment Options.

    4. For app_fee_money, choose Add, enter 500 for amount, and then set the currency to what you selected as your country when you created your Square account. oauth : walkthrough : Figure 8

  4. Choose Run Request. The Response box displays a 200 response code and returns details about the payment in the body of the response. The payment has an id value that you can use to identify this particular payment when calling List Payments or you can get it directly using Get Payment. oauth : walkthrough : Figure 9

You have successfully taken a payment using the Square API on behalf of a seller. Look at the seller's Seller Dashboard to see what it looks like from the seller's point of view.

  1. Open the Developer Dashboard, find the seller test account you created earlier in the Sandbox Test Accounts section, and then choose Open.

  2. In the Sandbox Seller Dashboard, choose Transactions in the left pane, and then choose the most recent transaction (there should be only one if this is the first time you have used this Sandbox account). The transaction details appear in a pane on the right.

oauth : walkthrough : Figure 10

You see the $100 payment that was just completed as well as the $5 app fee that your application collected and attributed to your Sandbox developer account.

In the Other row, you see the $5.00 app fee from the Create Payment call.

You have successfully used an OAuth token to call a Square API endpoint on behalf of a seller and have seen the results in the seller account.

Step 4: Renew your OAuth access token Permalink Get a link to this section

As previously discussed, an OAuth access token expires in 30 days. This means if you want your application to continue to be able to call on behalf of a seller, you must renew the access token. To do this, your application needs to call Obtain Token passing the refresh token instead of an authorization code. You can do this with API Explorer.

  1. Go to the Obtain Token page in API Explorer.

  2. Set the following parameters in the Body:

    1. client_id to the application ID for your application.

    2. client_secret to the application secret.

    3. grant_type to refresh_token.

    4. refresh_token to the refresh token you got from your original call to Obtain Token.

    oauth : walkthrough : Figure 10.5

  3. Choose Run Request. The 200 response looks like the following:

oauth : walkthrough : Figure 11

The access_token value is your new OAuth token. The refresh token never expires so you can use that same refresh token to get an OAuth access token whenever you need a new one.