Test Authorization with a Web Server

Applies to: OAuth API | Payments API

Learn how to use the OAuth code flow to authorize your application to access a Square account.

Link to section

Overview

Applications use OAuth access tokens to call Square APIs on behalf of Square sellers. Token acquisition includes the following high-level stages:

  1. Get authorization from the seller - Provide the authorization URL to the seller, which you simulate by signing in using a Sandbox test account. The authorization URL sends the seller to the Square authorize page where they can grant permissions to your application.
  2. Callback and token request - Set up a redirect URL for your application to receive the authorization code. Use this code to obtain OAuth access and refresh tokens.
  3. Refresh and revoke OAuth tokens - Sandbox tokens behave like production tokens, allowing you to maintain access using the refresh token. Remember, an OAuth access token expires after 30 days.

Square provides sample applications that demonstrate OAuth basics. This walkthrough uses the PHP sample in the Sandbox so you can test the OAuth flow without impacting the production environment or production accounts. After obtaining an access token, you refresh and then revoke the access token using API Explorer.

Important

In-production applications are required to securely store and manage OAuth tokens, which is outside the scope of the sample application.

Link to section

Requirements and limitations

  • You have a Square account and an application.

  • You created a Sandbox seller account to simulate the OAuth flow. This test account is different from your Default Test Account and must be configured to manually authorize your applications.

    To create a Sandbox seller account for this walkthrough:

    1. Open the Developer Console.
    2. In the left pane, choose Sandbox test accounts.
    3. Choose New sandbox test account.
    4. In the Account Name box, enter Seller Test Account.
    5. In the Country box, choose any country.
    6. Clear the Automatically create authorizations for all my current apps checkbox.
    7. Choose Create.
  • You downloaded or cloned the Square OAuth Examples repository. This walkthrough uses the Square OAuth Flow Example (PHP) sample application, which is a PHP web server project. Set up instructions are provided in the following sections.

    To download or clone the repository, do one of the following:

    • Download the repository as a ZIP file and unzip the contents to a local directory.
    • Clone https://github.com/Square-Developers/oauth-examples.git to a local directory.

    All of the OAuth sample applications in the repository have the same high-level workflow and concepts, even though the code and implementation differs by language.

  • This walkthrough configures the sample application to use the Sandbox environment, which doesn't work with production application credentials or production Square accounts. To test the sample application in production, configure the .env file to use the production environment, provide your production application ID and secret, and test with a production seller account. See the next section for more information about testing in production.

Link to section

OAuth code flow in production

To implement the OAuth code flow in production, you need to use your production redirect URL and authentication URL, your production application ID and secret, and test with a production seller account.

  1. Register the redirect URL for your application in the Developer Console for the production environment. This public endpoint is where your application receives the authorization code from the authorization response after the seller authorizes your application.
  2. Build the authorization URL to sends the seller to Square authorization page where they can approve or deny your authorization request. This URL uses the production base URL (https://connect.squareup.com/oauth2/authorize) of the Authorize endpoint and includes your production application ID and the required permissions you're requesting from sellers.
  3. Get the access token and refresh token using the ObtainToken endpoint, the authorization code from the authorization response, and your production application ID and secret. An OAuth access token obtained using the code flow expires after 30 days, so you'll need to call ObtainToken later to get a new access token before it expires.

For more information, see Create the Redirect URL and Square Authorization Page URL, Receive Seller Authorization and Manage Seller OAuth Tokens, and Refresh, Revoke, and Limit the Scope of OAuth Tokens.

Some values used for OAuth differ between the production and Sandbox environments:

Production Sandbox

Protocol and domain

HTTPs is required; localhost isn't supported

Example: https://my-server:3000/callback

HTTP and localhost supported

Example: http://localhost:3000/callback

Authorize endpoint base URLhttps://connect.squareup.com/oauth2/authorizehttps://connect.squareupsandbox.com/oauth2/authorize

session parameter

session=false is required

Example: https://connect.squareup.com/v2/authorize?client_id={YOUR_APP_ID}&scope={PERMISSIONS_LIST}&session=false&state={RANDOM_STRING}

Only session=true (default) is supported

Application ID (also called client ID)

Prefixed with "sq0idp"

Example: sq0idb-LB1Rr4Iob0hGXvAwlv7HIP

Prefixed with "sandbox-sq0idp"

Example: sandbox-sq0idb-ioiyW39PwreFzgXoGyLtYq

Application secret (also called client secret)

Prefixed with "sq0csp"

Example: sq0csp-iiWQf_JFiv8Z5t__7T6y2CBALOEtEVE9k_cLotSY0F4

Prefixed with "sandbox-sq0csp"

Example: sandbox-sq0csb-desU-1-gr4wkeC2P2JP1Bxi5WrOgS4m6elVPG5ZffVL

Link to section

1. Set the redirect URL and get your application credentials

  1. Sign in to the Developer Console and open an application.

  2. At the top of the page, set the environment toggle to Sandbox.

  3. In the left pane, choose OAuth.

  4. Register your redirect URL:

    1. In the Redirect URL box, choose Update.
    2. Enter http://localhost:8000/callback.php (the callback endpoint for this sample application), and then choose Confirm.

    Important

    Using HTTP and localhost is supported for testing in Sandbox. For in-production applications, you must provide the HTTPS URL to your actual web server.

  5. Copy your application ID and secret:

    1. In the Application ID box, copy the application ID.
    2. In the Application Secret box, choose Show, and then copy the application secret.
Link to section

2. Install the PHP project template

For this walkthrough, you set up a simple web server that responds to a seller's authorization and gets an OAuth access token and refresh token.

  1. Install Composer and the sample dependencies to the local directory:

    1. In the local directory, open a command line and change to the /php subdirectory.
    2. Install Composer.
    3. Run the following command line to install the Square PHP SDK and other project dependencies:
      composer install
  2. Note the following key sample files:

    • request_token.php - A web page that displays an Authorize button to a seller. When the seller clicks the button, they're directed to the Square-hosted authorization page (using the authorization URL) where they can authorize your application.
    • callback.php - The redirect URL target that receives the authorization response and gets the OAuth tokens. After a seller authorizes your application, Square sends the authorization code to this endpoint, which then sends the application ID, application secret, and authorization code to the ObtainToken endpoint to get the OAuth access token and refresh token.
    • messages.php - Contains helper functions to access tokens and display error messages.

    Note

    On a Mac, file names starting with "." are hidden by default. To view hidden files in Terminal, use the ls -a command. To view hidden files in Finder, hold down Cmd + Shift + .(period).

  3. Configure the sample to use the Sandbox environment with your Sandbox application credentials:

    1. Make a copy of the .env.example file and rename it to .env.
    2. In the .env file, replace the placeholder values:
      • Replace your-environment with sandbox.
      • Replace your-application-id with your Sandbox application ID.
      • Replace your-application-secret with your Sandbox application secret.
  4. Run the following command to start the server:

    php -S localhost:8000
Link to section

3. Set up a seller test account and simulate the seller authorization

Your Square developer account comes with a default test account in the Sandbox. To simulate third-party application development, you need to create a second Sandbox account to act as a seller account.

In the Sandbox, the seller must be signed in to see the Square authorization page. Sign in to a seller test account by opening the Square Dashboard. In production, you can also control whether you force the seller to sign in explicitly by setting the session parameter to false (recommended).

Create a Sandbox account as a seller test account:

  1. Open the Developer Console.

  2. In the left pane, choose Sandbox test accounts.

  3. Choose New sandbox test account.

  4. In the Account Name box, enter Seller Test Account.

  5. In the Country box, choose any country.

  6. Clear the Automatically create authorizations for all my current apps checkbox.

  7. Choose Create.

    The Developer Console should look like the following:

    A screenshot showing what the Developer Console should look like after creating a new Sandbox test account.

  8. Choose Open in Square Dashboard for the new seller account. This opens the Square Dashboard for the account. Leave this page open in your browser.

  9. Open a new browser window and enter http://localhost:8000/request_token.php. You should see the following:

    A graphic showing the Authorize button.

    Important

    When testing in the Sandbox, you need to have a Square Dashboard open so the request_token.php code can send the request to it. You're simulating what the seller does in a production environment when they receive the authorization request and approve it.

  10. Choose the Authorize button.

  11. The page shows the authorization request for the new account. Choose Allow.

  12. The page shows that the authorization succeeded. The callback.php code got the authorization code from the seller's authorization, submitted the OAuth API ObtainToken call, and received the access token and refresh token.

    The authorization returns the following parameters:

    • state is the CSRF token your application passed in the state parameter for the Square authorization page. Use this value to verify that this is a valid request.
    • response_type is code. This indicates that an authorization code was returned.
    • code is the authorization code. Use this value when you call ObtainToken to get the access token and refresh token for the seller account. The value you provide to the ObtainToken call must match this value exactly.

For more information about the values returned in the seller authorization, see Receive Seller Authorization and Manage Seller OAuth Tokens.

You've now completed the OAuth process by obtaining the access token and refresh token for the test seller. The next steps show you how to use the access token and refresh token.

Link to section

4. Use the seller access token to call a Square API on behalf of the seller

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

  1. Go to API Explorer.

  2. Make sure Sandbox is selected at the top of the page, 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:

    • For amount_money, choose Add, enter 10000 for the amount, and then set the currency to the country you selected 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.

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

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

    • For app_fee_money, choose Add, enter 500 for amount, and then set the currency to your Square account country. A screenshot showing a CreatePayment request in API Explorer.

  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 ListPayments or you can get it directly using GetPayment. A screenshot showing the details of a response when a request is made using API Explorer.

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

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

  6. In the Sandbox Square Dashboard, choose Transactions in the left pane, and then choose the most recent transaction. The transaction details appear in a pane on the right.

A screenshot showing the details of a transaction in the Square Dashboard.

You see the $100 payment that was completed and the $5 application fee that your application collected and credited to your Sandbox developer account.

In the Other row, you see the $5.00 application fee from the CreatePayment call.

Link to section

5. Refresh the access token

When you've completed the previous step, you know that you can use the seller's OAuth access token to make API calls on their behalf. Your application should be able to refresh the access token before it expires. To keep this simple, use API Explorer to call the ObtainToken endpoint to refresh the seller token.

  1. Go to Square API Explorer.
  2. Make sure Sandbox is selected at the top of the page, paste the seller's access token in the Access token box, and then choose Save.
  3. Set the following parameters in the body:
    • For client_id, enter your application's Sandbox application ID.
    • For client_secret, enter your application's Sandbox application secret.
    • For grant_type, enter refresh_token.
    • For refresh_token, enter the seller's OAuth refresh token.
  4. Choose Run Request. The Response box displays a 200 response code and returns information about the new access token. Use this new access token to call the Square APIs on the seller's behalf.
Link to section

6. Revoke the access token

Your application should enable sellers to revoke the access token if they choose to. To keep this simple, use API Explorer to call the RevokeToken endpoint to revoke the seller token.

  1. Go to API Explorer.
  2. Make sure Sandbox is selected at the top of the page, paste the seller's access token into the Access token box, and then choose Save.
  3. Set the following parameters in the body:
    • For client_secret, enter your application's Sandbox application secret.
    • For access_token, enter the seller's access token.
    • For client_id, enter your application's Sandbox application ID.
  4. Choose Run Request. The Response box displays a 200 response code and returns "success":true.
Link to section

Create a link to the Square authorization page

The request_token.php code creates the URL link to the Square authorization page that you give to the seller so they can authorize your application. The code uses your developer application ID and secret and requests several permissions that are then incorporated into the URL. The permissions in the list are separated by a URL-encoded space (%20 or +).

The md5 function generates a random string that is stored in the session cookie and passed in the state parameter. The state parameter is returned by the Square authorization page. The callback compares the state value with the string stored in the session cookie and rejects the request if they don't match. The state parameter helps protect against cross-site request forgery (CSRF).

The session parameter is omitted because the Sandbox only supports a default setting of true. For production, this value should be false.

The {APPLICATION_ID} placeholder value for the client_id parameter is the Sandbox application ID you got from the Developer Console for your application.

The completed URL looks like the following. For a complete review of the parameters used in the URL, see Create the Redirect URL and Square Authorization Page URL.

https://squareupsandbox.com/oauth2/authorize?client_id={APPLICATION_ID}&scope=ITEMS_READ+MERCHANT_PROFILE_READ+PAYMENTS_WRITE_ADDITIONAL_RECIPIENTS+PAYMENTS_WRITE+PAYMENTS_READ&state=0499178ad6fdf1946bcb184aeae355cdbf90fed7faf60dde36e35de6d2d91b09
Link to section

Exchange the authorization code for an OAuth token

The callback.php code parses the query string that is returned after the seller allows (or denies) your application the requested permissions the Square authorization page redirects to the redirect URL. This is the URL that you set on the OAuth page of your application in the Developer Console. The POST request on your callback page includes a query string with an authorization code or a denial error.

The code block parses the query string. If there's an authorization code, the obtainOAuthToken function is called to exchange the authorization code for OAuth tokens.

The code block performs three functions:

  • Validates the state parameter - The first if statement checks the state parameter against the value stored in the cookie. If the values don't match, the displayStateError function is called to display a message indicating that the state check failed and this block is exited.
  • Checks for authorization - If the state check succeeds, the block checks for the response_type parameter. If the response_type parameter value is code, an authorization code is returned in the code parameter.
  • Calls ObtainToken to get the access and refresh tokens - The obtainOAuthToken function takes the authorization code and calls the ObtainToken endpoint to get the OAuth access token and refresh token. The ObtainToken endpoint takes your application ID, your application secret, a grant_type of authorization_code, and the authorization code. For this walkthrough, these 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 Best Practices.

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

Link to section

See also