Error in Service Account Example

4,647 views
Skip to first unread message

andrew...@fcc.gov

unread,
Apr 12, 2012, 3:58:45 PM4/12/12
to google-api-php-client
I downloaded the latest file today and am attempting to run the the
service account example here -
http://code.google.com/p/google-api-php-client/source/browse/trunk/examples/prediction/serviceAccount.php

I get this error -
Fatal error: Call to undefined method
apiClient::setAssertionCredentials() in Google_Analytics_API\index.php
on line 44

My index.php is the serviceAccount.php with include paths changed and
the key file, client id and service account name changed.

But that none of that seems to matter based on the error above.
Looking through the files pretty quickly that method doesn't exist
anywhere.

Any ideas? Am I missing some files? Did I get the wrong files? Again,
I downloaded the latest just today from here -
http://code.google.com/p/google-api-php-client/downloads/list

Any ideas???

Chirag Shah

unread,
Apr 12, 2012, 7:26:09 PM4/12/12
to google-api...@googlegroups.com
Hey Andrew,

The service account example/implementation is only available on trunk right now.
You will need to download the very latest version of the library on trunk from here:

I am working on sinning up a new release very soon, and posting it on the downloads page.

Thank you,
Chirag Shah

Andrew Wolfe

unread,
Apr 13, 2012, 9:34:02 AM4/13/12
to google-api...@googlegroups.com, chira...@gmail.com

Thanks! Got passed that and ran into something else.

Below is my file as is (minus the client_id, service_account_name and key_file of course).

You’ll see I haven’t really changed anything except the couple variables that need to be changed.

 

I am getting this error:

<br />
<b>Fatal error</b>:  Uncaught exception 'apiAuthException' with message 'Error refreshing the OAuth2 token, message: '{
  &quot;error&quot; : &quot;invalid_grant&quot;
}'' in E:\xampp\htdocs\Google_Analytics_API\google-api-php-client\src\auth\apiOAuth2.php:276
Stack trace:
#0 E:\xampp\htdocs\Google_Analytics_API\google-api-php-client\src\auth\apiOAuth2.php(253): apiOAuth2-&gt;refreshTokenRequest(Array)
#1 E:\xampp\htdocs\Google_Analytics_API\google-api-php-client\src\auth\apiOAuth2.php(206): apiOAuth2-&gt;refreshTokenWithAssertion()
#2 E:\xampp\htdocs\Google_Analytics_API\google-api-php-client\src\service\apiServiceResource.php(167): apiOAuth2-&gt;sign(Object(apiHttpRequest))
#3 E:\xampp\htdocs\Google_Analytics_API\google-api-php-client\src\contrib\apiPredictionService.php(134): apiServiceResource-&gt;__call('predict', Array)
#4 E:\xampp\htdocs\Google_Analytics_API\index_new.php(63): HostedmodelsServiceResource-&gt;predict('sample.language...', Object(Input))
#5 {main}
  thrown in <b>E:\xampp\htdocs\Google_Analytics_API\google-api-php-client\src\auth\apiOAuth2.php</b> on line <b>276</b><br />

 

 

 

<?php

/*

 * Copyright 2012 Google Inc.

 *

 * Licensed under the Apache License, Version 2.0 (the "License");

 * you may not use this file except in compliance with the License.

 * You may obtain a copy of the License at

 *

 *     http://www.apache.org/licenses/LICENSE-2.0

 *

 * Unless required by applicable law or agreed to in writing, software

 * distributed under the License is distributed on an "AS IS" BASIS,

 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

 * See the License for the specific language governing permissions and

 * limitations under the License.

 */

 

require_once 'google-api-php-client/src/apiClient.php';

require_once 'google-api-php-client/src/contrib/apiPredictionService.php';

 

// Set your client id, service account name, and the path to your private key.

// For more information about obtaining these keys, visit:

// https://developers.google.com/console/help/#service_accounts

const CLIENT_ID = 'client_id';

const SERVICE_ACCOUNT_NAME = 'service_account_name';

 

// Make sure you keep your key.p12 file in a secure location, and isn't

// readable by others.

const KEY_FILE = 'key_file';

 

$client = new apiClient();

$client->setApplicationName("Google Prediction Sample");

 

// Set your cached access token. Remember to replace $_SESSION with a

// real database or memcached.

session_start();

if (isset($_SESSION['token'])) {

 $client->setAccessToken($_SESSION['token']);

 print_r ($client);

}

 

// Load the key in PKCS 12 format (you need to download this from the

// Google API Console when the service account was created.

$key = file_get_contents(KEY_FILE);

$client->setAssertionCredentials(new apiAssertionCredentials(

  SERVICE_ACCOUNT_NAME,

  array('https://www.googleapis.com/auth/prediction'),

  $key)

);

 

$client->setClientId(CLIENT_ID);

$service = new apiPredictionService($client);

 

 

// Prediction logic:

$id = 'sample.languageid';

$predictionData = new InputInput();

$predictionData->setCsvInstance(array('Je suis fatigue'));

 

$input = new Input();

$input->setInput($predictionData);

 

$result = $service->hostedmodels->predict($id, $input);

print '<h2>Prediction Result:</h2><pre>' . print_r($result, true) . '</pre>';

 

// We're not done yet. Remember to update the cached access token.

// Remember to replace $_SESSION with a real database or memcached.

if ($client->getAccessToken()) {

  $_SESSION['token'] = $client->getAccessToken();

}

?>

 

Any help is appreciated. I am continuing to research.


Chirag Shah

unread,
Apr 13, 2012, 5:13:03 PM4/13/12
to Andrew Wolfe, google-api...@googlegroups.com
When you created your application in the Google API Console, did you select "Service account" as your application type?

Also, make sure you have the Google Prediction API service enabled in the Google API Console.

Andrew Wolfe

unread,
Apr 18, 2012, 8:35:14 AM4/18/12
to Chirag Shah, google-api...@googlegroups.com

Thanks Chirag.

I did NOT have the prediction API enabled.

 

After doing that it did work but after working yesterday I ran it again this morning and the same error occurred.

Does that make sense at all?

 

Fatal error: Uncaught exception 'apiAuthException' with message 'Error refreshing the OAuth2 token, message: '{ "error" : "invalid_grant" }'' in E:\xampp\htdocs\Google_Analytics_API\google-api-php-client\src\auth\apiOAuth2.php:276 Stack trace: #0 E:\xampp\htdocs\Google_Analytics_API\google-api-php-client\src\auth\apiOAuth2.php(253): apiOAuth2->refreshTokenRequest(Array) #1 E:\xampp\htdocs\Google_Analytics_API\google-api-php-client\src\auth\apiOAuth2.php(206): apiOAuth2->refreshTokenWithAssertion() #2 E:\xampp\htdocs\Google_Analytics_API\google-api-php-client\src\service\apiServiceResource.php(167): apiOAuth2->sign(Object(apiHttpRequest)) #3 E:\xampp\htdocs\Google_Analytics_API\google-api-php-client\src\contrib\apiPredictionService.php(134): apiServiceResource->__call('predict', Array) #4 E:\xampp\htdocs\Google_Analytics_API\index.php(62): HostedmodelsServiceResource->predict('sample.language...', Object(Input)) #5 {main} thrown in E:\xampp\htdocs\Google_Analytics_API\google-api-php-client\src\auth\apiOAuth2.php on line 276

 

 

 


Chirag Shah

unread,
Apr 26, 2012, 6:08:25 PM4/26/12
to google-api...@googlegroups.com, Chirag Shah
Hey Andrew,

Alessandro ran into the same issue.  It appears that openssl_sign's optional signature_alg parameter accepts a string in PHP 5.3.0, but wasn't patched into 5.2.

Would it be possible for you to upgrade to the stable version of PHP 5.3? (I'm assuming you're running a version of PHP lower than 5.3)

Thank you,
Chirag

Jimbo

unread,
Apr 29, 2012, 8:39:14 PM4/29/12
to google-api...@googlegroups.com
Hi Chirag,

Can everything posted in the thread also be used for the  Google Analytic API?

I have that working fine using the method based here:
http://www.codediesel.com/php/reading-google-analytics-data-from-php/

But this method seems very slow.
Thanks,
Jim


On Thursday, April 12, 2012 3:58:45 PM UTC-4,:

Andrew Wolfe

unread,
Apr 30, 2012, 4:50:32 PM4/30/12
to google-api...@googlegroups.com, Chirag Shah

Thanks Chirag.

 

I just checked and I am running 5.3.8.

Any other ideas?

 

Thanks,

Andrew

Cynthia

unread,
May 3, 2012, 5:35:02 AM5/3/12
to google-api...@googlegroups.com
Hi,

I have the same problem using a service account and oAuth (Fatal error: Uncaught exception 'apiAuthException' with message 'Error refreshing the OAuth2 token, message: '{ "error" : "invalid_grant" }''). At first I tried the Prediction example, but since after I turn that service on in the backend I get a message about having to sign up for the Cloud I wasn't sure if that was possibly the problem.

I switched to the Analytics service as follows and still receive the error:

$client->setAssertionCredentials(
    new apiAssertionCredentials(
        SERVICE_ACCOUNT_NAME,
        array('https://www.googleapis.com/auth/analytics'),
        $key
    )
);

$client->setClientId(CLIENT_ID);
$service = new apiAnalyticsService($client);

$optParams = array(
        'dimensions' => 'ga:date',
        'sort' => '-ga:date',
        'filters' => 'ga:pagePath==/');

$result = $service->data_ga->get(
    'ga:XXXXXX',
    '2012-01-01',
    '2012-01-15',
    urlencode('ga:pageviews,ga:uniquePageviews,ga:entrances,ga:exits'),
    $optParams);

print_r($result);


Any help would be great.

luxerama

unread,
May 3, 2012, 12:43:26 PM5/3/12
to google-api...@googlegroups.com

Cynthia

unread,
May 4, 2012, 3:59:40 AM5/4/12
to google-api...@googlegroups.com
Thank you! I missed that.

Tariq Bashir

unread,
May 16, 2012, 11:03:33 AM5/16/12
to google-api...@googlegroups.com, Chirag Shah
I am having the same issues as Andrew.  Andrew, did you ever solve this issue?  I noticed the example never sets the clientSecret.  Is that an issue?
Also, what is the service account name?  Is that the product name from the API Console?

Thanks,
Tariq

On Monday, April 30, 2012 3:50:32 PM UTC-5, andrew...@fcc.gov wrote:

Thanks Chirag.

 

I just checked and I am running 5.3.8.

Any other ideas?

 

Thanks,

Andrew

 

Hans

unread,
May 16, 2012, 11:49:17 AM5/16/12
to google-api...@googlegroups.com, Chirag Shah
Tariq, on the service account name, does:


help?

I think changing this line of code ('INSERT_YOUR...):

const SERVICE_ACCOUNT_NAME = 'INSERT_YOUR_SERVICE_ACCOUNT_NAME'; 

could prevent future confusion.

Hans 

Tariq Bashir

unread,
May 16, 2012, 11:54:05 AM5/16/12
to google-api...@googlegroups.com, Chirag Shah
Yes, that clears that up, thanks!

Unfortunately, I am still getting the apiAuthException error:
Error refreshing the OAuth2 token, message: '{ "error" : "invalid_grant" }'

Thanks,
Tariq

Chirag Shah

unread,
May 16, 2012, 9:53:26 PM5/16/12
to google-api...@googlegroups.com
Hey Tariq and Andrew,

I was also able to finally reproduce this "invalid_grant" error by using an invalid key.pem file.

I would recommend starting from the beginning and going through the following steps. I also reproduced these steps on the OAuth2 wiki page here:

2) Press the down arrow in the left panel (under the Google apis logo)
3) Press create.
4) Name your project "Prediction Test Project".
5) Press create project.
6) Now a list of APIs should appear. You want to find "Prediction API" and switch that API to "ON".
7) Select the API Access tab on the left side.
8) Press "Create OAuth 2.0 Client" and create your client.
9) Select Service Account as the application type.
10) Press Download private key.


Now open the examples/prediction/serviceAccount.php sample application in your editor.
0) Make sure you have a recent version of the Google APIs PHP Client checked out from subversion.
1) Replace CLIENT_ID with your newly generated clientId. It should look like:
2) Replace SERVICE_ACCOUNT_NAME with the email address. It should look like:
xxxxxxxxxxxx-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx@developer.gserviceaccount.com
3) Replace KEY_FILE with the path to your private key. Make sure it is saved in a safe place, and readable the sample app.


I agree that the error "invalid_grant" from the API isn't very useful.  Let me know if these directions make sense.

Thank you,
Chirag

Tariq Bashir

unread,
May 17, 2012, 5:03:19 PM5/17/12
to google-api...@googlegroups.com
Hi Chirag,
I tried following all the steps again and am still getting the invalid_grant error. 
I was developing in a windows environment, so I decided to try on a unix box to see if that mattered.
It worked perfectly in the unix environment!
For the path to the key file, I tried using both C:\..\.. syntax and C:/..../ syntax, but neither worked.  
I also tried putting the key file in the same directory as the sample script and input just the name of the key file, which also produced an invalid grant error.
I get a different error if I intentially make the path to the file incorrect:
"Unable to parse the p12 file. Is this a .p12 file? Is the password correct?"

Thanks for your help,
Tariq

Jim OK

unread,
Jun 27, 2012, 1:54:20 PM6/27/12
to google-api...@googlegroups.com
It's still unclear to me what is supported. Supposedly  Google APIs Client Libraries for Python, Java, and PHP are supported, so shouldn't I be able to access any service exposed in the PHP client library?

Chirag Shah

unread,
Jun 27, 2012, 1:59:22 PM6/27/12
to google-api...@googlegroups.com
You can access any Google API that supports supports service accounts with the Python, Java, and PHP client libraries.

robin

unread,
Jul 19, 2012, 6:31:42 AM7/19/12
to google-api...@googlegroups.com
Hi

who know that GA will support serviceaccount?

在 2012年4月13日星期五UTC+8上午3时58分45秒,andrew...@fcc.gov写道:

Mohamed Chenouili

unread,
Jul 23, 2012, 7:47:56 AM7/23/12
to google-api...@googlegroups.com
Hello,

I tried the service Account for GA with the new PHP version of google API, the one from trunk
and i get invalid_grant error
So i did generate a key for service account,
the service Account name was added in my Google analytics account as a user
and here is the code. I have no clue as for the reason for this error.
I tried it with prediction API and still the same error but as it is prediction request is costly
i don't know if it is the reason for the 'invalid_grant' error

session_start();
const CLIENT_ID = 'CLIENT_ID';
const SERVICE_ACCOUNT_NAME = 'SERVICE_ACCOUNT_NAME';
const KEY_FILE = './PATH_TO_KEYFILE.p12';

$client = new apiClient();
$client->setApplicationName("NAME_APPLICATION");


$key = file_get_contents(KEY_FILE);
$client->setAssertionCredentials(new apiAssertionCredentials(
  SERVICE_ACCOUNT_NAME,
  array('https://www.googleapis.com/auth/prediction'),
  $key)
);

$client->setClientId(CLIENT_ID);
$service = new apiAnalyticsService($client);
echo getFirstprofileId($service);

I get the error : invalid_grant i try to find another solution but no luck so far

Could you tell me what i am doing wrong ???
and if there is another solution to get the data from my GA account with automatic authentification
(how to generate an access token for each session,...) ???

Venkat Sarvesh

unread,
Sep 11, 2013, 9:08:04 AM9/11/13
to google-api...@googlegroups.com
Hi Chirag,

This is Sarvesh. I am new to this Google Analytics API implementation. Started reading the docs, blogs. I tried to implement the API and always getting the error: 
     'Error refreshing the OAuth2 token, message: '{
  "error" : "invalid_grant"}

My code:

<?php
class GA {
public $analytics_id  = 'ga:XXXXXX';
public $startDate = '';
public $endDate = '';
public $query = '';
public $valueName = '';
public $limit = 1000;
public $keyfile = '';
function __construct($startDate,$endDate,$valueName='customVarValue1',$query='ga:visits',$limit='1000') {
(!$startDate) ? $startDate = date('Y-m-d', strtotime('-1 day'))  : '';
(!$endDate) ? $endDate = date('Y-m-d', strtotime('now'))  : '';
require 'google-api-php-client/src/Google_Client.php';
require 'google-api-php-client/src/contrib/Google_AnalyticsService.php';
// Assign params 
$this->valueName = $valueName;
$this->startDate = $startDate;
$this->endDate = $endDate;
$this->limit = $limit;
$this->query = $query;
$this->keyfile = file_get_contents('5e132e53a89c533f80b61d2080670c15da006744-privatekey.p12');
}
public function getMobileAnalytics(){
return $this->getAnalytics('ga:XXXXXXX');
}
public function getWebAnalytics(){
return $this->getAnalytics('ga:XXXXXXX');
}
protected function getAnalytics($analytics_id = ''){
if($analytics_id) {
$this->analytics = $analytics_id;
}
$client = new Google_Client();
$client->setApplicationName('GATest');
$client->setAssertionCredentials(
new Google_AssertionCredentials(
$this->keyfile
)
);
// Get this from the Google Console, API Access page
$client->setClientId('XXXXXXXX.apps.googleusercontent.com');
$client->setAccessType('offline');
$analytics = new Google_AnalyticsService($client);
 
try {
$results = $analytics->data_ga->get(
$this->analytics_id,
$this->startDate,
$this->endDate,
$this->query,
array(
// 'dimensions' => 'ga:'.$this->valueName,
'sort' => '-ga:visits',
'max-results' => $this->limit));
$rows = $results->getRows();
$array = (!empty($rows) && $rows > 0) ? $rows : '';
return $array;
} catch(Exception $e) {
echo 'There was an error : - ';
var_dump($e);
}
}

$testGA = new GA(date('Y-m-d', strtotime('-30 day')), date('Y-m-d', strtotime('now')));
$testGA->getWebAnalytics();
?>


I am working on Windows Machine...will there be any issue on Windows? Is Service Account now support Analytics API?
Please help me on this regard.

Thanks & Regards,
Sarvesh
Reply all
Reply to author
Forward
0 new messages