OAuth with PHP Part Two: refreshing & revoking tokens

Part 2 on using OAuth tokens with PHP

This blog post contains information that is out of date and uses deprecated endpoints. Please visit migrating to refresh tokens for information on upgrading. To just implement the latest OAuth, you can follow our guide here.

This is a follow up to part 1 that talks about creating access tokens from authorization codes.

At the end of the first part of our PHP journey with OAuth, we had two scripts: an index.php that would begin the OAuth process and a callback.php that would accept the result from Square and use the provided authorization code to create an access token that your application can use to use Square’s APIs on a merchant’s behalf.

Your newly minted access token will work great for about a month, but then your token will expire and your app won’t be able to do anything with Square’s APIs until the merchant reauthorizes the application. That isn’t very convenient for your users, so luckily there is a way to programatically refresh your OAuth credentials without requiring your end users to authorize your application. Refreshing your tokens will only work if your permissions do not change your application’s permissions. Any time you want to change the scopes available to your application, you must reauthenticate with the merchant.

Expiration dates

When you exchange an authorization code for an access token, you’ll get back a json response like this:

{ 
  "access_token": "sq0atp-XXXX",
  "token_type": "bearer",
  "expires_at": "2017-12-22T19:11:30Z",
  "merchant_id": "XXXXXXXXX"
}

You’ll want to keep track of that expires_at time, so that you will be able to refresh the token in time. You can even refresh a token after it is expired, as long as you do it within 15 days of the expiration date.

The refresh endpoint

The endpoint to refresh your access tokens is a little different than most of our endpoints because you need to authorize with your client_secret instead of the access_token in the header. Here is what it looks like with PHP using file_get_contents code:

//Refresh the token
$url = "[https://connect.squareup.com/oauth2/clients/$client_id/access-token/renew](https://connect.squareup.com/oauth2/clients/$client_id/access-token/renew)";
$data = array(
    'access_token' => $access_token
 );

$options = array(
    'http' => array(
        'header'  => "Content-type: application/json\r\n".  
        "Authorization: Client $client_secret\r\n",
        'method'  => 'POST',
        'content' => json_encode($data)
    )
);

var_dump($options);
$context  = stream_context_create($options);
$result = file_get_contents($url, false, $context);

echo "Result from /oauth2/clients/$client_id/access-token/renew:";
var_dump($result);

An important thing to note is that if you have everything correct, but provide an invalid access_token in your request body, you will get a 404 response because the access token cannot be found.

If everything goes well, you should get a response similar to when you first got your access token, with the refresh date now a month after the date you refreshed:

{
  "access_token": "sq0atp-XXXXXXX",
  "token_type": "bearer",
  "expires_at": "2017-12-22T19:49:36Z",
  "merchant_id": "XXXXXXXXX"
}

That is all you need to do to refresh your access tokens! Now your application will be able to continue making requests on other merchants’ behalf.

The revoke endpoint

Revoking an access token removes any access it has to Square merchant accounts. This endpoint is accessed similarly to the renew endpoint, with the client_secret in the header:

//Revoke the token
$url = "[https://connect.squareup.com/oauth2/revoke](https://connect.squareup.com/oauth2/revoke)";
$data = array(
    'access_token' => $access_token,
    'client_id' => $client_id
 );

$options = array(
    'http' => array(
        'header'  => "Content-type: application/json\r\n".  
        "Authorization: Client $client_secret\r\n",
        'method'  => 'POST',
        'content' => json_encode($data)
    )
);

var_dump($options);
$context  = stream_context_create($options);
$result = file_get_contents($url, false, $context);

echo "Result from /oauth2/revoke:";
var_dump($result);

If your request is successful, then the API will return the following response:

{
  "success": true
}

Now the access token that you had created is invalidated, and cannot be used, or refreshed. Your end users will need to authorize your application again in order for your application to be able to use Square’s APIs on their behalf.

The Code

To simplify everything, I’ve included all of the code (including the authorization from part 1) into a single page that will redirect you to Square, create an access token, renew the token and then revoke it all in one go.

<pre>
<?php 
$client_id = 'sq0idp-xxx';
$client_secret = 'sq0csp--xxxx';
$redirect_uri= "http://localhost:8080/callback.php";
$authorization_code = $_GET['code'];

if(!$authorization_code){
    die('something went wrong!');
}

$url = 'https://connect.squareup.com/oauth2/token';
$data = array(
    'client_id' => $client_id,
    'client_secret' => $client_secret,
    'redirect_uri' => $redirect_uri,
     'code' => $authorization_code
 );

$options = array(
    'http' => array(
        'header'  => "Content-type: application/json\r\n",
        'method'  => 'POST',
        'content' => json_encode($data)
    )
);
$context  = stream_context_create($options);
$result = file_get_contents($url, false, $context);

echo "Result from /oauth2/token:<br>";
var_dump($result);

$access_token = json_decode($result)->access_token;


//Refresh the token
$url = "https://connect.squareup.com/oauth2/clients/$client_id/access-token/renew";
$data = array(
    'access_token' => $access_token
 );

$options = array(
    'http' => array(
        'header'  => "Content-type: application/json\r\n".  
        "Authorization: Client $client_secret\r\n",
        'method'  => 'POST',
        'content' => json_encode($data)
    )
);

$context  = stream_context_create($options);
$result = file_get_contents($url, false, $context);

echo "Result from /oauth2/clients/$client_id/access-token/renew:";
var_dump($result);

//Revoke the token
$url = "https://connect.squareup.com/oauth2/revoke";
$data = array(
    'access_token' => $access_token,
    'client_id' => $client_id
 );

$options = array(
    'http' => array(
        'header'  => "Content-type: application/json\r\n".  
        "Authorization: Client $client_secret\r\n",
        'method'  => 'POST',
        'content' => json_encode($data)
    )
);

$context  = stream_context_create($options);
$result = file_get_contents($url, false, $context);

echo "Result from /oauth2/revoke:";
var_dump($result);
?>
<a href="https://connect.squareup.com/oauth2/authorize?client_id=<?php echo $client_id;?>">Authorize App</a>

Now you should have a complete example in PHP to do everything you can do with OAuth. If you have any questions, leave a comment on this post, and of course take a look at the official Square OAuth documentation.

Table Of Contents
View More Articles ›