How to set up google analytics account service? - php

I'm new in using Google Analytics API and I'm facing a problem.
i got the error labeled as (403) User does not have any Google Analytics account.
With my google account I am able to view google anaytics pages and by code, I just can't.
Here is my code. i think I misused something in the 6 first lines, but what ?
Any idea is welcomed.
$scope = "https://www.googleapis.com/auth/analytics";
$client_id = "[12 numbers]-[32 letters/numbers].apps.googleusercontent.com";
$service_account_name = "[same 12 numbers]-[same 32 letters/numbers] #developer.gserviceaccount.com";
$key_file_location = "./google-account-service.p12";
$projectId = "[same 12 numbers]";
$projectName = "[my project name defined in console.developers.google.com]";
$client = new Google_Client();
$client->setApplicationName($projectName);
$key = file_get_contents($key_file_location);
$cred = new Google_Auth_AssertionCredentials($service_account_name, array($scope), $key);
$client->setAssertionCredentials($cred);
if($client->getAuth()->isAccessTokenExpired()){
$client->getAuth()->refreshTokenWithAssertion($cred);
}
$client->getAccessToken();
$service = new Google_Service_Analytics($client);
// metrics
$_params[] = 'date';
$_params[] = 'date_year';
$_params[] = 'date_month';
$_params[] = 'date_day';
// dimensions
$_params[] = 'visits';
$_params[] = 'pageviews';
$_params[] = 'bounces';
$_params[] = 'entrance_bounce_rate';
$_params[] = 'visit_bounce_rate';
$_params[] = 'avg_time_on_site';
$from = date('Y-m-d', time()-2*24*60*60); // 2 days
$to = date('Y-m-d'); // today
$metrics = 'ga:visits,ga:pageviews,ga:bounces,ga:entranceBounceRate,ga:visitBounceRate,ga:avgTimeOnSite';
$dimensions = 'ga:date,ga:year,ga:month,ga:day';
$data = $service->data_ga->get('ga:'.$projectId, $from, $to, $metrics, array('dimensions' => $dimensions));
foreach($data['rows'] as $row) {
$dataRow = array();
foreach($_params as $colNr => $column) echo $column . ': '.$row[$colNr].', ';
}

the service account mail that you use is not valid. You need to create a project in console.developers.google.com and activate the api for google analytics. then you will get acces to you service account email use it in your code.

just a tip i noticed in your code u set the $projectid = the first 12 number as in the $clientid which is as far as i know wrong .. the $projectid must be equal to ( go to your google analytics account , take a look at the URL you will notice there is a segment looks like /a39569200w68518820p70543179/ take the numbers after the 'p' letter in this case the 70543179 numbers and set them as a value for $projectid variable ) i dont know if it solve your problem but i think you should know ..

Related

Updating Google Calendar - Fatal error: Call to undefined function dateTime()

I am trying to update Google Calendar using the PHP API. I have successfully been able to create Google Calendar Events and automatically get the ID for the event, but when I try and update the event, I get this error:
PHP Fatal error: Call to undefined function dateTime() in public_html/googleapi/calendarupdate.php on line 45. It is referring to the line:
$event->setStart.dateTime($startdatetime);
Here is my current PHP Code for the error:
<?php
header('Content-type: application/json');
require_once __DIR__ . '/google-api-php-client/src/Google/autoload.php';
$summary = $_POST["summary"];
$location = $_POST["location"];
$description = $_POST["description"];
$startdatetime = $_POST["startdatetime"];
$enddatetime = $_POST["enddatetime"];
$clientemail = $_POST["clientemail"];
$privatekey = $_POST["privatekey"];
$useremail = $_POST["useremail"];
$calendarid = $_POST["calendarid"];
$client_email = $clientemail;
$private_key = file_get_contents($privatekey);
$scopes = array('https://www.googleapis.com/auth/calendar');
$user_to_impersonate = $useremail;
$credentials = new Google_Auth_AssertionCredentials(
$client_email,
$scopes,
$private_key,
'notasecret', // Default P12 password
'http://oauth.net/grant_type/jwt/1.0/bearer', // Default grant type
$user_to_impersonate
);
$client = new Google_Client();
$client->setAssertionCredentials($credentials);
if ($client->getAuth()->isAccessTokenExpired()) {
$client->getAuth()->refreshTokenWithAssertion();
}
$service = new Google_Service_Calendar($client);
$event = $service->events->get($useremail, $calendarid);
$event->setSummary($summary);
$event->setLocation($location);
$event->setStart.dateTime($startdatetime);
$event->setStart.timeZone('America/Los_Angeles');
$event->setEnd.dateTime($enddatetime);
$event->setEnd.timeZone('America/Los_Angeles');
$event->setDescription($description);
$updatedEvent = $service->events->update($useremail, $event->getId(), $event);
echo json_encode($updatedEvent);
My PHP code is based off of Google's API Documentation found here.
Ok, I actually managed to figure it out. I just had to change the line:
$event->setStart.dateTime($startdatetime);
To This:
$event->start->setDateTime($startdatetime);
I do the same general thing for the end datetime, except where it says start, I just put end. Just tested it and it worked perfectly. The site that helped me out can be found here.

Google Cloud DNS Services - entity.change parameter is required but missing

With the following code using Google's PHP API Client I am receiving this response.
Google_Service_Exception with message 'Error calling POST https://www.googleapis.com/dns/v1/projects/PROJECT-NAME/managedZones/DNSZONE/changes: (400) The 'entity.change' parameter is required but was missing.
Where PROJECT-NAME and DNSZONE are my project and zone.
$client_email = MYCLIENT;
$private_key = file_get_contents('config/credentials/KEY.p12');
$scopes = array('https://www.googleapis.com/auth/ndev.clouddns.readwrite');
$project = "PROJECT-NAME";
$managedZone = "DNSZONE";
$creds = new Google_Auth_AssertionCredentials($client_email,$scopes,$private_key);
$client = new Google_Client();
$client->setAssertionCredentials($creds);
$resource = new Google_Service_Dns_ResourceRecordSet();
$resource->kind = "dns#resourceRecordSet";
$resource->name = "testing.DNSZONE.net.";
$resource->rrdatas[] = "testing.otherhost.com.";
$resource->ttl = 800;
$resource->type = "CNAME";
$dns = new Google_Service_Dns($client);
$change = new Google_Service_Dns_Change();
$change->kind = "dns#change";
$change->setAdditions($resource);
$dns->changes->create($project,$managedZone,$change);
I am a bit confused as to how to set this parameter. Or where I am even am to define it.
Just for clarify what the answer is, setAdditions expects an array.
$change->setAdditions([ $resource ]);

Google Calendar API, getItem and getSummery returns nothing

I seem to have bumped into a google calendar api problem. and I can't really see where I have made the error so an extra set of eyes would be greatly appreciated. The problem in short is that the part of the code that should output the events.. doesn't (the "result" part of the code.
require_once "./google-api-php-client/src/Google/Client.php";
require_once "./google-api-php-client/src/Google/Service/Calendar.php";
// Service Account info
$client_id = "XXXXXX-XXXXXXXXXXXXXXXXXXXXX.apps.googleusercontent.com";
$app_name = "Some-name";
$service_account_name = 'XXXXX-XXXXXXXXXXXXXXXXXXXXXXX#developer.gserviceaccount.com';
$key_file_location = 'google-api-php-client/Some-name-xxxxxxxxxx.p12';
$cal_id = "primary";
// Service Account info
$client_id = $client_id;
$service_account_name = $service_account_name;
$key_file_location = $key_file_location;
// Calendar id
$calName = $cal_id;
$client = new Google_Client();
$client -> setApplicationName($app_name);
$service = new Google_Service_Calendar($client);
$key = file_get_contents($key_file_location);
$cred = new Google_Auth_AssertionCredentials(
$service_account_name,
array('https://www.googleapis.com/auth/calendar.readonly'),
$key
);
$client->setAssertionCredentials($cred);
$cals = $service->calendarList->listCalendarList();
print_r($cals);
echo "<br>events<br>";
$events = $service->events->listEvents($calName);
var_dump($events);
echo "<br>result:<br>";
// the following is what returns nothing, works fine until this point.
$i = 0;
foreach ( $events->getItems() as $event ) {
echo 'i:'.$i.' '.$event->getSummary();
$i++;
}
echo 'end';
Change $events to the below line:
$events = $service->events->listEvents('primary', $params);
Instead of primary, add $calName and also send $params in listEvents method.
Hope this works.

PHP Google Analytics API - Simple example

I am trying to set some basic example of using Google Analytics with this library: https://github.com/google/google-api-php-client
For starter I have:
<?php
require_once 'Google/Client.php';
require_once 'Google/Service/Analytics.php';
$client = new Google_Client();
$client->setApplicationName("Client_Library_Examples");
$client->setDeveloperKey("MY_SECRET_API"); //security measures
$service = new Google_Service_Analytics($client);
$results = $service->data_ga;
echo '<pre>';
print_r($results);
echo '</pre>';
Q: How to get data from Google Analytics from this query ?
/*
https://www.googleapis.com/analytics/v3/data/
ga?ids=ga%123456
&dimensions=ga%3Acampaign
&metrics=ga%3Atransactions
&start-date=2013-12-25
&end-date=2014-01-08
&max-results=50
*/
$client->setDeveloperKey("MY_SECRET_API");
First of all, for as far as I experienced this won't work for authentication, you'll need to use a OAuth2 authentication. There are two options to do this, using client ID for web application or using a service account. Authorization api
After you have this, you can make a call like this.
(I use a service account here)
First authenticate:
$key = file_get_contents($key_file_location);
$cred = new Google_Auth_AssertionCredentials(
$service_account_name,
array('https://www.googleapis.com/auth/analytics.readonly'),
$key
);
$client->setAssertionCredentials($cred);
Make a call:
$ids = 'ga:123456'; //your id
$startDate = '2013-12-25';
$endDate = '2014-01-08';
$metrics = 'ga:transactions';
$optParams = array(
'dimensions' => 'ga:campaign',
'max-results' => '50'
);
$results = $service->data_ga->get($ids, $startDate, $endDate, $metrics, $optParams);
//Dump results
echo "<h3>Results Of Call:</h3>";
echo "dump of results";
var_dump($results);
echo "results['totalsForAllResults']";
var_dump($results['totalsForAllResults']);
echo "results['rows']";
foreach ($results['rows'] as $item) {
var_dump($item);
}
You will need to do a http get to get the information from the url.
http://www.php.net/manual/en/function.http-get.php
Remember you will still need to add the Oauth2 auth code to the string before you can send that request. This link might help if you dont have auth code already.
https://developers.google.com/analytics/solutions/articles/hello-analytics-api#authorize_access
what you could do is create a new function...
function ga_campaign_transactions($gaEmail, $gaPass, $gProfile, $limit)
{
require_once('classes/google-analytics/gapi.class.php');
$gDimensions = array('campaign');
$gMetrics = array('transactions');
$gSortMetric = NULL;
$gFilter = '';
$gSegment = '';
$gStartDate = '2013-12-25';
$gEndDate = '2014-01-08';
$gStartIndex = 1;
$gMaxResults = $limit;
$ga = new gapi($gaEmail, $gaPass);
$ga->requestReportData($gProfile, $gDimensions, $gMetrics, $gSortMetric, $gFilter, $gSegment, $gStartDate, $gEndDate, $gStartIndex, $gMaxResults);
$gAnalytics_results = $ga->getResults();
//RETURN RESULTS
return $gAnalytics_results;
}
$gProfile = '123456'; // The Profile ID for the account, NOT GA:
$gaEmail = 'YOUR GOOGLE EMAIL'; // Google Email address.
$gaPass = 'YOUR GOOGLE PASSWORD'; // Google Password.
// NOTE: if 2 step login is turned on, create an application password.
$limit = 50;
$ga_campaign_transactions = ga_campaign_transactions($gaEmail, $gaPass, $gProfile, $limit)
//OUTPUT
if(!empty($ga_campaign_transactions))
{
$counter=0;
$gaCampResults= array(); // CREATE ARRAY TO STORE ALL RESULTS
foreach($ga_campaign_transactions as $row)
{
$dim_list = $row->getDimesions();
$met_list = $row->getMetrics();
$gaCampResults[$counter]['campaign'] = $dim_list['campaign'];
$gaCampResults[$counter]['transactions'] = $met_list['transactions'];
$counter++;
}
}
if(!empty($gaCampResults))
{
$totalCampTransactions = count($gaCampResults);
?>
<h2>We Found ( <?php echo number_format($totalCampTransactions,0);?> ) Results</h2>
<ul>
<?php
foreach($gaCampResults as $gaRow){
echo "<li>Campaign:".$gaRow['campaign']." | Transactions: ".$gaRow['transactions']."</li>";
}
?>
</ul>
<?php
}
find Analytics Profile ID
Create Google Application password
Hopefully that puts you on the right track :)
untested this, but similar to what I've been using...
Marty

Google Calendar API batch request PHP

i am trying to send a bunch of events via an Batch Request to Google Calendar.
But i cant figur out how to do. https://developers.google.com/google-apps/calendar/batch doesnt help me.
require_once 'google-api-php-client/src/Google_Client.php';
require_once 'google-api-php-client/src/contrib/Google_CalendarService.php';
$client = new Google_Client();
$client->setUseBatch(true);
$batch = new Google_BatchRequest();
$uri = 'http://www.google.com/calendar/feeds/default/private/full/batch';
$batchContent = file_get_contents('xxxxx/google-api-php-client/batch.xml');
$batch->add($batchContent);
batch.xml contains 2 -items.
Thats all so far. But nothing happened.
I also have tried
$batch->execute()
But thats throws error without message.
My question: How to send a Batch via PHP to Google Calendar ?
I'm using the latest version of Google APIs Client Library for PHP (Google Calendar v.3). I use batch operations for pushing instructor lessons to Google Calendar. Here is my example of code for you (multipleInsert function). Good luck!
<?php
require_once(APPPATH . 'libraries/Google/Client.php');
require_once(APPPATH . 'libraries/Google/Http/Batch.php');
require_once(APPPATH . 'libraries/Google/Service/Calendar.php');
class My_google_calendar
{
...
/** Add single Event for Student */
function addEvent($lesson, $instructor, $return_request = false, $enable_attendees = false)
{
$calendar = $this->getGoogleCalendar(); // get calendar service variable
$lesson_from = date(DATE_RFC3339, $lesson->from);
$lesson_to = date(DATE_RFC3339, $lesson->from + $lesson->duration);
$event = new Google_Service_Calendar_Event();
$event->setSummary('Lesson with student: '$lesson->student_full_name);
$start = new Google_Service_Calendar_EventDateTime();
$start->setDateTime($lesson_from);
$start->setTimeZone($this->getGoogleCalendarTimeZone());
$event->setStart($start);
$end = new Google_Service_Calendar_EventDateTime();
$end->setDateTime($lesson_to);
$end->setTimeZone($this->getGoogleCalendarTimeZone());
$event->setEnd($end);
$event->setColorId(4);
$description = "...";
$event->setDescription($description);
if (isset($student->email) && $enable_attendees) {
$attendee1 = new Google_Service_Calendar_EventAttendee();
$attendee1->setResponseStatus('needsAction');
$attendee1->setEmail($student->email);
$attendees = array($attendee1);
$event->setAttendees($attendees);
}
$createdEvent = $this->calendar->events->insert($this->calendar_id, $event, array('fields' => 'id'));
return $return_request ? $createdEvent : $createdEvent->getId();
}
/** Push group of events to the Calendar */
function multipleInsert ($lessons, $instructor)
{
$this->use_batch = true;
$this->client->setUseBatch($this->use_batch);
$batch = new Google_Http_Batch($this->client);
$optParams = array('fields' => 'status,updates');
foreach($lessons as $time => $lesson) {
$lesson = array_shift($group['lessons']);
$req = $this->addEvent($lesson, $instructor, true);
$batch->add($req, $time);
}
}
$results = $batch->execute();
return $results;
}
}
in the newer versions, you should use
$batch = $service->createBatch();
instead of
$batch = new Google_Http_Batch($this->client);
reference

Categories