Examples

Renew OAuth Token

Automatically renew OAuth tokens to keep them from expiring.

Server Side
Client Side

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

Before you start

  • The example code below uses a configuration file to define important application information. See [Step X](link to step X) in the OAuth Setup guide for more information.
  • We are using PHP version 5.4 or later to revoke the OAuth token. We also have
    the Square Connect PHP SDK installed. Square SDKs are also available in other programming languages.

Renew an OAuth token

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.

Add a function that creates a renew token request body:

// Define constants
if (!defined(_SQ_DOMAIN)) {
    define('_SQ_DOMAIN', "connect.squareup.com") ;
}
if (!defined(_SQ_APP_ID)) {
    define('_SQ_APP_ID', "{REPLACE_ME}") ;
}
if (!defined(_SQ_APP_SECRET)) {
    define('_SQ_APP_SECRET', "{REPLACE_ME}") ;
}

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

  # Headers to provide to OAuth API endpoints.
  $requestHeaders = array(
    "Content-Type: application/json",
    "Accept: application/json",
    'Authorization: Client '. _SQ_APP_SECRET
  );

  $oauthRequestBody = array(
      'access_token' => $accessToken,
  );
  $encodedData = json_encode($oauthRequestBody);
  array_push($requestHeaders, "Content-Length: " . strlen($encodedData)) ;

  $curlHandle = curl_init(
    _SQ_DOMAIN .
    '/oauth2/clients/' .
    _SQ_APP_ID .
    '/access-token/renew'
  );
  curl_setopt($curlHandle, CURLOPT_POSTFIELDS, $encodedData);
  curl_setopt($curlHandle, CURLOPT_CUSTOMREQUEST, "POST") ;
  curl_setopt($curlHandle, CURLOPT_HTTPHEADER, $requestHeaders) ;
  curl_setopt($curlHandle, CURLOPT_RETURNTRANSFER, 1) ;
  $response = json_decode(curl_exec($curlHandle), true) ;
  curl_close($curlHandle) ;

  # If the exchange failed, log the error and throw an exception.
  $accessToken = "Renew failed";
  if ($response == null || !is_array($response) || !array_key_exists('access_token', $response)) {
      error_log('Renew token failed');
      throw new Exception("Error Processing Request: Renew token failed!", 1);
  } else {
      $accessToken = $response['access_token'];
  }
  return $accessToken;
}

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.

Next
API Development 101 >

Ask for help on Stack Overflow or join our Slack channel