How to use google's API refresh token (Curl, php) ??

5,374 views
Skip to first unread message

Naïm Joukovsky

unread,
Sep 25, 2015, 10:23:55 AM9/25/15
to Google Analytics Reporting API

 Hi everybody,

 I'm trying to use the Google Analytics Api but I'm failling to use the mysterious refresh token.

 I'm succeeding to ask the API with Curl with a short life token.

 Does somebody know how to do to automaticaly refresh my token ?
I need to use the datas for an interactive dashboard.

 This is my code :


  $url2 ='https://www.googleapis.com/analytics/v3/data/realtime?ids=ga%3A104738580&metrics=rt%3AactiveUsers&access_token=.ya29.-QF7_hN0uNhn9iGl8fXB1wFWE7gl_oujmBACEJA5outSg2H5HP28D4mekq6c8tHP2KYn';
//realtime
function get_report($url)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)");
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLINFO_HEADER_OUT, TRUE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$output = curl_exec($ch);
$request = curl_getinfo($ch, CURLINFO_HEADER_OUT);
$error = curl_error($ch);
curl_close($ch);
return ($output);
}

Matt

unread,
Sep 25, 2015, 12:58:19 PM9/25/15
to Google Analytics Reporting API
You need to change the authorization request you make to get the token to get the "offline_access" token.


-Matt
Message has been deleted

Naïm Joukovsky

unread,
Sep 26, 2015, 8:52:10 AM9/26/15
to Google Analytics Reporting API
Hi Matt,

thank you for your answer.

I read all the documentation you gave to me, it's alI I need but I'm failling to use it .

I have a code and  a refresh token obtained on the OAuth Playground and I want to revoke my access_token every hours and get a new one with my refresh token.

 I somebody can help me because I really need to get my google Analytics datas.

I show you my none-working code:


POST /oauth2/v3/token HTTP/1.1
Host: www.googleapis.com
Content-Type: application/x-www-form-urlencoded
client_id=1011760424792-huap7gokulbflbcdefrtgls2rsl19n31.apps.googleusercontent.com&
client_secret={SXhE**************-vcox}&
refresh_token=1/3Ww3MOaMHu5Ynwuz9oz3oM0bbtWaQBk_cL7j70g_SIA&
grant_type=refresh_token

Matthew Cohoon

unread,
Sep 28, 2015, 12:22:08 PM9/28/15
to Google Analytics Reporting API
Can you be a little more precise about what is not working? Are you getting an error response?

Your code example only shows the request to the Google Analytics API. Not the authentication requests which seem to be the crux your question.

In order to exchange a refresh token for a newly validated access_token you need to make another requests to www.googleapis.com/oauth2/v3/token

You will notice in the OAuth2.0 Playground this takes place as step two.  you can then repeat this process whenever you need to get a new access_token. As described in the "using a refresh token" section of the OAuth documentation.

-Matt

--
You received this message because you are subscribed to a topic in the Google Groups "Google Analytics Reporting API" group.
To unsubscribe from this topic, visit https://groups.google.com/d/topic/google-analytics-data-export-api/xVDLAEXpNsg/unsubscribe.
To unsubscribe from this group and all its topics, send an email to google-analytics-data-...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Naïm Joukovsky

unread,
Sep 28, 2015, 12:31:00 PM9/28/15
to Google Analytics Reporting API
Hi Matt,

thanks again to be here.

 I will ty to be more precise.

I need to have my google's analytics dats on my webpage.

First can you tell me if the redirection url need to be toward my webpage or toward https://developers.google.com/oauthplayground/ ?

 As you see I'm using Curl and simple url request but I d'ont know how to build my URLs to have right response from the API.
I've read all the documentation you gave me and all I found but I never succeed to use the code's example.

 Could you give example mate ?

I hope you could help me because I really need to done that.

Thanks

Matthew Cohoon

unread,
Sep 28, 2015, 1:21:03 PM9/28/15
to Google Analytics Reporting API
I would first and foremost recommend using one the client libraries. Each of the client libraries have code which makes authentication and authorization much easier than using CURL.

Secondly you need to decide on the type Application you want to build. Are you trying to build a site where you or your users can access their own data? Then follow the Hello World instructions on building a Web Application. If you are trying to share your private google analytics data publicly. then you either Collect the data server side with service account authentication, or you can use some combination of server side authentication and client side refresh access as described in this article about using the embed API pared with the Server side authentication.

The redirect determines where the response from google's authentications servers is sent. It should be your website. The value of this parameter must exactly match one of the values listed for this project in the Google Developers Console(including the http or https scheme, case, and trailing '/'). when I am building a new application I usually use https://localhost:8080 and then change it to my public address when its ready to be published.

-Matt




--

Naïm Joukovsky

unread,
Sep 29, 2015, 9:18:21 AM9/29/15
to Google Analytics Reporting API
Hi Matt,

I'm lucky to have your help.
I took your advice and I switch to use a the google-api-php-client librairy.

I've followed first all the steps from https://developers.google.com/analytics/devguides/reporting/core/v3/quickstart/service-php and when I'm trying to test the code on localhost I have a lot of warnings.

Warning: file_get_contents(/client_secrets.p12): failed to open stream: No such file or directory in C:\wamp\www\LeHibou.com_Dashboard\HelloAnalytics.php on line 21

Fatal error: Uncaught exception 'Google_Auth_Exception' with message 'Unable to parse the p12 file. Is this a .p12 file? Is the password correct? OpenSSL error: ' in C:\wamp\www\LeHibou.com_Dashboard\google-api-php-client\src\Google\Signer\P12.php on line 55

Google_Auth_Exception: Unable to parse the p12 file. Is this a .p12 file? Is the password correct? OpenSSL error: in C:\wamp\www\LeHibou.com_Dashboard\google-api-php-client\src\Google\Signer\P12.php on line 55

Can you tell me what I did wrong please ?

thanks a lot

Matthew Cohoon

unread,
Sep 29, 2015, 1:18:21 PM9/29/15
to Google Analytics Reporting API
So the p12 file is the file you downloaded from the Google Developer Console when setting up the service account.

1. You should log into the Google Developer console.
2. Under APIs & Auth select "credentials"
3. If you have not done so already click "Add credentials" and create a service account. Select p12 type click create

This should start the download of you your p12 file.

If you have not done so already you will also need to add the service account as a user to Google Analytics Account.
This means logging into your GA account and adding <projectid>-<serviceaccountID>@developer.gserviceaccount.com to as user to your Google Analytics account.
-Matt



--

Naïm Joukovsky

unread,
Sep 29, 2015, 1:24:12 PM9/29/15
to Google Analytics Reporting API
Hi mate,

That's exactly what I 've done.
The p12 file is on the same folder so shall I write the path toward him like:
'client_secrets.p12'; ?

Matthew Cohoon

unread,
Sep 29, 2015, 1:31:58 PM9/29/15
to Google Analytics Reporting API
Try replacing it with the relative path, ie drop the forward slash "/". I think your app was looking int the root directory for the p12 file.

if it is in the same directory you are executing it, make sure the string is "client_secrets.p12"

Message has been deleted
Message has been deleted

Naïm Joukovsky

unread,
Sep 30, 2015, 4:25:42 AM9/30/15
to Google Analytics Reporting API
Ok I've succeded to use the client librairy.

 But I've still have two problems:

 I can't ask the API to have my real time sessions or my Daily session .

I think I have to modifiate this part but I don't know how:

function
getResults(&$analytics, $profileId) {
// Calls the Core Reporting API and queries for the number of sessions
// for the last seven days.
return $analytics->data_ga->get(
'ga:' . $profileId,
'7daysAgo',
'today',
'ga:sessions');
}

 and I'm failing to refresh the token...

 I start to feel hopeless.

Hope somebody will help me.

Matthew Cohoon

unread,
Sep 30, 2015, 12:25:16 PM9/30/15
to Google Analytics Reporting API
Are you trying to use the Realtime API, just change the call from $analytics->data_ga->get(....) to the following:
$optParams = array(
   
'dimensions' => 'rt:medium');

try {
  $results
= $analytics->data_realtime->get(
     
'ga:56789',
     
'rt:activeUsers',
      $optParams
);

You will also need to change how the response is handled of course.

Regarding refreshing the token the PHP client library documentation gives the following example:

if ($client->getAuth()->isAccessTokenExpired()) {
  $client
->getAuth()->refreshTokenWithAssertion();
}

Also http://stackoverflow.com/questions/tagged/google-analytics-api is a great place to get help with specific coding issues.
-Matt

--
Message has been deleted

Naïm Joukovsky

unread,
Oct 3, 2015, 2:28:17 PM10/3/15
to Google Analytics Reporting API

Hi Matt,

can you please help to obtain my realtime actice users ?

I'm using this code but nothing  happened, nothing is print.

Can you please tell me what is wrong ?

I hope you're well.


$analytics = getService();
$profile = getFirstProfileId($analytics);


$optParams = array(
'dimensions' => 'rt:medium');

try {
$results = $analytics->data_realtime->get(
        'ga:' . $profile,
'rt:activeUsers',
$optParams);
// Success.
} catch (apiServiceException $e) {
// Handle API service exceptions.
$error = $e->getMessage();
}


function printRealtimeReport($results) {
printReportInfo($results);
}

function printReportInfo(&$results) {
$html = <<<HTML
<pre>
Kind = {$results->getKind()}
ID = {$results->getId()}
Self Link = {$results->getSelfLink()}
Total Results = {$results->getTotalResults()}
</pre>
HTML;

print $html;
}

Nam's

Matthew Cohoon

unread,
Oct 6, 2015, 11:52:44 AM10/6/15
to Google Analytics Reporting API
Try printing the error message.
When I am debugging new code I always put in lots of print statements.

print "I am about to call method foo"

results = foo()

print "results of method foo: " + foo

In this way if I never see the debug statement "I am about to call method foo" I know that the problem is somehow that the code I thought I was running is not actually running.

-Matt



Reply all
Reply to author
Forward
0 new messages