Jack Trowbridge
Jack Trowbridge

Reputation: 3251

Google API Quering for Refresh Token

I've written a script that successfully queries Google for an access token using the PHP SDK.

My code,

require_once('_/libs/google/apiclient/autoload.php');

$client_id = '<MY_ID>';
$client_secret = '<MY_SECRET>';
$redirect_uri = '<REDIRECT_URL>';

// Config my apps information 
$client = new Google_Client();
$client->setClientId($client_id);
$client->setClientSecret($client_secret);
$client->setRedirectUri($redirect_uri);
$client->addScope("https://mail.google.com/");

// When google redirects with code swap for access token
if (isset($_GET['code'])) {
    $client->authenticate($_GET['code']);

    <------------- Try to get both tokens ----------------->
    $_SESSION['access_token'] = $client->getAccessToken();
    $_SESSION['refresh_token'] = $client->getRefreshToken();


    $redirect = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
    header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL));
}

Once I get the authentication code as shown above and query for the access token through getAccessToken(); it returns with the creation and expiry time.

However when I query for the refresh token through getRefreshToken(); it returns nothing when outputting it to the screen.

There was a similar question asked here

The problem seems to be letting Google know you need offline access however answers to that question aren't transferable to the PHP SDK.

Upvotes: 1

Views: 248

Answers (1)

Alex
Alex

Reputation: 5278

Although I was using JavaScript, I just went through this exact same issue. I solved it by adding the redirect_uri parameter to the initial token request call.

Here is my SO post and my solution: Google API - Oauth 2.0 Auth token flow

To clarify the flow, to get a refresh token you actually have to make a request to get a 'code' from Google (thus my parameter 'response_type': 'code'), and then you make another call with that code to get an access token and refresh token.

Upvotes: 1

Related Questions