Google Analytics Data Export API V3 - php

I am trying to get to grips with interacting with the GA API v3 using php. Being quite new to php, I am struggling somewhat. Does anyone here have any experience with using the api with php (v3)?
http://code.google.com/intl/nl/apis/analytics/docs/index.html
Google does supply a small sample script but it's effectively useless (with my limited skills) as it returns an api key but doesn't tell you where it needs to go or why you need it.
If anyone has any knowledge I would be very grateful if you could show me how.

You need to make sure you register you API with Google from their API console. Make sure you turn on Google Analytics, and create a project.
After make sure you download the full api from Google Code.
You want to go into simple.php located in the Analytics folder (under examples) and uncomment lines 11-14, and replace with information from Google API Console:
$client->setClientId('xxxx.apps.googleusercontent.com');
$client->setClientSecret('xxxxxx');
$client->setRedirectUri('http://www.xxxx.com/xxx/examples/analytics/simple.php');
$client->setDeveloperKey('xxxxxxxxxxx');
This will let you connect and you will see the basic data. For more details and a great tutorial you can see it here.
Your total page should look like this:
<?php
require_once '../../src/apiClient.php';
require_once '../../src/contrib/apiAnalyticsService.php';
session_start();
$client = new apiClient();
$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('addyourshere');
$client->setClientSecret('addyourshere');
$client->setRedirectUri('addyourshere');
$client->setDeveloperKey('addyourshere');
$service = new apiAnalyticsService($client);
if (isset($_GET['logout'])) {
unset($_SESSION['token']);
}
if (isset($_GET['code'])) {
$client->authenticate();
$_SESSION['token'] = $client->getAccessToken();
header('Location: http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF']);
}
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>";
}

Related

PHP Google People API - Simple email request failing

Thank you everyone for your time.
I've spent all day on this although, wasn't able to find a good example and answer, so I thought it may be relevant for the community.
<?php
session_start();
require_once ('Google/src/Google/autoload.php');
$client = new Google_Client();
$client->setApplicationName("xxxxx");
$client->setClientId('xxxxx');
$client->setClientSecret('xxxxx')
$client->setRedirectUri('xxxxx');
$client->addScope('profile');
$client->addScope('email');
$client->addScope('https://www.googleapis.com/auth/contacts.readonly');
if (isset($_GET['oauth'])) {
// Start auth flow by redirecting to Google's auth server
$auth_url = $client->createAuthUrl();
header('Location: ' . filter_var($auth_url, FILTER_SANITIZE_URL));
} else if (isset($_GET['code'])) {
// Receive auth code from Google, exchange it for an access token, and redirect to your base URL
$client->authenticate($_GET['code']);
$_SESSION['access_token'] = $client->getAccessToken();
$redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . '/';
header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
} else if ($_SESSION['access_token']) {
// You have an access token; use it to call the People API
$client->setAccessToken($_SESSION['access_token']);
$service = new Google_Service_People($client);
$optParams = array('pageSize' => 10);
// TODO: Use service object to request People data
$results = $service->people_connections->listPeopleConnections('people/me', $optParams);
} else {
$redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . '/?oauth';
header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
}
Upon executing the script I simply get a blank white page, if I comment out $results = $service->people_connections->listPeopleConnections('people/me', $optParams) the script then works.
It looks like it loads the API properly and authenticates with Oauth and the token session variables are set; although when uncommented it is simply a white screen so I think the problem is retrieving data from the Google People API.
I'm trying to download a list of each users contacts (including name & email) to share a link with via email; after clicking a 'Login with Google' button.
Any assistance would be greatly appreciated, thank you for your time!

"Fatal error: Class 'Google_Http_Request' not found in" while using Oauth2.0 authentication and Google Contact API for PHP

I am trying to retrieve all my contacts using Google Contact API. For this I used Oauth2.0 authentication and Google Contact API for PHP.
But i am getting this error:
"Fatal error: Class 'Google_Http_Request' not found in"
could not get the reason why. I even used Google_HttpRequest but error remains the same but this time it is for "Google_HttpRequest".
Code used is as follows, can some one help because for this this there no help is available on internet
<?php
//require_once 'C:/xampp/htdocs/google-api-php-client-master/src/Google/Client.php';
require_once 'C:/xampp/htdocs/google-api-php-client-master/vendor/autoload.php';// or wherever autoload.php is located
session_start();
//Declare your Google Client ID, Google Client secret and Google redirect uri in php variables
$google_client_id = 'xxx-yyy.apps.googleusercontent.com';
$google_client_secret = 'xxxx';
$google_redirect_uri = 'https://localhost:4433/xxx.php';
$client = new Google_Client();
$client -> setApplicationName('My application name');
$client -> setClientid($google_client_id);
$client -> setClientSecret($google_client_secret);
$client -> setRedirectUri($google_redirect_uri);
$client -> setAccessType('online');
$client->setApplicationName('Google Contacts PHP Sample');
$client->setScopes("http://www.google.com/m8/feeds/");
///if (isset($_GET['code'])) {
/// $client->authenticate($_GET['code']);
/// $auth_code = $_GET["code"];
/// $_SESSION['google_code'] = $auth_code;
/// header('Location: ' . $google_redirect_uri);
///}
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 (isset($_SESSION['token'])) {
$client->setAccessToken($_SESSION['token']);
}
if (isset($_REQUEST['logout'])) {
unset($_SESSION['token']);
$client->revokeToken();
}
if ($client->getAccessToken()) {
//$req = new Google_Http_Request("https://www.google.com/m8/feeds/contacts/default/full", 'GET', null, null);
$req = new Google_Http_Request("https://www.google.com/m8/feeds/contacts/default/full");
$val = $client->getIo()->authenticatedRequest($req);
// The contacts api only returns XML responses.
$response = json_encode(simplexml_load_string($val->getResponseBody()));
print "<pre>" . print_r(json_decode($response, true), true) . "</pre>";
// The access token may have been updated lazily.
$_SESSION['token'] = $client->getAccessToken();
} else {
$auth = $client->createAuthUrl();
}
if (isset($auth)) {
print "<a class=login href='$auth'>Connect Me!</a>";
} else {
print "<a class=logout href='?logout'>Logout</a>";
}
You are trying to mix things that cant be mixed.
The current Google php client library which you are using only supports discovery service APIs. Which are the new APIs that return Json.
The google contacts API is an older Gdata api which returns XML. the two do not speak the same language. I haven't tried it but the old GData client library can be found here.

Google Calendar API/PHP

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

Google Calendar API --> How can I make the useraccount from which I retrieve Events, variable?

I'm currently working with the Google Calendar API.
I retrieve a list of EVENTS from the user's calendar, but at the moment the account of the user is given in my code.
I wan't to make this variable (It should retrieve EVENTS from the account you select).
This is my code:
<?php
require_once 'src/Google_Client.php';
require_once 'src/contrib/Google_CalendarService.php';
$client = new Google_Client();
$client->setApplicationName('Tryout for Google Calendar');
// Visit https://code.google.com/apis/console?api=plus to generate your
// client id, client secret, and to register your redirect uri.
$client->setClientId('myid');
$client->setClientSecret('mysecret');
$client->setRedirectUri('http://localhost/gcal/done.php');
$client->setDeveloperKey('mykey');
$cal = new Google_CalendarService($client);
if (isset($_GET['logout'])) {
unset($_SESSION['token']);
}
if (isset($_GET['code'])) {
$client->authenticate($_GET['code']);
$_SESSION['token'] = $client->getAccessToken();
header('Location: http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF']);
}
if (isset($_SESSION['token'])) {
$client->setAccessToken($_SESSION['token']);
}
if ($client->getAccessToken()) {
$minCheck = date(DATE_ATOM);
$eventList = $cal->events->listEvents("phpkay#gmail.com", array('singleEvents' => 'true', 'timeMin' => $minCheck));
print "<h1>Calendar List</h1><pre>" . print_r($eventList, true) . "</pre>";
$_SESSION['token'] = $client->getAccessToken();
} else {
$authUrl = $client->createAuthUrl();
print "<a class='login' href='$authUrl'>Connect Me!</a>";
}
?>
This is the part where I set the useraccount, namely: "phpkay#gmail.com"
$eventList = $cal->events->listEvents("phpkay#gmail.com", array('singleEvents' => 'true', 'timeMin' => $minCheck));
How can I retrieve the selected useraccount (the user gets a screen where he can select one of the Google accounts he owns to use for this APP) and use this instead of the set "phpkay#gmail.com"-account?
Sorry if my question is unclear, I have no clue how to phrase this in another way.
You can do this with the OAuth 2.0 API. Just include:
https://developers.google.com/admin-sdk/directory/v1/reference/users
in your list of OAuth scopes and then make an authenticated GET request to:
https://www.googleapis.com/oauth2/v2/userinfo
this will return the email address of the authenticated user. You can try this out in the Google API Explorer

How can I reach google analytics datas?

My goal is to show google analytics datas on the header of my site. Thats all I have until now (its from googleApiPhPClient/examples/analytics:
require_once 'library/GoogleApiPhpClient/apiClient.php';
$client = new apiClient();
$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('aaa');
$client->setClientSecret('bbb_gK');
$client->setRedirectUri('ccc');
$client->setDeveloperKey('dd');
require_once ('contrib/apiAnalyticsService.php');
$service = new apiAnalyticsService($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>";
}
but this only drops a "connect me" link. Am in the somewhat right way on getting analytic datas anyway?
I've been using this code.google.com/p/gapi-google-analytics-php-interface which only requires the google account user name and password and works pretty well
a sample code of mine where im checking visits $ga->requestReportData($ga_profile_id,array('browser','browserVersion','country'‌​),array('pageviews','visits'),null,"country==USA",$yesterday,$todate);
when you log in to your account, select the profile you already made for your web site . when you will click it, the url would be like google.com/analytics/web/#report/visitors-overview/… so the ga_profile_id would be the one written after "p" in the URL.. i see this way only to get this profile id

Categories