Code Cookbook

Renew OAuth Token

Automatically renew OAuth access tokens.

Server Side
Client Side
Languages Supported

OAuth tokens need to be renewed regularly because they expire after 30 days.

Before you start

To use the example code as written, you will need:

Obtain a new OAuth access token using a refresh token

OAuth access tokens expires 30 days after issued, but refresh tokens do not expire. When an access token expires, you send a request to the ObtainToken endpoint and include the refresh token in the request body. You also set the grant_type to "REFRESH_TOKEN".

Add a function that creates an ObtainToken request body using the refresh token:

// Renew OAuth access token using a refresh token.
function renewOAuthToken($refreshToken) {

  // Create an OAuth API client
  $oauthApi = new SquareConnect\Api\OAuthApi($defaultApiClient);
  $body = new \SquareConnect\Model\ObtainTokenRequest();

  // Set the POST body
  $body->setClientId($applicationId);
  $body->setClientSecret($applicationSecret);
  $body->setGrantType("refresh_token"); 
  $body->setRefreshToken($refreshToken);

  try {
      $result = $oauthApi->obtainToken($body);
  } catch (Exception $e) {
      error_log('Exception when calling OAuthApi->obtainToken: ' .  $e->getMessage());
      throw new Exception("Error Processing Request: Token renewal failed!", 1);
  }

  return $result->getAccessToken();
}

If your request succeeds, the ObtainToken endpoint returns a new access token. The renew function can be called at any point in your normal workflow to maintain the associated OAuth access token.

Renew an OAuth access token (if using API version prior to 2019-03-13)

To renew an OAuth token, send a request to the ObtainToken endpoint. OAuth tokens expire 30 days after they are issued. You can renew OAuth tokens any time from 24 hours after its issued to 15 days after they expire.

Add a function that creates a renew token request body:

// Renew OAuth token.
function renewOAuthToken($oauthToken) {

  // Create an OAuth API client
  $oauthApi = new SquareConnect\Api\OAuthApi($defaultApiClient);
  $body = new \SquareConnect\Model\RenewTokenRequest();

  // Set the POST body
  $body->setAccessToken($oauthToken);

  try {
      $result = $oauthApi->renewToken($body);
  } catch (Exception $e) {
      error_log 'Exception when calling OAuthApi->renewToken: ' . $e->getMessage();
      throw new Exception("Error Processing Request: Token renewal failed!", 1);
  }

  return $result->getAccessToken();
}

If your request succeeds, the RenewToken endpoint returns a renewed OAuth token. The renew function can be called at any point in your normal workflow to maintain the associated OAuth token.

Contact Developer Support, join our Slack channel, or ask for help on Stack Overflow