Applies to: OAuth API
Learn how to create an application that receives the seller's OAuth authorization and manages the OAuth tokens.
The next stage in the OAuth authorization process is where the seller uses the authorization URL you provided and logs in to their Square seller account. Square shows an authorization page with the requested permissions and scope. After the seller accepts or denies the permissions, the page sends a GET response to the redirect URL you specified for your application.
The application that's at the redirect URL endpoint must do the following:
- Parse the parameters that are returned in the seller authorization response.
- Use the authorization code in the response to call the OAuth API to obtain the seller's access and refresh tokens.
- Manage and use the access and refresh tokens securely.
- Encrypt the access and refresh tokens and store them securely.
- If your application is using the PKCE flow, you must retain the
code_verifier
that was used to obtain the authorization code. You submit thecode_verifier
along with the authorization code when callingObtainToken
. - Verify that the token used for each API call is valid.
- Refresh the access token in a timely manner.
- If your application is using the PKCE flow, you must use the single-use refresh token within 90 days.
- Provide the seller with the ability to revoke the access and refresh tokens.
- Show the permissions granted by the access token to the seller and enable them to manage authorization.
- Ensure that API calls made with the seller's tokens can handle token-based errors appropriately.
The seller can approve or deny your authorization request. Your web page or application endpoint that receives the authorization redirect must handle the Allow
or Deny
responses in the query string.
If the seller chooses Allow
, a production response URL looks like the following:
https://example.com/callback.php?code=sq0cgb-xJPZ8rwCk7KfapZz815Grw&response_type=code&state=jf0weoif3dfsk04imofpdgmlksadfwmvmf4oip
The URL returns the following parameters:
state
is the CSRF token your application passed in thestate
parameter for the Square authorization page. Use this value to verify that this is a valid request.response_type
iscode
. This indicates that an authorization code was returned.code
is the authorization code. Use this value when you callObtainToken
to get the access token and refresh token for the seller account. The value you provide to theObtainToken
call must match this value exactly. If you're using the PKCE flow, you must also include thecode_verifier
in the request toObtainToken
.
If the seller chooses Deny
, or there's an error, a production response URL looks like the following:
http://example.com/callback.php?error=access_denied&error_description=user_denied&state=59192b1e9f3c448569e0008b6856da50#
The URL returns the following parameters:
state
is the CSRF token your application passed in thestate
parameter for the Square authorization page.error
is the error type. Theaccess_denied
value indicates that the seller denied the authorization request.error_description
provides more details about the error.
If the error is access_denied
, you need to contact the seller to determine the reason they denied authorization. Your application should show a user-friendly page to tell the seller that authorization failed.
If the seller authorizes your set of permissions, the Authorize
endpoint sends a response with an authorization code to your redirect URL. You must use the authorization code (code
) to call the ObtainToken endpoint to get the seller's OAuth access token and refresh token. The authorization code expires 5 minutes after the Square authorization page generates the code. The value you include in the ObtainToken
call must exactly match the authorization code you received. If the code expires before you get an access token, the seller must go to the Square authorization page again to create another authorization code.
The request format to call ObtainToken
differ between the code flow and PKCE flow.
An ObtainToken
request using the code flow looks like the following:
curl https://connect.squareupsandbox.com/oauth2/token \
-X POST \
-H 'Square-Version: 2021-05-13' \
-H 'Content-Type: application/json' \
-d '{
"client_id": "<YOUR_APPLICATION_ID>",
"client_secret": "<YOUR_APPLICATION_SECRET>",
"code": "<THE_AUTHORIZATION_CODE_YOU_WERE_GIVEN>",
"grant_type": "authorization_code"
}'
A response looks similar to the following:
{
“access_token”: “<access_token>“,
“token_type”: “bearer”,
“expires_at”: “2022-06-03T22:19:44Z”,
“merchant_id”: “<merchant_id>“,
“refresh_token”: “<refresh_token>“,
“short_lived”: false
}
An ObtainToken
request using the PKCE flow looks like the following:
curl https://connect.squareup.com/oauth2/token \
-X POST \
-H 'Square-Version: 2022-04-20' \
-H 'Content-Type: application/json' \
-d '{
"client_id": "<YOUR_APPLICATION_ID>",
"grant_type": "authorization_code",
"redirect_uri": "<THE REDIRECT URL>",
"code": "<THE_AUTHORIZATION_CODE_YOU_WERE_GIVEN>",
"code_verifier":"<THE CODE_VERIFIER YOU CREATED>"
}'
A response looks similar to the following:
{
“access_token”: “<access_token>“,
“token_type”: “bearer”,
“expires_at”: “2022-06-03T22:19:44Z”,
“merchant_id”: “<merchant_id>“,
“refresh_token”: “<refresh_token>“,
“short_lived”: false
“refresh_token_expires_at”: “2022-08-03T22:19:44Z”
}
Refresh tokens returns by the PKCE flow can only be used once and expire in 90 days.
When you have successfully received the seller's access token and refresh token, you must store the values securely.
OAuth access tokens, refresh tokens, and the application secret all have privileged access (or potential to get privileged access) to seller resources. You should use them in a secure environment and protect access to them. Follow these best practices:
- OAuth operations that use a private client should be performed on a secure application server. This includes, for example, calls to
ObtainToken
to obtain the original OAuth access token and refresh token, subsequent calls to get a new OAuth access token using a refresh token, generating and validating thestate
parameter, encrypting the tokens and application secret, and revoking a token. - Never store the application secret, access token, or refresh token in a mobile application or on any public client. Use the PKCE flow for these scenarios.
- OAuth access tokens and refresh tokens should be stored encrypted in a secure database or keychain. Your application should use a strong encryption standard such as AES. The production encryption keys shouldn't be accessible to database administrators, business analysts, developers, or anyone who doesn't need them. The tokens that these keys protect can be used to perform actions on behalf of the seller and should be guarded appropriately. The encryption keys shouldn't be stored in source control and should only be accessible by server administrators.
- When you request authorization from a seller, record the permissions that you request. After the seller authorizes your request and you receive the authorization code, you cannot find what permissions are associated with the code or the access token you receive when you call
ObtainToken
.
Warning
Never store your credentials or access tokens in your version control system. The .env file is included in the .gitignore project to help prevent uploading confidential information.
You should never put the application secret in your source code. Instead, encrypt the secret and use an environment variable to reference the secret in your application.
Submitting an API request without a valid OAuth access token results in a poor experience for sellers and potentially their customers. In some cases, a seller might be prevented from taking payments. An OAuth access token can be invalid for two main reasons: expiration and revocation.
Your application should automatically renew OAuth access tokens every 7 days or less, regardless of whether the seller is actively interacting with your application. For more information about refreshing an access token, see OAuth Best Practices.
An OAuth access token expires after 30 days. If your application doesn't get a new access token, it cannot make calls on behalf of the seller. This can happen if your application doesn't have a token refresh process, but it can also happen if the call to ObtainToken fails and your application doesn't detect the failure and doesn't retry.
To ensure that tokens remain in a valid state, Square requires all partner applications to renew at a frequent interval.
Square recommends that your application automatically renew OAuth access tokens every 7 days or less, regardless of whether the seller is actively interacting with your application. Renewing every 7 days or less provides sufficient time to discover and resolve errors. If your application only attempts to refresh tokens near the 30-day expiration date, it increases the risk of missing a failed token refresh and creating a poor experience for sellers or their customers.
Your application should check tokens when they're retrieved from your database to see whether they're older than 8 days. If this check fails, it should generate a notification (paging or other alerting mechanism) so that you can address any issues with your renewal logic. Silent token renewal failures result in breaking your application integration and potentially cause an outage for your sellers or their customers.
Refresh tokens used with PKCE are single-use tokens and expire in 90 days.
An OAuth access token can be revoked in two ways:
- The seller can disconnect the application through My Applications in the Square Dashboard. Disconnecting an application calls RevokeToken to revoke all OAuth tokens for the seller.
- Your application can call
RevokeToken
to revoke a particular OAuth token or all OAuth tokens for a seller account.
To ensure that a token is valid and not revoked, call ListLocations and check the response to confirm validity.
Your application must provide a mechanism for sellers to view the status of their OAuth tokens and manage the authorization for your application. Typically, this is done with a settings/configuration dashboard in your application.
Your application must accurately show the seller's access token status with Square. Access token status must always be accurate and indicate the correct state of the access token (valid, expired, or revoked). Using the recommendation method in the previous section, your application can check the validity of the token by calling ListLocations and checking the response.
Your application must let the seller revoke the access token. You revoke access tokens using RevokeToken. For more information about revoking an access token, see Refresh, Revoke, and Limit the Scope of OAuth Tokens.
When your application uses an access token to call a Square API, OAuth-related errors can occur if a token is expired, is revoked, or has insufficient scope (unauthorized). Your application should handle these error codes and display a customer-friendly message that clearly communicates the error to the seller, their customer, or both. Errors include:
ACCESS_TOKEN_EXPIRED
ACCESS_TOKEN_REVOKED
UNAUTHORIZED
Square retains expired access tokens for a limited time. During this time, the Square API returns the ACCESS_TOKEN_EXPIRED
error. After that time, the Square API returns an UNAUTHORIZED
error.
Square API calls that return the UNAUTHORIZED
error aren't cases of insufficient scope. Square API calls with insufficient scope return a 403 FORBIDDEN
error.