Not getting Google analytics data in PHP - php

I am trying to get analytics data can someone help me, below are the ways I tried but I am getting 500 internal server.
<?php
require_once realpath(dirname(__FILE__) . '/google-api-php-client-master/src/Google/autoload.php');
session_start();
$client = new Google_Client();
$client->setApplicationName("meme");
$client->setDeveloperKey('my app key here');
$service = new Google_Service_Analytics($client);
$projectId = '103785255';
$from = '2016-01-18'; // 2 days
$to = date('Y-m-d'); // today
$metrics = 'ga:pageviews';
$dimensions = 'ga:date,ga:year,ga:month,ga:day';
$data = $service->data_ga->get('ga:'.$projectId, $from, $to, $metrics, array('dimensions' => $dimensions));
print_r($data);
?>
Second method with oauth-2.0 authentication
<?php
require_once realpath(dirname(__FILE__) . '/google-api-php-client-master/src/Google/autoload.php');
session_start();
$client_id = 'my client id .apps.googleusercontent.com';
$client_secret = 'my client secret';
$redirect_uri = 'redirect uri';
$client = new Google_Client();
$client->setApplicationName("meme");
$client->setClientId($client_id);
$client->setClientSecret($client_secret);
$client->addScope(Google_Service_Drive::DRIVE_METADATA_READONLY);
$client->setRedirectUri($redirect_uri);
$client->setAccessType("offline");
if (isset($_GET['code'])) {
$client->authenticate($_GET['code']);print_r($client);exit;
$_SESSION['token'] = $client->getAccessToken();
header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
}
if (!$client->getAccessToken() && !$_SESSION['token']) {
$authUrl = $client->createAuthUrl();
print "<div><a class='login' href='$authUrl'>Connect Me!</a></div>";
}
if($_SESSION['token']){
$client->setAccessToken($_SESSION['token']);
$service = new Google_Service_Analytics($client);
$projectId = '103785255';
$_params[] = 'pageviews';
$from = '2016-01-18'; // 2 days
$to = date('Y-m-d'); // today
$metrics = 'ga:pageviews';
$dimensions = 'ga:date,ga:year,ga:month,ga:day';
$data = $service->data_ga->get('ga:'.$projectId, $from, $to, $metrics, array('dimensions' => $dimensions));
foreach($data['totalsForAllResults'] as $row) {
echo $row;
}
}
?>
If you see I have placed a print statement after $client->authenticate($_GET['code']); where I am getting 500 internal server error If I print the code before authenticate method it is printing, facing issue while calling $client->authenticate($_GET['code']). Even followed the below links and endup with the same issues
Google PHP client won't authenticate code, invalid_request
http://www.daimto.com/google-oauth2-php/

Related

Getting 'Forbidden error' when trying to execute youtube analytic API

I am receiving an error message when trying to execute youtube analytics API.
A service error occurred: Error calling GET
https://www.googleapis.com/youtube/analytics/v1/reports?ids=channel%3D%3DUCaayLD9i5x4MmIoVZxXSv_g&start-date=2016-08-01&end-date=2016-08-07&metrics=views&dimensions=7DayTotals:
(403) Forbidden
Here is my code:
require_once __DIR__.'\google-api-php-client-1-master\src\Google\autoload.php';
require_once __DIR__.'\google-api-php-client-1-master\src\Google\Client.php';
require_once __DIR__.'\google-api-php-client-1-master\src\Google\Service\YouTube.php';
session_start();
$key = file_get_contents('mykey.json');
$OAUTH2_CLIENT_ID = 'xx-xx-xx';
$OAUTH2_CLIENT_SECRET = 'xxx';
$scope = array("https://www.googleapis.com/auth/youtube.force-ssl", "https://www.googleapis.com/auth/youtubepartner-channel-audit", "https://www.googleapis.com/auth/youtube", "https://www.googleapis.com/auth/youtube.readonly", "https://www.googleapis.com/auth/yt-analytics.readonly", "https://www.googleapis.com/auth/yt-analytics-monetary.readonly","https://www.googleapis.com/auth/youtubepartner");
$client = new Google_Client();
$client->setClientId($OAUTH2_CLIENT_ID);
$client->setClientSecret($OAUTH2_CLIENT_SECRET);
$client->setAccessType('offline');
$client->setAccessToken($key);
$client->setScopes($scope);
if ($client->getAccessToken()) {
//Check to see if our access token has expired. If so, get a new one and save it to file for future use.
if($client->isAccessTokenExpired()) {
//refresh your access token if it's expired
$newToken = json_decode($client->getAccessToken());
$client->refreshToken($newToken->refresh_token);
file_put_contents('mykey.json', $client->getAccessToken());
}
$analytics = new Google_Service_YouTubeAnalytics($client);
$channel_url = 'UCaayLD9i5x4MmIoVZxXSv_g';
$ids = 'channel==' . $channel_url . '';
$end_date = '2016-08-07';
$start_date = '2016-08-01';
$optparams = array(
'dimensions' => '7DayTotals',
);
$metric = 'views';
$api = $analytics->reports->query($ids, $start_date, $end_date, $metric, $optparams);
echo '<pre>';print_r($api);die;
}
I have already enable 'youtube analytic API' and I get the access_token from here
What is wrong with my code ,Or do we need to do some more stuff to get rid from this?
Looking at your code, it seems that you are generating a new access token at the point you save it to file (invalidating the first one).
Try :
if($client->isAccessTokenExpired()) {
//refresh your access token if it's expired
$newToken = json_decode($client->getAccessToken());
$client->refreshToken($newToken->refresh_token);
file_put_contents('mykey.json', $newToken);
}

Error Using PHP to add an event to Google Calendar

Like so many others before me, I'm having great difficulty getting full functionality to a PHP script that adds/deletes/Updates Google Calendar events.
My code, from the Daimto web site works using Oauth2 in that it lists the current events in my main calendar.
However when I add some code to add an event, the page is blank and I'm unable to trap an error.
The code is:
<?php
require_once realpath(dirname(__FILE__) . '/../src/Google/autoload.php');
session_start();
// ******************************************************** //
// Get these values from https://console.developers.google.com
// Be sure to enable the Analytics API
// ******************************************************** //
$client_id = 'xxx.apps.googleusercontent.com';
$client_secret = 'xxxkQO8K';
$redirect_uri = 'xxx/GoogleCalendar/tests/MGC_NEW.php';
$client = new Google_Client();
$client->setApplicationName("primary");
$client->setClientId($client_id);
$client->setClientSecret($client_secret);
$client->setRedirectUri($redirect_uri);
$client->setAccessType('offline'); // Gets us our refreshtoken
$client->setScopes(array('https://www.googleapis.com/auth/calendar'));
//For loging out.
if (isset($_GET['logout'])) {
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 (!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'])) {
$client->setAccessToken($_SESSION['token']);
print "<a class='logout' href='http://www.marchgolfclub.co.uk?logout=1'>LogOut</a><br>";
$service = new Google_Service_Calendar($client);
$calendarList = $service->calendarList->listCalendarList();
//print_r($calendarList);
while(true) {
foreach ($calendarList->getItems() as $calendarListEntry) {
echo $calendarListEntry->getSummary()."<br>\n";
// get events
$events = $service->events->listEvents($calendarListEntry->id);
foreach ($events->getItems() as $event) {
/*Code to add holiday and Bank Holidays etc.*/
//echo "-----".$event->getSummary()."<br>";
}
}
$pageToken = $calendarList->getNextPageToken();
if ($pageToken) {
$optParams = array('pageToken' => $pageToken);
$calendarList = $service->calendarList- >listCalendarList($optParams);
} else {
break;
}
}
//THIS IS WHERE THE CODE BREAKS DOWN
echo "<hr><font size=+1>I have access to your calendar</font>";
$event = new Google_Service_Calendar_Event($client);
$event->setSummary(‘Interview’);
$event->setLocation(‘Hell’);
$start = new Google_Service_Calendar_EventDateTime();
$start->setDateTime(‘2015-10-03T10:00:00.000-07:00’);
$event->setStart($start);
$end = new Google_Service_Calendar_EventDateTime();
$end->setDateTime(‘2015-10-03T10:25:00.000-07:00′);
$event->setEnd($end);
$attendee1 = new Google_Service_Calendar_EventAttendee();
$attendee1->setEmail(’email#abc.com’);
// …
$attendees = array($attendee1);
$event->attendees = $attendees;
//$createdEvent = $service->events->insert(‘primary’, $event);
//Google code error was fixed
$createdEvent = $service->events->insert($calName, $event);
//echo $createdEvent->getId();
var_dump($createdEvent);
echo "<br><font size=+1>Event created</font>";
//END OF BROKEN CODE
}
?>`
Can anyone help?

get google account image using google api

At the very first time,I'm trying to get my google account profile picture by using google api. So I have referred Refer this site.
so in my google-plus-access.php:
<?php
require_once 'google-api-php-client-master/src/Google/autoload.php'; // or wherever autoload.php is located
session_start();
$client = new Google_Client();
$client->setApplicationName("Google+ PHP Starter Application");
$client->setClientId('MY_CLIENT_ID');
$client->setClientSecret('MY_SECRET_KEY');
$client->setRedirectUri('http://localhost/G-api');
$client->setDeveloperKey('MY_DEV_KEY');
$client->setScopes(array('https://www.googleapis.com/auth/plus.me'));
//$plus = new apiPlusService($client);
$plus = $client -> createAuthUrl();
if(isset($_REQUEST['logout']))
{
unset($_SESSION['access_token']);
}
if(isset($_GET['code']))
{
echo $_GET['code'];
$client->authenticate();
$_SESSION['access_token'] = $client->getAccessToken();
header('Location: http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF']);
}
if(isset($_SESSION['access_token']))
{
echo $_SESSION['access_token'];
$client->setAccessToken($_SESSION['access_token']);
}
if ($client->getAccessToken()) {
$me = $plus->people->get('me');
echo $me;
$optParams = array('maxResults' => 100);
$activities = $plus->activities->listActivities('me', 'public', $optParams);
$_SESSION['access_token'] = $client->getAccessToken();
} else {
$authUrl = $client->createAuthUrl();
echo '<pre>';
print_r($authUrl); // this block is running!!!
echo '</pre>';
}
echo "</br>";
?>
And in my index.php:
<?php
include('google-plus-access.php');
?>
<img src="<?php echo(substr($me['image']['url'],0,stripos($me['image']['url'],'?sz='))); ?>?sz=200" />
but i'm getting the result as:
https://accounts.google.com/o/oauth2/auth?response_type=code&redirect_uri=http%3A%2F%2Flocalhost%2FG-api&client_id=887633147241-8ragvhdi97lga3n829qogpl5aoima7l5.apps.googleusercontent.com&scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fplus.me&access_type=online&approval_prompt=auto
In my console I'm getting the below error:
My output scree is looking like this :
EDIT:
In my console i'm getting GET http://localhost/G-api/%3Cbr%20/%3E%3Cb%3ENotice%3C/b%3E:%20%20Undefined%20…/G-api/index.php%3C/b%3E%20on%20line%20%3Cb%3E7%3C/b%3E%3Cbr%20/%3E?sz=200 403 (Forbidden) this.
These things are done in local.So some body making me scared that we can't do this is local and we have create domain for that.So kindly help me to do this.
Check your code $me is created in the if // this block is running!!!
is in the else.
You are trying to use $me which hasn't been created.
if ($client->getAccessToken()) {
$me = $plus->people->get('me'); //Daimto: This doesn't run so you cant use it
echo $me;
$optParams = array('maxResults' => 100);
$activities = $plus->activities->listActivities('me', 'public', $optParams);
$_SESSION['access_token'] = $client->getAccessToken();
} else {
$authUrl = $client->createAuthUrl();
echo '<pre>';
print_r($authUrl); // this block is running!!!
echo '</pre>';
}
You also need to create a service, $plus->people->get('me'); isn't going to work because $plus isn't a Google_Service_Plus. You should check out the example found here user-sample.php
$googlePlus = new Google_Service_Plus($client);
$userProfile = $googlePlus->people->get('me');

Google Drive PHP API Download file

I have problem with downloading file from google drive using php api. I managed to upload file to google drive in folder and $service->files->insert returns to me File Resource which has attribute downloadUrl but when I redirect to that url, it does not work. I get 401 error. Why is this happening? What do I need to do make this work?
Here's code:
<?php
require_once 'vendor/autoload.php';
session_start();
$client_id = 'xxx';
$client_secret = 'yyy';
$redirect_uri = 'http://localhost/GoogleDrive/code.php';
$client = new Google_Client();
$client->setClientId($client_id);
$client->setClientSecret($client_secret);
$client->setRedirectUri($redirect_uri);
$client->addScope("https://www.googleapis.com/auth/drive");
$service = new Google_Service_Drive($client);
$authUrl = $client->createAuthUrl();
header("Location: $authUrl");
and code.php
require_once 'vendor/autoload.php';
session_start();
$client_id = 'xxx';
$client_secret = 'yyy';
$redirect_uri = 'http://localhost/GoogleDrivePayload/code.php';
$client = new Google_Client();
$client->setClientId($client_id);
$client->setClientSecret($client_secret);
$client->setRedirectUri($redirect_uri);
$client->setApprovalPrompt('force');
$client->addScope("https://www.googleapis.com/auth/drive");
$service = new Google_Service_Drive($client);
if (isset($_GET['code'])) {
$client->authenticate($_GET['code']);
$_SESSION['upload_token'] = $client->getAccessToken();
$redirect = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL));
}
if (isset($_SESSION['upload_token']) && $_SESSION['upload_token']) {
$client->setAccessToken($_SESSION['upload_token']);
if ($client->isAccessTokenExpired()) {
unset($_SESSION['upload_token']);
}
}
if ($client->getAccessToken()) {
$file = new Google_Service_Drive_DriveFile();
$file->setTitle("hello.exe");
$file->setDescription("LALALALALAL");
$file->setMimeType('application/x-msdos-program');
$parent = new Google_Service_Drive_ParentReference();
$parent->setId("zzz");
$file->setParents(array($parent));
$data = file_get_contents('hello.exe');
$createdFile = $service->files->insert($file, array(
'data' => $data,
'mimeType' => 'application/x-msdos-program',
'uploadType' => 'multipart',
"visibility" => "DEFAULT"
));
header("Location: " . $createdFile->downloadUrl);
}
downloadUrl is exactly what it says, ie. the URL your PHP app can use to fetch the file. You would almost never redirect a browser to that URL, and if you did (you probably really don't want to), you'll need append a valid access token to the URL to fix the 401.

Google OAuth 2.0 refresh token for web application with public access

I'm getting the following error:
The OAuth 2.0 access token has expired, and a refresh token is not available. Refresh tokens are not returned for responses that were auto-approved
I have a web application which only my server will be accessing, the initial auth works fine, but after an hour, the aforementioned error message pops up. My script looks like this:
require_once 'Google/Client.php';
require_once 'Google/Service/Analytics.php';
session_start();
$client = new Google_Client();
$client->setApplicationName("Client_Library_Examples");
$client->setDeveloperKey("{MY_API_KEY}");
$client->setClientId('{MY_CLIENT_ID}.apps.googleusercontent.com');
$client->setClientSecret('{MY_KEY}');
$client->setRedirectUri('{MY_REDIRECT_URI}');
$client->setScopes(array('https://www.googleapis.com/auth/gmail.readonly'));
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));
}
if (!$client->getAccessToken() && !isset($_SESSION['token'])) {
$authUrl = $client->createAuthUrl();
print "<a class='login' href='$authUrl'>Connect Me!</a>";
}
How can I set up a refresh token for this?
Edit 1: I've tried doing this with a Service account as well. I followed the documentation available on GitHub:
https://github.com/google/google-api-php-client/blob/master/examples/service-account.php
My script looks like this:
session_start();
include_once "templates/base.php";
require_once 'Google/Client.php';
require_once 'Google/Service/Gmail.php';
$client_id = '{MY_CLIENT_ID}.apps.googleusercontent.com';
$service_account_name = '{MY_EMAIL_ADDRESS}#developer.gserviceaccount.com ';
$key_file_location = 'Google/{MY_KEY_FILE}.p12';
echo pageHeader("Service Account Access");
if ($client_id == ''
|| !strlen($service_account_name)
|| !strlen($key_file_location)) {
echo missingServiceAccountDetailsWarning();
}
$client = new Google_Client();
$client->setApplicationName("Client_Library_Examples");
$service = new Google_Service_Gmail($client);
if (isset($_SESSION['service_token'])) {
$client->setAccessToken($_SESSION['service_token']);
}
$key = file_get_contents($key_file_location);
$cred = new Google_Auth_AssertionCredentials(
$service_account_name,
array('https://www.googleapis.com/auth/gmail.readonly'),
$key
);
$client->setAssertionCredentials($cred);
if($client->getAuth()->isAccessTokenExpired()) {
$client->getAuth()->refreshTokenWithAssertion($cred);
}
This returns the following message:
Error refreshing the OAuth2 token, message: '{ "error" : "invalid_grant" }''
After tracking this code to it's source, which can be found in Google/Auth/OAuth2.php
The method in question, refreshTokenRequest:
private function refreshTokenRequest($params)
{
$http = new Google_Http_Request(
self::OAUTH2_TOKEN_URI,
'POST',
array(),
$params
);
$http->disableGzip();
$request = $this->client->getIo()->makeRequest($http);
$code = $request->getResponseHttpCode();
$body = $request->getResponseBody();
if (200 == $code) {
$token = json_decode($body, true);
if ($token == null) {
throw new Google_Auth_Exception("Could not json decode the access token");
}
if (! isset($token['access_token']) || ! isset($token['expires_in'])) {
throw new Google_Auth_Exception("Invalid token format");
}
if (isset($token['id_token'])) {
$this->token['id_token'] = $token['id_token'];
}
$this->token['access_token'] = $token['access_token'];
$this->token['expires_in'] = $token['expires_in'];
$this->token['created'] = time();
} else {
throw new Google_Auth_Exception("Error refreshing the OAuth2 token, message: '$body'", $code);
}
}
Which means that the $code variable is NULL.
I found this post on SO:
Error refreshing the OAuth2 token { “error” : “invalid_grant” }
And can see that there is still no prefered solution. This is driving me nuts. There is very little to no documentation available on this and if anybody has a solution, I'm sure I'm not the only one looking for it.
Each access_token expires after a few seconds and need to be refreshed by refresh_token, "Offline access" is what you are looking for. Here you can follow the documentation:
https://developers.google.com/accounts/docs/OAuth2WebServer#offline
To obtain a refresh_token you have to run this code only one time:
require_once 'Google/Client.php';
$client = new Google_Client();
$client->setClientId('{MY_CLIENT_ID}.apps.googleusercontent.com');
$client->setClientSecret('{MY_KEY}');
$client->setRedirectUri('{MY_REDIRECT_URI}');
//next two line added to obtain refresh_token
$client->setAccessType('offline');
$client->setApprovalPrompt('force');
$client->setScopes(array('https://www.googleapis.com/auth/gmail.readonly'));
if (isset($_GET['code'])) {
$credentials = $client->authenticate($_GET['code']);
/*TODO: Store $credentials somewhere secure */
} else {
$authUrl = $client->createAuthUrl();
print "<a class='login' href='$authUrl'>Connect Me!</a>";
}
$credentials includes an access token and a refresh token. You have to store this to obtain new access tokens at any time. So when you wanted to make a call to api:
require_once 'Google/Client.php';
require_once 'Google/Service/Gmail.php';
/*TODO: get stored $credentials */
$client = new Google_Client();
$client->setClientId('{MY_CLIENT_ID}.apps.googleusercontent.com');
$client->setRedirectUri('{MY_REDIRECT_URI}');
$client->setClientSecret('{MY_KEY}');
$client->setScopes(array('https://www.googleapis.com/auth/gmail.readonly'));
$client->setAccessToken($credentials);
$service = new Google_Service_Gmail($client);

Categories