I am trying to create a page where data about a persons GA account will be displayed. Currently only 1 users data is displayed no matter who is logged in. I dont understand why this is the case because I am using a client ID to authenticate along with oauth2.0. I call getFirstprofileId, however no matter who is logged in to google, the result always returns the same id
info.php
<?php
// Load the Google API PHP Client Library.
require_once realpath(dirname(__FILE__).'/google-api-php-client/src/Google/autoload.php');
// Start a session to persist credentials.
session_start();
$client_id = 'XXXXXXXXX';
$client_secret = 'XXXXXXX';
$redirect_uri = 'http://XXXXX.info/info.php';
// Create the client object and set the authorization configuration
// from the client_secretes.json you downloaded from the developer console.
$client = new Google_Client();
$client->setClientId($client_id);
$client->setClientSecret($client_secret);
$client->setRedirectUri($redirect_uri);
$client->addScope(Google_Service_Analytics::ANALYTICS_READONLY);
$analytics = new Google_Service_Analytics($client);
/************************************************
If we're logging out we just need to clear our
local access token in this case
************************************************/
if (isset($_REQUEST['logout'])) {
unset($_SESSION['access_token']);
}
/************************************************
If we have a code back from the OAuth 2.0 flow,
we need to exchange that with the authenticate()
function. We store the resultant access token
bundle in the session, and redirect to ourself.
************************************************/
if (isset($_GET['code'])) {
$client->authenticate($_GET['code']);
$_SESSION['access_token'] = $client->getAccessToken();
$redirect = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL));
}
/************************************************
If we have an access token, we can make
requests, else we generate an authentication URL.
************************************************/
if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {
$client->setAccessToken($_SESSION['access_token']);
} else {
$authUrl = $client->createAuthUrl();
}
function getFirstprofileId(&$analytics) {
// Get the user's first view (profile) ID.
// Get the list of accounts for the authorized user.
$accounts = $analytics->management_accounts->listManagementAccounts();
if (count($accounts->getItems()) > 0) {
$items = $accounts->getItems();
$firstAccountId = $items[0]->getId();
// Get the list of properties for the authorized user.
$properties = $analytics->management_webproperties
->listManagementWebproperties($firstAccountId);
if (count($properties->getItems()) > 0) {
$items = $properties->getItems();
$firstPropertyId = $items[0]->getId();
// Get the list of views (profiles) for the authorized user.
$profiles = $analytics->management_profiles
->listManagementProfiles($firstAccountId, $firstPropertyId);
if (count($profiles->getItems()) > 0) {
$items = $profiles->getItems();
// Return the first view (profile) ID.
return $items[0]->getId();
} else {
throw new Exception('No views (profiles) found for this user.');
}
} else {
throw new Exception('No properties found for this user.');
}
} else {
throw new Exception('No accounts found for this user.');
}
}
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');
}
function printResults(&$results) {
// Parses the response from the Core Reporting API and prints
// the profile name and total sessions.
if (count($results->getRows()) > 0) {
// Get the profile name.
$profileName = $results->getProfileInfo()->getProfileName();
// Get the entry for the first entry in the first row.
$rows = $results->getRows();
$sessions = $rows[0][0];
// Print the results.
print "<p>First view (profile) found: $profileName</p>";
print "<p>Total sessions: $sessions</p>";
} else {
print "<p>No results found.</p>";
}
}
$profile = getFirstProfileId($analytics);
$results = getResults($analytics, $profile);
printResults($results)
?>
Related
I want to access google analytic data using oAuth , so that I do not have to login again and again.
for that I download google analytic Php library , install it using composer , put the code provided by google , my code is below -
require_once 'vendor/autoload.php';
$analytics = initializeAnalytics();
$profile = getFirstProfileId($analytics);
$results = getResults($analytics, $profile);
printResults($results);
function initializeAnalytics()
{
// Creates and returns the Analytics Reporting service object.
// Use the developers console and download your service account
// credentials in JSON format. Place them in this directory or
// change the key file location if necessary.
$KEY_FILE_LOCATION = 'myproject.json';
// Create and configure a new client object.
$client = new Google_Client();
$client->setApplicationName("Hello Analytics Reporting");
$client->setAuthConfig($KEY_FILE_LOCATION);
$client->setScopes(['https://www.googleapis.com/auth/analytics.readonly']);
$analytics = new Google_Service_Analytics($client);
return $analytics;
}
function getFirstProfileId($analytics) {
// Get the user's first view (profile) ID.
// Get the list of accounts for the authorized user.
$accounts = $analytics->management_accounts->listManagementAccounts();
if (count($accounts->getItems()) > 0) {
$items = $accounts->getItems();
$firstAccountId = $items[0]->getId();
// Get the list of properties for the authorized user.
$properties = $analytics->management_webproperties
->listManagementWebproperties($firstAccountId);
if (count($properties->getItems()) > 0) {
$items = $properties->getItems();
$firstPropertyId = $items[0]->getId();
// Get the list of views (profiles) for the authorized user.
$profiles = $analytics->management_profiles
->listManagementProfiles($firstAccountId, $firstPropertyId);
if (count($profiles->getItems()) > 0) {
$items = $profiles->getItems();
// Return the first view (profile) ID.
return $items[0]->getId();
} else {
throw new Exception('No views (profiles) found for this user.');
}
} else {
throw new Exception('No properties found for this user.');
}
} else {
throw new Exception('No accounts found for this user.');
}
}
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');
}
function printResults($results) {
// Parses the response from the Core Reporting API and prints
// the profile name and total sessions.
if (count($results->getRows()) > 0) {
// Get the profile name.
$profileName = $results->getProfileInfo()->getProfileName();
// Get the entry for the first entry in the first row.
$rows = $results->getRows();
$sessions = $rows[0][0];
// Print the results.
print "First view (profile) found: $profileName\n";
print "Total sessions: $sessions\n";
} else {
print "No results found.\n";
}
}
When I used to run this code it providing below error -
Fatal error: Uncaught Google_Service_Exception: { "error": "invalid_client", "error_description": "The OAuth client was invalid." } in D:\wamp64\www\store2\pdf\printpdf\vendor\google\apiclient\src\Google\Http\REST.php on line 118
Basically, if anybody can provide me a step by step process of accessing data from google analytics, because I roll out my head whole day, but there is not a single post which can provide me steps to follow, some which I found are old , and not working for me
This is the code i use
Serviceaccount.php
// Load the Google API PHP Client Library.
require_once __DIR__ . '/vendor/autoload.php';
// Use the developers console and download your service account
// credentials in JSON format. Place them in this directory or
// change the key file location if necessary.
putenv('GOOGLE_APPLICATION_CREDENTIALS='.__DIR__.'/service-account.json');
$service = getAuthenticateServiceAccount();
/**
* Authenticating to Google using a Service account
* Documentation: https://developers.google.com/api-client-library/php/auth/service-accounts
* Initializes an Analyticsreporting.v4 service object.
*
* #return An authorized Analyticsreporting.v4 service object.
*/
function getAuthenticateServiceAccount() {
try {
// Create and configure a new client object.
$client = new Google_Client();
$client->useApplicationDefaultCredentials();
$client->addScope(Google_Service_Analytics::ANALYTICS);
return new Google_Service_AnalyticsReporting($client);
} catch (Exception $e) {
print "An error occurred: " . $e->getMessage();
}
}
?>
Reporting.php
// Load the Google API PHP Client Library.
require_once __DIR__ . '/vendor/autoload.php';
require_once __DIR__ . '/ServiceAccount.php';
// Create the DateRange object.
$dateRange = new Google_Service_AnalyticsReporting_DateRange();
$dateRange->setStartDate("2016-01-01");
$dateRange->setEndDate("2017-06-30");
// Create the Metrics object.
$sessions = new Google_Service_AnalyticsReporting_Metric();
$sessions->setExpression("ga:sessions");
$sessions->setAlias("ga:sessions");
$users = new Google_Service_AnalyticsReporting_Metric();
$users->setExpression("ga:users");
$users->setAlias("ga:users");
//Create the Dimensions object.
$date = new Google_Service_AnalyticsReporting_Dimension();
$date->setName("ga:date");
$pagePath = new Google_Service_AnalyticsReporting_Dimension();
$pagePath->setName("ga:pagePath");
// Create the ReportRequest object.
$request = new Google_Service_AnalyticsReporting_ReportRequest();
$request->setViewId("81692014");
$request->setPageSize("10000");
$request->setDateRanges($dateRange);
$request->setDimensions(array($date,$pagePath));
$request->setMetrics(array($sessions,$users));
$body = new Google_Service_AnalyticsReporting_GetReportsRequest();
$body->setReportRequests( array( $request) );
$data = $service->reports->batchGet( $body );
showData($data->reports[0]);
$cnt = 0;
while ($data->reports[0]->nextPageToken > 0 && $cnt < 1) {
// There are more rows for this report.
$body->reportRequests[0]->setPageToken($data->reports[0]->nextPageToken);
$data = $service->reports->batchGet( $body );
showData($data->reports[0]);
$cnt++;
}
function showData($data) {
?> <pre><table><?php
?><tr><?php // Header start row
for($i = 0; $i < sizeof($data->columnHeader->dimensions);$i++) {
?> <td> <?php print_r($data->columnHeader->dimensions[$i]); ?> </td> <?php
}
for($i = 0; $i < sizeof($data->columnHeader->metricHeader->metricHeaderEntries);$i++) {
?> <td> <?php print_r($data->columnHeader->metricHeader->metricHeaderEntries[$i]->name); ?> </td> <?php
}
?><tr><?php // Header row end
// Display data
for($i = 0; $i < sizeof($data->data->rows);$i++) {
?><tr><?php // Data row start
// Dimensions
for($d = 0; $d < sizeof($data->columnHeader->dimensions);$d++) {
?> <td> <?php print_r($data->data->rows[$i]->dimensions[$d]); ?> </td> <?php
}
// Metrics
for($m = 0; $m < sizeof($data->columnHeader->metricHeader->metricHeaderEntries);$m++) {
?> <td> <?php print_r($data->data->rows[$i]->metrics[0]->values[$m]); ?> </td> <?php
}
?><tr><?php // Header row end
}
?></table></pre><?php
}
function showText($data)
{
?> <pre> <?php print_r($data); ?> </pre> <?php
}
/**
* Returns the Analytics data.
* Documentation https://developers.google.com/analyticsreporting/v4/reference/reports/batchGet
* Generation Note: This does not always build corectly. Google needs to standardise things I need to figuer out which ones are wrong.
* #service Authenticated Analyticsreporting service.</param>
* #body A valid Analyticsreporting v4 body.</param>
* #return GetReportsResponseResponse</returns>
*/
function BatchGet($service, $body)
{
try
{
// Initial validation.
if ($service == null)
throw new Exception("service");
if ($body == null)
throw new Exception("body");
// Make the request.
return $service->reports->batchGet($body);
}
catch (Exception $ex)
{
throw new Exception("Request Reports.BatchGet failed.", $ex->getMessage());
}
}
?>
Update:
Remember to make sure you granted the service account assess to your Google analytics account at the account level.
Note code was ripped from my github project
I'm trying to get this example to work: https://developers.google.com/analytics/devguides/config/mgmt/v3/quickstart/web-php#enable
The error I'm getting is "Error: invalid_request, Missing required parameter:scope"
In order to install the google api resources, I used composer with this command:
php composer.phar require google/apiclient:^2.0.0#RC
This installed the "vendor" folder in my root site folder. My index.php and oauth2callback.php files are located in the "public_html" folder.
Here's what I have in my index.php:
<?php
// Load the Google API PHP Client Library.
require_once '../vendor/autoload.php';
// Start a session to persist credentials.
session_start();
// Create the client object and set the authorization configuration
// from the client_secretes.json you downloaded from the developer console.
$client = new Google_Client();
$client->setAuthConfigFile('client_secrets.json');
$client->addScope(Google_Service_Analytics::ANALYTICS_READONLY);
// If the user has already authorized this app then get an access token
// else redirect to ask the user to authorize access to Google Analytics.
if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {
// Set the access token on the client.
$client->setAccessToken($_SESSION['access_token']);
// Create an authorized analytics service object.
$analytics = new Google_Service_Analytics($client);
// Get the first view (profile) id for the authorized user.
$profile = getFirstProfileId($analytics);
// Get the results from the Core Reporting API and print the results.
$results = getResults($analytics, $profile);
printResults($results);
} else {
$redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . '/oauth2callback.php';
header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
}
function getFirstprofileId(&$analytics) {
// Get the user's first view (profile) ID.
// Get the list of accounts for the authorized user.
$accounts = $analytics->management_accounts->listManagementAccounts();
if (count($accounts->getItems()) > 0) {
$items = $accounts->getItems();
$firstAccountId = $items[0]->getId();
// Get the list of properties for the authorized user.
$properties = $analytics->management_webproperties
->listManagementWebproperties($firstAccountId);
if (count($properties->getItems()) > 0) {
$items = $properties->getItems();
$firstPropertyId = $items[0]->getId();
// Get the list of views (profiles) for the authorized user.
$profiles = $analytics->management_profiles
->listManagementProfiles($firstAccountId, $firstPropertyId);
if (count($profiles->getItems()) > 0) {
$items = $profiles->getItems();
// Return the first view (profile) ID.
return $items[0]->getId();
} else {
throw new Exception('No views (profiles) found for this user.');
}
} else {
throw new Exception('No properties found for this user.');
}
} else {
throw new Exception('No accounts found for this user.');
}
}
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');
}
function printResults(&$results) {
// Parses the response from the Core Reporting API and prints
// the profile name and total sessions.
if (count($results->getRows()) > 0) {
// Get the profile name.
$profileName = $results->getProfileInfo()->getProfileName();
// Get the entry for the first entry in the first row.
$rows = $results->getRows();
$sessions = $rows[0][0];
// Print the results.
print "<p>First view (profile) found: $profileName</p>";
print "<p>Total sessions: $sessions</p>";
} else {
print "<p>No results found.</p>";
}
}
Then here's what I have in my oauth2callback.php:
<?php
require_once '../vendor/autoload.php';
// Start a session to persist credentials.
session_start();
// Create the client object and set the authorization configuration
// from the client_secrets.json you downloaded from the Developers Console.
$client = new Google_Client();
$client->setAuthConfigFile('client_secrets.json');
$client->setRedirectUri('http://' . $_SERVER['HTTP_HOST'] . '/oauth2callback.php');
// Handle authorization flow from the server.
if (! isset($_GET['code'])) {
$auth_url = $client->createAuthUrl();
header('Location: ' . filter_var($auth_url, FILTER_SANITIZE_URL));
} else {
$client->authenticate($_GET['code']);
$_SESSION['access_token'] = $client->getAccessToken();
$redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . '/';
header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
}
I have read up similar errors and saw someone posting that just by adding:
passport.authenticate('google', {scope: 'https://www.googleapis.com/auth/plus.login'});
it'll work, but I don't know where to add this, nor do I know if it will solve my problem.
Also, I don't know if it's necessary to know, but the client_secrets.json file is in the same folder as the index.php file; (public_html) folder.
By the way, in my Google API manager, I have my Authorized redirect URIs set to only "http://localhost:8080/oauth2callback.php" which was what the first reference I linked in this question said to do. I don't think this should be a problem, but just wanted to get the entirety of my question here.
Can anyone help me understand what to do from here?
I'll attach a screenshot of what I'm seeing as the error.
Change this (index.php);
$client = new Google_Client();
$client->setAuthConfigFile('client_secrets.json');
$client->addScope(Google_Service_Analytics::ANALYTICS_READONLY);
To this;
$client = new Google_Client();
$client->setAuthConfigFile('client_secrets.json');
$client->addScope('https://www.googleapis.com/auth/analytics.readonly');
Also, you're missing addscope on your callback, change this (oauth2callback.php);
$client = new Google_Client();
$client->setAuthConfigFile('client_secrets.json');
$client->setRedirectUri('http://' . $_SERVER['HTTP_HOST'] . '/oauth2callback.php')
To this;
$client = new Google_Client();
$client->setAuthConfigFile('client_secrets.json');
$client->setRedirectUri('http://' . $_SERVER['HTTP_HOST'] . '/oauth2callback.php')
$client->addScope('https://www.googleapis.com/auth/analytics.readonly');
You can find more information here https://developers.google.com/api-client-library/php/start/get_started#setup
Side note;
Also, I don't know if it's necessary to know, but the
client_secrets.json file is in the same folder as the index.php file;
(public_html) folder.
This is not recommended, you should put the json file outside of the 'webapps' directory, such as a config folder.
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.
I'm want to get google+ posts via PHP, but google requires my login via browser.
It's possible provide the account's authentication via PHP, allowing me to get the posts without login every time I want to get the posts?
The code is:
<?php
require_once 'src/Google_Client.php';
require_once 'src/contrib/Google_PlusService.php';
session_start();
$client = new Google_Client();
$client->setApplicationName("Google+ PHP Starter Application");
// Visit https://code.google.com/apis/console?api=plus to generate your
// client id, client secret, and to register your redirect uri.
$client->setClientId('clientid');
$client->setClientSecret('clientsecret');
$client->setRedirectUri('http://localhost/OLA/google+/simple.php/b.html');
$client->setDeveloperKey('apikey');
$plus = new Google_PlusService($client);
if (isset($_GET['logout'])) {
unset($_SESSION['token']);
}
if (isset($_GET['code'])) { // login stuff <-------
if (strval($_SESSION['state']) !== strval($_GET['state'])) {
die("The session state did not match.");
}
$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()) {
//$me = $plus->people->get('me');
//print "Your Profile: <pre>" . print_r($me, true) . "</pre>";
$params = array('maxResults' => 100);
$activities = $plus->activities->listActivities('me', 'public', $params);
//print "Your Activities: <pre>" . print_r($activities, true) . "</pre>";
$params = array(
'orderBy' => 'recent',
'maxResults' => '20'//20
);
$q = "tag";
$results = $plus->activities->search($q, $params);
//code ....
// The access token may have been updated lazily.
$_SESSION['token'] = $client->getAccessToken();
} else {
// This is the part that logs me in via browser <------
$state = mt_rand();
$client->setState($state);
$_SESSION['state'] = $state;
$authUrl = $client->createAuthUrl();
print "<a class='login' href='$authUrl'>Connect Me!</a>";
}
?>
Yep, just call as you would and use the simple API access key - you can retrieve public information, but you will have to supply to long numeric ID for the user you're retrieving posts for rather than using the string 'me'. Take a look at the latest version of the library as well: https://github.com/google/google-api-php-client as well. You need to setup your client as you were doing, with an API key from a project which has the Google+ enabled on https://developers.google.com/console
$client = new Google_Client();
$client->setApplicationName("Post Fetcher");
$client->setDeveloperKey('PUT_YOUR_API_KEY_HERE_OR_IT_WONT_WORK');
$plus = new Google_Service_Plus($client);
$activities = $this->plus->activities
->listActivities("118051310819094153327", "public");
I have been Googling this for going on hours now. I have followed the Hello Analytics tutorial.
The application runs fine until the user has granted permission from the Google 'consent screen' at which point i receive the following error:
There wan a general error : Error calling GET My url
(403) Access Not Configured. Please use Google Developers Console to
activate the API for your project.
I have checked in the developer console and Analytics API is enabled and, after reading other posts on this, have added Google+ and Drive access.
NOTE: I am running this application locally and redirecting the redirecting back to 127.0.0.1.
I have added my code below for reference although I think the issue is to do with my google console account and / or running this application locally.
Appreciate any help with this guys. Please let me know if any further information is required.
==================================================================================
// --------------------- Google libraries
require_once 'google-api-php-client/src/Google_Client.php';
require_once 'google-api-php-client/src/contrib/Google_AnalyticsService.php';
session_start();
// --------------------- Application credentials
$client = new Google_Client();
$client->setApplicationName('Interim Testing Tool');
$client->setClientId('xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.apps.googleusercontent.com');
$client->setClientSecret('xxxxxxxxxxxxxxxxxxxxxxxx');
$client->setRedirectUri('http://127.0.0.1');
$client->setDeveloperKey('xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx');
$client->setScopes(array('https://www.googleapis.com/auth/analytics.readonly'));
// Returns objects from the Analytics Service instead of associative arrays.
$client->setUseObjects(true);
// --------------------- Client access checks
// Handle authorization flow from the server
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));
}
// Retrieve and use stored credentials if set
if (isset($_SESSION['token'])) {
$client->setAccessToken($_SESSION['token']);
}
if (!$client->getAccessToken()) {
// CLient not logged in create a connect button
$authUrl = $client->createAuthUrl();
print "<a class='login' href='$authUrl'>Connect Me!</a>";
} else {
$analytics = new Google_AnalyticsService($client);
runMainDemo($analytics);
}
//-------------------------------------------------------------- Run main demo
function runMainDemo($analytics) {
try {
// Get the user's first view (profile) ID.
$profileId = getFirstProfileId($analytics);
if (isset($profileId)) {
// Query the Core Reporting API.
$results = getResults($analytics, $profileId);
// 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();
}
}
// ------------------------------------------------------------------ Get first profile id
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.');
}
}