I am using Core reporting API for reporting. I have installed Google PHP API client master on my localhost server and made a file HelloAnalyticsAPi.php in src folder Where I include
Google/Client.php
,
Google/Service/Analytics.php
files. And use the below details
$client->setClientId('XXXXXXXXXXX.apps.googleusercontent.com');
$client->setClientSecret('XXXXXXXXXXX');
$client->setRedirectUri('http://localhost/analytics/src/HelloAnalyticsApi.php');
$client->setDeveloperKey('XXXXXXXXXXX');
$client->setScopes(array('https://www.googleapis.com/auth/analytics.readonly'));
$client->setUseObjects(true);
I have fatal error on setUseObjects. Error is Fatal error: Call to undefined method Google_Client::setUseObjects(). I have done some authorization on my google analytics backend also.
Please let me know the whole process for getting report on my server. Because I am not able to understand the developers guide of google analytics which they have given.
The problem you are having is that you have the wrong client lib. The Hello Analytics API tutorial was created using the old lib on Code.google - google-api-php-client Not the newer version on github.
Update:
Because of the fact that the tutorial still hasn't been updated I have made a tutorial that may help. Google Oauth2 php. The code below is ripped directly from it. The tutorial will be kept up to date you may want to check that for any changes.
<?php
require_once 'Google/Client.php';
require_once 'Google/Service/Analytics.php';
session_start();
$client = new Google_Client();
$client->setApplicationName("Client_Library_Examples");
$client->setDeveloperKey("{devkey}");
$client->setClientId('{clientid}.apps.googleusercontent.com');
$client->setClientSecret('{clientsecret}');
$client->setRedirectUri('http://www.daimto.com/Tutorials/PHP/Oauth2.php');
$client->setScopes(array('https://www.googleapis.com/auth/analytics.readonly'));
//For loging out.
if ($_GET['logout'] == "1") {
unset($_SESSION['token']);
}
// Step 2: The user accepted your access now you need to exchange it.
if (isset($_GET['code'])) {
$client->authenticate($_GET['code']);
$_SESSION['token'] = $client->getAccessToken();
$redirect = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL));
}
// Step 1: The user has not authenticated we give them a link to login
if (!$client->getAccessToken() && !isset($_SESSION['token'])) {
$authUrl = $client->createAuthUrl();
print "<a class='login' href='$authUrl'>Connect Me!</a>";
}
// Step 3: We have access we can now create our service
if (isset($_SESSION['token'])) {
print "<a class='logout' href='".$_SERVER['PHP_SELF']."?logout=1'>LogOut</a><br>";
$client->setAccessToken($_SESSION['token']);
$service = new Google_Service_Analytics($client);
// request user accounts
$accounts = $service->management_accountSummaries->listManagementAccountSummaries();
foreach ($accounts->getItems() as $item) {
echo "Account: ",$item['name'], " " , $item['id'], "<br /> \n";
foreach($item->getWebProperties() as $wp) {
echo ' WebProperty: ' ,$wp['name'], " " , $wp['id'], "<br /> \n";
$views = $wp->getProfiles();
if (!is_null($views)) {
foreach($wp->getProfiles() as $view) {
// echo ' View: ' ,$view['name'], " " , $view['id'], "<br /> \n";
}
}
}
} // closes account summaries
}
print "<br><br><br>";
print "Access from google: " . $_SESSION['token'];
?>
Related
I am using the following code which was largely lifted from this tutorial - http://www.daimto.com/google-oauth2-php/
I have added the line client->setAccessType("offline"); in order to receive a refresh token from Google which I can see coming through from print "Access from google: " . $_SESSION['token'];.
I'm struggling to understand how to use the refresh token in order to get authorisation. What I'd ideally like to is update this script to
- use a refresh token if one is available, or
- present the existing "Connect Me" link if one is not
I plan to store the refresh token in a DB eventually, however to get it working initially I will just hard code.
Any help is much appreciated!
<?php
set_include_path('src');
require_once 'Google/Client.php';
require_once 'Google/Service/Calendar.php';
session_start();
$client = new Google_Client();
$client->setApplicationName("Client_Library_Examples");
$client->setDeveloperKey("XXXXXXXXXXXXXXXXXXXX");
$client->setClientId('XXXXXXXXXXXXXXXXXXXX');
$client->setClientSecret('XXXXXXXXXXXXXXXXXXXX');
$client->setRedirectUri('XXXXXXXXXXXXXXXXXXXX');
$client->setAccessType("offline");
$client->setScopes(array('https://www.googleapis.com/auth/calendar'));
//For loging out.
if ($_GET['logout'] == "1") {
unset($_SESSION['token']);
}
// Step 2: The user accepted your access now you need to exchange it.
if (isset($_GET['code'])) {
$client->authenticate($_GET['code']);
$_SESSION['token'] = $client->getAccessToken();
$redirect = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL));
}
// Step 1: The user has not authenticated we give them a link to login
if (!$client->getAccessToken() && !isset($_SESSION['token'])) {
$authUrl = $client->createAuthUrl();
print "<a class='login' href='$authUrl'>Connect Me!</a>";
}
// Step 3: We have access we can now create our service
if (isset($_SESSION['token'])) {
print "<a class='logout' href='".$_SERVER['PHP_SELF']."?logout=1'>LogOut</a><br>";
$client->setAccessToken($_SESSION['token']);
$service = new Google_Service_Calendar($client);
}
print "<br>";
print "Access from google: " . $_SESSION['token'];
print "<br><br>";
require_once 'calendar_app.php';
?>
I am completely lost... All I'm trying to do is get rid of this error message and log into Google API. I've created all the keys and added them to /src/Google/Config.php.
PHP Fatal error: Uncaught exception 'Google_Service_Exception' with message 'Error calling GET
https://www.googleapis.com/calendar/v3/users/me/calendarList/0qfrti6gst4q8hpl89utm8elno%40grou p.calendar.google.com?key=AIzaSyAiR_4OsoheCPbd7tU2u3QrqbEW_a2uVCc: (401) Login Required'
in C:\\Bitnami\\wampstack\\apache2\\htdocs\\yac\\google-api-php-
client\\src\\Google\\Http\\REST.php:79\nStack ...
Here's my (most likely) incorrect script:
session_start();
set_include_path( get_include_path() . PATH_SEPARATOR . 'google-api-php-client/src' );
include_once('google-api-php-client/src');
require_once('google-api-php-client/src/Google/Client.php');
require_once ('google-api-php-client/src/Google/Service/Calendar.php');
$client = new Google_Client();
$client->setApplicationName("YAC_Calendar");
$client->setDeveloperKey(<MY KEY>);
$service = new Google_Service_Calendar($client);
$calendarListEntry = $service->calendarList->get('0qfrti6gst4q8hpl89utm8elno#group.calendar.google.com');
echo $calendarListEntry->getSummary();
you need to login using Oauth before you can access the calendar. The only example I have on hand right now is one using Google Analytics API with PHP if you have any switching it over to Calendar let me know I will see if I can get a working example for that.
<?php
require_once 'Google/Client.php';
require_once 'Google/Service/Analytics.php';
session_start();
$client = new Google_Client();
$client->setApplicationName("Client_Library_Examples");
$client->setDeveloperKey("{devkey}");
$client->setClientId('{clientid}.apps.googleusercontent.com');
$client->setClientSecret('{clientsecret}');
$client->setRedirectUri('http://www.daimto.com/Tutorials/PHP/Oauth2.php');
$client->setScopes(array('https://www.googleapis.com/auth/analytics.readonly'));
//For loging out.
if ($_GET['logout'] == "1") {
unset($_SESSION['token']);
}
// Step 2: The user accepted your access now you need to exchange it.
if (isset($_GET['code'])) {
$client->authenticate($_GET['code']);
$_SESSION['token'] = $client->getAccessToken();
$redirect = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL));
}
// Step 1: The user has not authenticated we give them a link to login
if (!$client->getAccessToken() && !isset($_SESSION['token'])) {
$authUrl = $client->createAuthUrl();
print "<a class='login' href='$authUrl'>Connect Me!</a>";
}
// Step 3: We have access we can now create our service
if (isset($_SESSION['token'])) {
print "<a class='logout' href='".$_SERVER['PHP_SELF']."?logout=1'>LogOut</a><br>";
$client->setAccessToken($_SESSION['token']);
$service = new Google_Service_Analytics($client);
// request user accounts
$accounts = $service->management_accountSummaries->listManagementAccountSummaries();
foreach ($accounts->getItems() as $item) {
echo "Account: ",$item['name'], " " , $item['id'], "<br /> \n";
foreach($item->getWebProperties() as $wp) {
echo ' WebProperty: ' ,$wp['name'], " " , $wp['id'], "<br /> \n";
$views = $wp->getProfiles();
if (!is_null($views)) {
foreach($wp->getProfiles() as $view) {
// echo ' View: ' ,$view['name'], " " , $view['id'], "<br /> \n";
}
}
}
} // closes account summaries
}
print "<br><br><br>";
print "Access from google: " . $_SESSION['token'];
?>
Code from my tutorial Google Oauth2 php
I'm using Google PHP Client 4ae272683e18888362e1f935b813e345b99e23b8 pulled Aug 9 from github. I feel like my code is too simple to be wrong.
require_once ('Google/Client.php');
$client = new Google_Client();
$client->setAuthConfigFile('client_secret.json');
$client->authenticate($_POST['code']);
I get this invalid_request error:
Uncaught exception 'Google_Auth_Exception' with message 'Error fetching OAuth2 access token, message: 'invalid_request'' in /Users/dfabulich/test/Google/Auth/OAuth2.php:125
Stack trace:
#0 /Users/dfabulich/test/Google/Client.php(135): Google_Auth_OAuth2->authenticate('4/58wTCTNiQNIdR...')
#1 /Users/dfabulich/test/google-login.php(24): Google_Client->authenticate('4/58wTCTNiQNIdR...')
#2 {main}
client_secret.json is the exact file I downloaded from the Google API Developers Console. The file definitely exists, because if I use the wrong file name, I get a very clear error, "Invalid client secret JSON file." I've visually inspected the file and it looks fine.
I edited Google/Auth/OAuth2.php to log the post body as json; it looks like this (but I've HIDDEN the client secret below):
{"code":"4\/58wTCTNiQNIdRfb8DgQBYk518URV.Elrb71kFKHAYEnp6UAPFm0HWWGd6jwI","grant_type":"authorization_code","redirect_uri":"","client_id":"807284957448-3katmu7oqd1277ql9eo258dadkbkqruq.apps.googleusercontent.com","client_secret":"HIDDEN"}
What could I possibly be doing wrong?!
I was using the Google+ Sign-in API, so I also needed to add a setRedirectUri("postmessage") line. This code works.
require_once ('Google/Client.php');
$client = new Google_Client();
$client->setRedirectUri('postmessage');
$client->setAuthConfigFile('client_secret.json');
$client->authenticate($_POST['code']);
I cant tell you why your code doesn't work I have never tried using setAuthConfigFile This is the code i use
<?php
require_once 'Google/Client.php';
require_once 'Google/Service/Analytics.php';
session_start();
$client = new Google_Client();
$client->setApplicationName("Client_Library_Examples");
$client->setDeveloperKey("{devkey}");
$client->setClientId('{clientid}.apps.googleusercontent.com');
$client->setClientSecret('{clientsecret}');
$client->setRedirectUri('http://www.daimto.com/Tutorials/PHP/Oauth2.php');
$client->setScopes(array('https://www.googleapis.com/auth/analytics.readonly'));
//For loging out.
if ($_GET['logout'] == "1") {
unset($_SESSION['token']);
}
// Step 2: The user accepted your access now you need to exchange it.
if (isset($_GET['code'])) {
$client->authenticate($_GET['code']);
$_SESSION['token'] = $client->getAccessToken();
$redirect = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL));
}
// Step 1: The user has not authenticated we give them a link to login
if (!$client->getAccessToken() && !isset($_SESSION['token'])) {
$authUrl = $client->createAuthUrl();
print "<a class='login' href='$authUrl'>Connect Me!</a>";
}
// Step 3: We have access we can now create our service
if (isset($_SESSION['token'])) {
print "<a class='logout' href='".$_SERVER['PHP_SELF']."?logout=1'>LogOut</a><br>";
$client->setAccessToken($_SESSION['token']);
$service = new Google_Service_Analytics($client);
// request user accounts
$accounts = $service->management_accountSummaries->listManagementAccountSummaries();
foreach ($accounts->getItems() as $item) {
echo "Account: ",$item['name'], " " , $item['id'], "<br /> \n";
foreach($item->getWebProperties() as $wp) {
echo ' WebProperty: ' ,$wp['name'], " " , $wp['id'], "<br /> \n";
$views = $wp->getProfiles();
if (!is_null($views)) {
foreach($wp->getProfiles() as $view) {
// echo ' View: ' ,$view['name'], " " , $view['id'], "<br /> \n";
}
}
}
} // closes account summaries
}
print "<br><br><br>";
print "Access from google: " . $_SESSION['token'];
?>
My tutorial can be found at Google Oauth2 php
I am trying to retrieve the Google Analytics Management Profiles using the latest PHP client API (https://github.com/google/google-api-php-client).
I have the following code snippet:
// we've got the token, so set it
$google_client->setAccessToken($_SESSION['access_code']);
if ($google_client->getAccessToken()) {
$profiles = $google_analytics_service->management_profiles->listManagementProfiles("~all", "~all");
print "<h1>Profiles</h1><pre>" . print_r($profiles, true) . "</pre>";
}
/* $url = 'https://www.googleapis.com/analytics/v3/management/accounts/~all/webproperties/~all/profiles'; */
/* // json decode as array */
/* $analytics_auth = json_decode($_SESSION['access_code'], true); */
/* $ch = curl_init($url . '?access_token=' . $analytics_auth['access_token']); */
/* curl_exec($ch); */
/* curl_close($ch); */
The error message I get with the above is:
Error calling GET https://www.googleapis.com/analytics/v3/management/accounts/~all/webproperties/~all/profiles?key=AIza[SNIP]: (403) Access Not Configured
Note: However I decided to run the same with cURL and it returns a JSON array with the profiles (the commented code). Is this a bug, or me? What I do notice is that my access_token starts with "ya29".
I think you are missing a step:
<?php
require_once 'Google/Client.php';
require_once 'Google/Service/Analytics.php';
session_start();
$client = new Google_Client();
$client->setApplicationName("Client_Library_Examples");
$client->setDeveloperKey("{developerkey}");
$client->setClientId('{clientID}.apps.googleusercontent.com');
$client->setClientSecret('{Client secret}');
$client->setRedirectUri('http://www.daimto.com/Tutorials/PHP/Oauth2.php');
$client->setScopes(array('https://www.googleapis.com/auth/analytics.readonly'));
//For loging out.
if ($_GET['logout'] == "1") {
unset($_SESSION['token']);
}
// Step 2: The user accepted your access now you need to exchange it.
if (isset($_GET['code'])) {
$client->authenticate($_GET['code']);
$_SESSION['token'] = $client->getAccessToken();
$redirect = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL));
}
// Step 1: The user has not authenticated we give them a link to login
if (!$client->getAccessToken() && !isset($_SESSION['token'])) {
$authUrl = $client->createAuthUrl();
print "<a class='login' href='$authUrl'>Connect Me!</a>";
}
// Step 3: We have access we can now create our service
if (isset($_SESSION['token'])) {
print "<a class='logout' href='".$_SERVER['PHP_SELF']."?logout=1'>LogOut</a><br>";
$client->setAccessToken($_SESSION['token']);
$service = new Google_Service_Analytics($client);
// request user accounts
$accounts = $service->management_accountSummaries->listManagementAccountSummaries();
foreach ($accounts->getItems() as $item) {
echo "Account: ",$item['name'], " " , $item['id'], "<br /> \n";
foreach($item->getWebProperties() as $wp) {
echo ' WebProperty: ' ,$wp['name'], " " , $wp['id'], "<br /> \n";
$views = $wp->getProfiles();
if (!is_null($views)) {
foreach($wp->getProfiles() as $view) {
// echo ' View: ' ,$view['name'], " " , $view['id'], "<br /> \n";
}
}
}
} // closes account summaries
}
print "<br><br><br>"; // fix syntax
print "Access from google: " . $_SESSION['token'];
?>
Due to issue with the session_start and headers its a bit out of order. I added some comments to help you understand what its doing. Its a simple script but you can test it here Dummy Example for Hal9k
The 403 problem was because the correct IP address wasn't set for the server applications key. This can be set in the Google Developers' Console. It's odd, however, that using cURL bypassed this.
Public API access
Use of this key does not require any user action or consent, does not grant access to any account information, and is not used for authorization.
Key for server applications API key: AI[snip]
IPs: 91.[snip] 109.[snip] Make sure correct IP address is set here
I have followed the directions exactly, copied code examples - I cannot get this to respond (write an event on a calendar).
Please help - if there is any help for me. AFter 12 hours of working on this with a huge deadline of tomorrow, I'm about to pull my hair out.
On Google Developer Console, created a project and generated keys required.
The keys below are altered for safety.
None of the echos are showing except for the first one with the order number in it.
My programmer got this code to work, so I know it's OK - it's something set up wrong on the console, but I need a clue:
Full code - like I said, it's been tested and works on another project.
if(isset($_GET['orderid']) )
{
$_SESSION['oid']= $_GET['orderid'];
}
echo $_GET['orderid'];
$client = new Google_Client();
$client->setApplicationName("API Project");
$client->setClientId('9999999999999.apps.googleusercontent.com');
$client->setClientSecret('xxxxxxxxxxxxxxxxxxxxxxxxx');
$scriptUri = "http://".$_SERVER["HTTP_HOST"].$_SERVER['PHP_SELF'];
$client->setRedirectUri($scriptUri);
//$client->setDeveloperKey('AIxxxxxxxxxxxxx'); - SERVER APPS
$client->setDeveloperKey('AIxxxxxxxxxxxxxxx'); // - WEB APPS
$cal = new Google_CalendarService($client);
if (isset($_GET['logout'])) {
unset($_SESSION['token']);
}
if (isset($_GET['code'])) {
echo $_GET['code'];
$client->authenticate($_GET['code']);
$_SESSION['token'] = $client->getAccessToken();
header('Location: http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF']);
}
if (isset($_SESSION['token'])) {
echo $_SESSION['token'];
$client->setAccessToken($_SESSION['token']);
}
if ($client->getAccessToken()) {
$calList = $cal->calendarList->listCalendarList();
//print "<h1>Calendar List</h1><pre>" . print_r($calList, true) . "</pre>";
$_SESSION['token'] = $client->getAccessToken();
// database access is here and like I said, it is tested and working
echo "<center>Event has successfully added to Your Google Calendar...</center>";
unset($_SESSION['oid']);
} else {
$authUrl = $client->createAuthUrl();
print "<a class='login' href='$authUrl'>Click Here for Google Authorization!</a>";
}
If you just want to add an event on Google Calendar (no other interactions), I think you should use the direct link :
https://www.google.com/calendar/render?action=TEMPLATE&text=Your+event+title&dates=20140325T090000Z/20140325T100000Z&details=Your+event+description&location=Room+12&pli=1&uid&sf=true&output=xml
You just have to customize variables and escape non-URI characters.
** EDIT **
Do you successfully connect the user through OAuth 2?
** EDIT 2 **
Your code is working for me without the DB access :
if ($client->getAccessToken()) {
$calList = $cal->calendarList->listCalendarList();
//print "<h1>Calendar List</h1><pre>" . print_r($calList, true) . "</pre>";
$_SESSION['token'] = $client->getAccessToken();
// DB ACCESS
echo "<center>Event has successfully added to Your Google Calendar...</center>";
unset($_SESSION['oid']);
} else {
$authUrl = $client->createAuthUrl();
print "<a class='login' href='$authUrl'>Click Here for Google Authorization!</a>";
}
Julian