Authenticating while running PHP at command line

2,546 views
Skip to first unread message

Sondra Russell

unread,
Feb 13, 2012, 11:28:13 PM2/13/12
to google-api...@googlegroups.com
Team,

I'm trying to run a PHP script at the command line and I'm really struggling with authentication.  In attempting to modify the sample script for CLI (i.e. getting rid of the references to sessions), I've done this:

#!/usr/bin/php5
<?php
require_once 'google-api-php-client/src/apiClient.php';

$client = new apiClient();
$client->setClientId('[client id]);
$client->setClientSecret('[client secret]');
$client->setRedirectUri('urn:ietf:wg:oauth:2.0:oob');

$client->authenticate();
echo $client->getAccessToken();

?>

But I get nothing.   No error code, no JSON string to decode.  Nothing.  What am I missing?

-S.

Chirag Shah

unread,
Feb 13, 2012, 11:39:05 PM2/13/12
to google-api...@googlegroups.com

Sondra Russell

unread,
Feb 14, 2012, 12:14:17 AM2/14/12
to google-api-php-client
Thanks for this!! So, my challenge is that I want to run the script
at command line so that i can automate a daily query run by cron job.
Thus the:

print "Please visit:\n$authUrl\n\n";
print "Please enter the auth code:\n";

part ain't gonna work so well. Any suggestions?

Thanks,
-S.



On Feb 13, 11:39 pm, Chirag Shah <chir...@google.com> wrote:
> Hey Sondra,
>
> You will have better luck with this example:http://code.google.com/p/google-api-php-client/source/browse/trunk/te...

Chirag Shah

unread,
Feb 14, 2012, 12:34:11 AM2/14/12
to google-api...@googlegroups.com
That snippet asks the user to grant access to your application, so it needs to be run at least once. If the authenticated user in the context of the cron job is always the same, you can do the following:
  • Run that script once and save the result of $client->getAccessToken() in a secure place.
  • When the cron job runs, simply fetch the saved token and call $client->setAccessToken($token).
  • The cron job can ignore the other auth bits in the script. It only needs to worry about setAccessToken.
The client library defaults to requesting offline access, so you don't need to worry about the refresh token expiring unless the user installs your application.

-Chirag

Sondra Russell

unread,
Feb 14, 2012, 7:34:12 PM2/14/12
to google-api-php-client
Okay, that's awesome. I've PARTIALLY gotten this to work. I can get
it to work really consistently with the apiPlusService, but it always
returns a 401 with apiAnalyticsService. Any idea why?

(see code below)

Again, THANK YOU so much for your help with this!!
-S.



//require the code to help you authenticate and access the api
require_once 'google-api-php-client/src/apiClient.php';

//require the code specific to the API service (ie. adsense,
analytics, google+, etc)
require_once 'google-api-php-client/src/contrib/
apiAnalyticsService.php';
require_once 'google-api-php-client/src/contrib/apiPlusService.php';

// Visit https://code.google.com/apis/console to generate your
oauth2_client_id,
//oauth2_client_secret, and to register your oauth2_redirect_uri.
//For these purposes, you should set it up as if it was an "installed
application"
$client = new apiClient();
$client->setClientId('[client id]');
$client->setClientSecret(''[client secret]');
$client->setRedirectUri('urn:ietf:wg:oauth:2.0:oob');

$service = new apiAnalyticsService($client);
$plus = new apiPlusService($client);

//modify this based on which type of api you want to dig into.
//look here: http://code.google.com/apis/gdata/faq.html#AuthScopes
for help
$client->setScopes(array(
'https://www.googleapis.com/auth/plus.me',
'https://www.googleapis.com/auth/analytics.readonly'
));
//check to see if there's a saved token. The first time you run this
script, there won't be one
$token = file_get_contents("token.txt");

//if there isn't a token (as will happen the first time you run the
script
if (!($token)) {

defined('STDIN') or define('STDIN', fopen('php://stdin', 'r'));
$authUrl = $client->createAuthUrl();

print "Please visit:\n$authUrl\n\n";
print "Please enter the auth code:\n";
$authCode = trim(fgets(STDIN));

$_GET['code'] = $authCode;
$token = $client->authenticate();
$write_token = file_put_contents("token.txt",$token);

//if there is a token
} else {
//test to see if the token has expired
$decoded_token = json_decode($token);
if (time() > ( $decoded_token->{'created'} + $decoded_token-
>{'expires_in'})) {
$client->refreshToken($decoded_token->{'refresh_token'});
$token = $client->getAccessToken();
}
$decoded_token = json_decode($token);

//now that we have a good token happening...
$client->setAccessToken($token);

//so this is working just beautifully
$activities = $plus->activities->listActivities('me', 'public');
print_r($activities);

//this is returning error message: "Error calling GET
https://www.googleapis.com/analytics/v3/management/accounts: (401)
Invalid Credentials"
$accounts = $service->management_accounts->listManagementAccounts();
print_r($accounts);

}

Chirag Shah

unread,
Feb 14, 2012, 7:44:49 PM2/14/12
to google-api...@googlegroups.com
Not a problem! Do you see anything related to analytics in the OAuth permission screen?

The client library will do this for you before making an api request. No need to refresh the token yourself.

You can save the updated token by calling $token = $client->getAccessToken(); after making an api request.

 
               $token = $client->getAccessToken();
       }
       $decoded_token = json_decode($token);

       //now that we have a good token happening...
       $client->setAccessToken($token);

       //so this is working just beautifully
       $activities = $plus->activities->listActivities('me', 'public');
       print_r($activities);

       //this is returning error message: "Error calling GET
https://www.googleapis.com/analytics/v3/management/accounts: (401)
Invalid Credentials"
       $accounts = $service->management_accounts->listManagementAccounts();
       print_r($accounts);
Regenerate your token with only the scope https://www.googleapis.com/auth/analytics.readonly and see if that helps.  You can remove the stuff related to the plus api if you don't need it.


}

Reply all
Reply to author
Forward
0 new messages