Google-api-php-client: Offline Access

Created on 25 Nov 2015  路  14Comments  路  Source: googleapis/google-api-php-client

Hi,
I'm using google-api-php-client and its working but I've an issue, I used this for google analytic reports and its working except one issue and that is after one hour google expire token i want that once i authorized i don't want to login again and again i want offline access for crone job as i want to full data at specific time.
Please help me regards this.
I've used $client->setAccessType("offline"); but its not working.

Thanks in advance :)

Most helpful comment

Hi @iftikhardirv
Most likely you just need to add $client->setApprovalPrompt('force');

A confusing aspect of the Offline Access parameter is it only returns a refresh token the first time it's authorized. After that, it won't request offline access any more unless you set approval_prompt to force

All 14 comments

Hi @iftikhardirv
Most likely you just need to add $client->setApprovalPrompt('force');

A confusing aspect of the Offline Access parameter is it only returns a refresh token the first time it's authorized. After that, it won't request offline access any more unless you set approval_prompt to force

Hi @bshaffer
I want to get analytic data once authorized just like we using other apis and they ask for some api key and secret key and they don't need to login again and again.

Yes, if you add approval_prompt=force, you'll receive a refresh token. The refresh token will allow you to request additional access tokens without the need for client authorization.

Have you tried using refresh tokens?

No i didn't how can i add refresh token ? bellow is my script

error_reporting(E_ALL);
ini_set('display_errors', 1);
// Load the Google API PHP Client Library.
require_once 'src/Google/autoload.php';
// Start a session to persist credentials.
session_start();
// Create the client object and set the authorization configuration
// from the client_secretes.json you downloaded from the developer console.
$client = new Google_Client();

$client->setAuthConfigFile('client_secrets.json');
$client->addScope(Google_Service_Analytics::ANALYTICS_READONLY);

$client->setAccessType("offline");

if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {

        // Set the access token on the client.
    //    $_SESSION['access_token'] = $client->refreshToken($_SESSION['access_token']);
        $client->setAccessToken($_SESSION['access_token']);
        // Create an authorized analytics service object.
        $analytics = new Google_Service_Analytics($client);
        // Get the first view (profile) id for the authorized user.
        $profile = getFirstProfileId($analytics, ACC_ID, ACTION_TYPE);
    } else {
        $redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . '/google-api/oauth2callback.php';
        //echo $redirect_uri;exit;
        header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
    }
$client->revokeToken();

You would handle this in your oauth2callback.php script. When you receive the access token in that script, do a var_dump on the response, and you'll see a refresh_token property. This should convince you the refresh token is being handled.

If the refresh token is indeed coming back with the response, then using $client->setAccessToken will automatically store the refresh token and use it to get a new access token, as long as $client->setAuthConfigFile is being called and client_secrets.json includes valid client credentials.

Your code looks great. But as I said in my first comment, you may want to add $client->setApprovalPrompt('force);`, because if you've already authorized the client, it won't send the refresh token again without this.

This is my oauth2callback.php file script

require_once 'src/Google/autoload.php';

// Start a session to persist credentials.
session_start();

// Create the client object and set the authorization configuration
// from the client_secrets.json you downloaded from the Developers Console.
$client = new Google_Client();
$client->setAuthConfigFile('client_secrets.json');
$client->setRedirectUri('http://' . $_SERVER['HTTP_HOST'] . '/google-api/oauth2callback.php');
$client->addScope(Google_Service_Analytics::ANALYTICS_READONLY);

// Handle authorization flow from the server.
if (! isset($_GET['code'])) {
  $auth_url = $client->createAuthUrl();
  header('Location: ' . filter_var($auth_url, FILTER_SANITIZE_URL));
} else {
  $client->authenticate($_GET['code']);
  $_SESSION['access_token'] = $client->getAccessToken();
  $redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . '/google-api';
  header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
}

Yes... do a var_dump where you have $client->getAccessToken(), do you see a refresh_token property? If not, then add $client->setApprovalPrompt('force); in your first file under setAccessType.

Also, get rid of the $client->createAuthUrl() line. This creates two different places where your authorization URL is generated, which makes it harder to know which one's being used.

i should remove the " if else " script ? or only remove the if part ?

Change this:

// Handle authorization flow from the server.
if (! isset($_GET['code'])) {
  $auth_url = $client->createAuthUrl();
  header('Location: ' . filter_var($auth_url, FILTER_SANITIZE_URL));
} else {
  $client->authenticate($_GET['code']);
  $_SESSION['access_token'] = $client->getAccessToken();
  $redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . '/google-api';
  header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
}

to this:

// Handle authorization flow from the server.
$client->authenticate($_GET['code']);
$_SESSION['access_token'] = $client->getAccessToken();
$redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . '/google-api';
header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));

The reason is you do not want your callback endpoint functioning as an authorize endpoint. Rather, it should throw an error ("code" not found) if a code is not supplied in the querystring.

I am curious, where did you find this implementation code? I would like to fix it so this doesn't happen to other users.

if I used bellow code and remove the authurl then it stuck me on oauth2callback.php

$client->authenticate($_GET['code']);
$_SESSION['access_token'] = $client->getAccessToken();
$redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . '/google-api';
header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));

I don't remembered now but I've used your old library. I've seen your new library you did lot of changes but I didn't updated yet.

Yes, it should send you back to the URL from before, this time with an access token. This is the expected behavior. If you access the page directly, the authenticate method should throw an error.

These instructions should work with both the old and new versions of this library.

Were you able to obtain a refresh token?

It didn't send me back to main url, it stuck on oauth2callback.php. I'm confused I want to access data using $client->setAuthConfigFile('client_secrets.json'); only. I don't want to direct me login page and after authenticating it give me access to data.
Also let me know is it possible to get google play statistics using this API ?

If you don't want to authorize a third party, you shouldn't be requesting the authorization URL. The code you've supplied is the code to use login page authentication

For Server-to-Server authentication, follow the instructions in these docs.

You can find information on the Google Play API here

Hope this will help:
$google_account = array(
'email' => 'service account email',
'key' => file_get_contents('../client_secrets.json'),
'profile' => projectId
);

    $client = new Google_Client();
    $client->setApplicationName('demomunch');
    $this->object = new Google_Service_Analytics($client);
    $scopes = array(Google_Service_Analytics::ANALYTICS_READONLY);
    $client->setScopes($scopes);
    $client->setAuthConfigFile('../client_secrets.json');
    if ($client->isAccessTokenExpired()) {
        $client->refreshTokenWithAssertion();
    }

Its working for me.

Was this page helpful?
0 / 5 - 0 ratings