OAUTH API: Code Cookbook

Renew OAuth Token

Automatically renew OAuth access tokens.

UI
Backend

Before you start
Permalink Get a link to this section

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

Obtain a new OAuth access token using a refresh token
Permalink Get a link to this section

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

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.

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();
}

Renew an OAuth access token (if using API version prior to 2019-03-13)
Permalink Get a link to this section

Warning

This article is deprecated. For developers using API version 2019-03-13 or later, see the preceding topic.

To renew an OAuth token, send a request to the RenewToken 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.

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.

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();
}