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
Related
I'm new to Google API and am having trouble getting the Analytics API to work. So far I've set up the Developer Console, created a project, and generated the relevant credentials. My registered email ID is myname#mycompany.com, and the redirect URI is set to http://www.mycompany.com/oauth2callback by default. The JavaScript Origins is set to http://www.mycompany.com.
When I run the project from localhost, I'm able to initiate the OAuth procedure. But when I hit the "allow" button, I'm sent to http://www.mycompany.comand nothing happens. What could I be doing wrong? Do I need to be running this script from the mycompany.com doamin for it to work? Lastly, how can I run it from localhost?
<?php
include_once "google_api/autoload.php";
session_start();
$client = new Google_Client();
$client->setApplicationName("Hello Analytics API Example");
$client->setClientId('XXXXXXXXXXXXXXXXX');
$client->setClientSecret('XXXXXXXXXXXXXXXXXXXX');
//$client->setRedirectUri('XXXXXXXXXXXXXXXXXXX');
$client->setRedirectUri('XXXXXXXXXXXXXXXXXX');
$client->setDeveloperKey('XXXXXXXXXXXXXXXXXXXX');
$client->setScopes(array('https://www.googleapis.com/auth/analytics.readonly'));
// Magic. Returns objects from the Analytics Service instead of associative arrays.
//print_r($client);
//$client->setUseObjects(true);
if (isset($_GET['code']))
{
$client->authenticate();
$_SESSION['token'] = $client->getAccessToken();
$redirect = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL));
}
if (isset($_SESSION['token'])) {
$client->setAccessToken($_SESSION['token']);
}
if (!$client->getAccessToken())
{
$authUrl = $client->createAuthUrl();
print "<a class='login' href='$authUrl'>Connect Me!</a>";
}
else
{
// Create analytics service object. See next step below.
$analytics = new apiAnalyticsService($client);
runMainDemo($analytics);
}
function runMainDemo(&$analytics) {
try {
// Step 2. Get the user's first view (profile) ID.
$profileId = getFirstProfileId($analytics);
if (isset($profileId)) {
// Step 3. Query the Core Reporting API.
$results = getResults($analytics, $profileId);
// Step 4. Output the results.
printResults($results);
}
} catch (apiServiceException $e) {
// Error from the API.
print 'There was an API error : ' . $e->getCode() . ' : ' . $e->getMessage();
} catch (Exception $e) {
print 'There wan a general error : ' . $e->getMessage();
}
}
function getFirstprofileId(&$analytics) {
$accounts = $analytics->management_accounts->listManagementAccounts();
if (count($accounts->getItems()) > 0) {
$items = $accounts->getItems();
$firstAccountId = $items[0]->getId();
$webproperties = $analytics->management_webproperties
->listManagementWebproperties($firstAccountId);
if (count($webproperties->getItems()) > 0) {
$items = $webproperties->getItems();
$firstWebpropertyId = $items[0]->getId();
$profiles = $analytics->management_profiles
->listManagementProfiles($firstAccountId, $firstWebpropertyId);
if (count($profiles->getItems()) > 0) {
$items = $profiles->getItems();
return $items[0]->getId();
} else {
throw new Exception('No views (profiles) found for this user.');
}
} else {
throw new Exception('No webproperties found for this user.');
}
} else {
throw new Exception('No accounts found for this user.');
}
}
function getResults(&$analytics, $profileId) {
return $analytics->data_ga->get(
'ga:' . $profileId,
'2012-03-03',
'2012-03-03',
'ga:sessions');
}
function printResults(&$results) {
if (count($results->getRows()) > 0) {
$profileName = $results->getProfileInfo()->getProfileName();
$rows = $results->getRows();
$sessions = $rows[0][0];
print "<p>First view (profile) found: $profileName</p>";
print "<p>Total sessions: $sessions</p>";
} else {
print '<p>No results found.</p>';
}
}
If you want to be able to request there data automated you will need to store the refreshtoken. If you only want them to be able to access there data when they are on your site then this should get you started.
The latest Google PHP client lib can be found here. Github
<?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 ripped from the tutorial Google Analytics Oauth2 with php.
Update: After looking at your code I think part of your problem may be that you aren't linking the redirectURi to a page. It cant just be a directory you must give it the php page that it should redirect to.
Just trying to use the Google Client API to pull traffic data for my site and thought I would try the simple.php file on https://code.google.com/p/google-api-php-client/source/browse/trunk/examples/contacts/simple.php
I've edited it appropriately for my credentials and I can get it to go from the "Connect Me" link to the request permission page, but after I accept I end up at "This webpage is not available". I'm wondering if there might be an issue with needing the token refreshed?
Any thoughts are greatly appreciated. Thanks!
<?php
require_once 'src/Google_Client.php';
require_once 'src/contrib/Google_AnalyticsService.php';
session_start();
$client = new Google_Client();
$client->setApplicationName("Google Analytics PHP Starter Application");
// Visit https://code.google.com/apis/console?api=analytics to generate your
// client id, client secret, and to register your redirect uri.
$client->setClientId('MY_CLIENT_ID');
$client->setClientSecret('MY_CLIENT_SECRET');
$client->setDeveloperKey('MY_DEVELOPER_KEY');
$client->setRedirectUri('http://localhost/google-analytics/simple.php');
$service = new Google_AnalyticsService($client);
if (isset($_GET['logout'])) {
unset($_SESSION['token']);
}
if (isset($_GET['code'])) {
$client->authenticate();
$_SESSION['token'] = $client->getAccessToken();
$redirect = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL));
}
if (isset($_SESSION['token'])) {
$client->setAccessToken($_SESSION['token']);
}
if ($client->getAccessToken()) {
$props = $service->management_webproperties->listManagementWebproperties("~all");
print "<h1>Web Properties</h1><pre>" . print_r($props, true) . "</pre>";
$accounts = $service->management_accounts->listManagementAccounts();
print "<h1>Accounts</h1><pre>" . print_r($accounts, true) . "</pre>";
$segments = $service->management_segments->listManagementSegments();
print "<h1>Segments</h1><pre>" . print_r($segments, true) . "</pre>";
$goals = $service->management_goals->listManagementGoals("~all", "~all", "~all");
print "<h1>Segments</h1><pre>" . print_r($goals, true) . "</pre>";
$_SESSION['token'] = $client->getAccessToken();
} else {
$authUrl = $client->createAuthUrl();
print "<a class='login' href='$authUrl'>Connect Me!</a>";
}
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 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'];
?>