Google Analytics Daily Upload Script not working - php

I have been working my way through the Hello Analytics Tutorial here - https://developers.google.com/analytics/solutions/articles/hello-analytics-api
and I have been using Ewan Hemings Example here - http://www.ewanheming.com/upload-cost-data-google-analytics to try and upload my external cost data into Google analytics's.
I have been testing the POST data using the API Explorer - https://developers.google.com/apis-explorer/#s/analytics/v3/analytics.management.dailyUploads.upload and the post master app. Although it is not returning any errors the data is not appearing in my Analytics.
I can print the data to the screen and its seems to be formatted correctly so I am a bit stumped. Any help would be apprenticed, even if you could offer a suggestion for debugging.
<?php
// The filename of the performance report
$reportFile = "Bing.csv";
// Hard code the source and medium
$source = "acme ads";
$medium = "cpc";
// Upload file headers
$headers = array(
"ga:source",
"ga:medium",
"ga:campaign",
"ga:adGroup",
"ga:adContent",
"ga:keyword",
"ga:impressions",
"ga:adClicks",
"ga:adCost"
);
$headerRow = implode(",", $headers);
// Create an array to store the data to upload
$uploadFiles = array();
// Open the performance report
$fp = fopen($reportFile, "r");
// Process each row in the file
while ($row = fgetcsv($fp)) {
// Attempt to create a date from the first column of the row
$date = isset($row[0]) ?
date_create_from_format('M d, Y', $row[0]) : null;
// If the date creation was successful, this is a data row
if ($date instanceof DateTime) {
// Extract the columns from the row
$campaign = $row[1];
$adgroup = $row[2];
$headline = $row[3];
$keyword = $row[4];
$impressions = $row[5];
$clicks = $row[6];
$cost = $row[7];
// Don't upload rows with no impressions
if ($impressions > 0) {
// Format the date
$uploadDate = date_format($date, 'Y-m-d');
// If there isn't a file for the upload date, then create one
if (!isset($uploadFiles[$uploadDate])) {
// Add the headers to the file
$uploadFiles[$uploadDate] = "$headerRow\n";
}
// Add the row to the file
$uploadRow = array(
"\"$source\"",
"\"$medium\"",
"\"$campaign\"",
"\"$adgroup\"",
"\"$headline\"",
"\"$keyword\"",
$impressions,
$clicks,
$cost
);
$uploadFiles[$uploadDate] .= implode(",", $uploadRow) . "\n";
}
}
}
fclose($fp);
require_once 'src/Google_Client.php';
require_once 'src/contrib/Google_AnalyticsService.php';
session_start();
$client = new Google_Client();
$client->setApplicationName('Hello Analytics API Sample');
// Visit //code.google.com/apis/console?api=analytics to generate your
// client id, client secret, and to register your redirect uri.
$client->setClientId('69673577u537j57n57j7jjm0.apps.googleusercontent.com');
$client->setClientSecret('67qg6646744724724gK');
$client->setRedirectUri('http://www.mywebsite.co.uk/analytics/GAUpload.php');
$client->setDeveloperKey('AIz42172147246h46h630JuY');
$client->setScopes(array('https://www.googleapis.com/auth/analytics.readonly'));
// Magic. Returns objects from the Analytics Service instead of associative arrays.
$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 {
$analytics = new Google_AnalyticsService($client);
foreach (array_keys($uploadFiles) as $uploadDate) {
$analytics->management_dailyUploads->upload('46856856853', 'UA-4276753-1', 'o867567568560XJY4qg', '2013-09-02', 1, 'cost', array("reset" => true, "data" => $uploadFiles[$uploadDate], 'mimeType' => 'application/octet-stream', 'uploadType' => 'media'));
}
}
?>

Related

"Login with Google" in PHP - Google+ API shutdown migration - how to migrate away from plus.people.get?

I got a warning email from Google reminding me of Google+'s EOL which is supposed to break my current "Login with Google", but I am unsure what exactly should I change.
Let me show you my (simplified) login code:
google-login.php
new class {
public function __construct() {
$state = mt_rand();
$client = new Google_Client();
$client->setApplicationName(Config::Google['app_name']);
$client->setClientId(Config::Google['id']);
$client->setClientSecret(Config::Google['secret']);
$client->setRedirectUri(sprintf('https://%s/members/google-callback.php', $_SERVER['HTTP_HOST']));
$client->setScopes(['profile', 'email']);
$client->setState($state);
$_SESSION['state'] = $state;
$url = $client->createAuthUrl(); // $url = https://accounts.google.com/o/oauth2/auth?response_type=code&access_type=online&client_id=CLIENT_ID.apps.googleusercontent.com&redirect_uri=https%3A%2F%2Fread2me.online%2Fmembers%2Fgoogle-callback.php&state=1588245f23f2a&scope=profile%20email&approval_prompt=auto
header ("location: $url");
}
};
google-callback.php
new class {
private $newUser = false;
public function __construct() {
if (!isset($_GET['state']) || $_GET['state'] != $_SESSION['state'])
die('State mismatch.');
$client = new Google_Client();
$client->setApplicationName(Config::Google['app_name']);
$client->setClientId(Config::Google['id']);
$client->setClientSecret(Config::Google['secret']);
$client->setRedirectUri(sprintf('https://%s/members/google-callback.php', $_SERVER['HTTP_HOST']));
$client->setScopes(['profile', 'email']);
$plus = new Google_Service_Plus($client);
if (isset($_GET['code'])) {
$client->fetchAccessTokenWithAuthCode($_GET['code']);
$_SESSION['token'] = $client->getAccessToken();
}
if (isset($_SESSION['token'])) {
$client->setAccessToken($_SESSION['token']);
}
if (!$client->getAccessToken() || $client->isAccessTokenExpired()) {
$state = mt_rand();
$client->setState($state);
$_SESSION['state'] = $state;
$url = $client->createAuthUrl();
header ("location: $url");
}
try {
$me = $plus->people->get('me');
} catch (Google_Exception $e) {
\Rollbar::report_message($e->getMessage());
print_r($e->getMessage());
return;
}
$accessToken = $client->getAccessToken()['access_token'];
$email = $me->getEmails()[0]->getValue();
$name = $me->getDisplayName();
$avatar = $me->getImage()->getUrl();
$id = $me->getId();
if ($this->isEmailInSystem($email) === false) {
$this->newUser = true;
$this->addUser($email, $name, 'google', $accessToken, $id, $avatar);
}
header ("location: " . '/');
}
};
Now, I'm going through at what seems to be the up-to-date Sign In guide for PHP, but I am not sure what to change - any ideas?
Thanks
The best migration is to move from the Plus API to the People API, which provides access to the user's profile in a similar (tho not quite identical) way.
You would replace the creation of the $plus object with a new Goolge_Service_PeopleService object. Something like
$people = new Google_Service_PeopleService( $client );
Getting the profile is more involved since you need to specify which fields from the profile you want to get. But you might do it something like
$profile = $people->people->get(
'people/me',
array('personFields' => 'names,emailAddresses,photos')
);
The first parameter needs to be "people/me" to specify that you're requesting the authorized user's profile.
The second is an array of query parameters. You need to specify the "personFields" that you want from the list of what is available (scroll down on this page till you see the description of the available fields) and specify this as a comma separated list in a string. In my example above, I illustrate getting the name, email addresses, and photos. But consult the list and experiment.
The exact fields you get from the result in $profile will be different than those you got from $plus, but they should match the fields you requested. Check the values and exactly how they're structured.
I ran into the same issue as Google+ APIs shutting down on March 7, 2019.
Make sure Google People API is enable in your google console
I used google-api-php-client Library.
Once you have an access token here is code to get the person object using people API
$accessToken = 'REPLACE_WITH_ACCESS_TOKEN';
$clientId = 'REPLACE_WITH_CLIENT_ID';
$clientSecret = 'REPLACE_WITH_CLIENT_SECRET';
$developerKey = 'REPLACE_WITH_DEVELOPER_KEY';
$client = new Google_Client();
$client->setApplicationName("Application Name");
$client->setClientId($clientId . '.apps.googleusercontent.com');
$client->setClientSecret($clientSecret);
$client->setDeveloperKey($developerKey);
$client->setScopes(['https://www.googleapis.com/auth/userinfo.email','https://www.googleapis.com/auth/userinfo.profile']);
$client->setAccessToken($accessToken);
$guzzleClient = new \GuzzleHttp\Client(array( 'curl' => array( CURLOPT_SSL_VERIFYPEER => false, ), ));
$client->setHttpClient($guzzleClient);
$people = new Google_Service_PeopleService( $client );
if ($client->getAccessToken()) {
try {
$me = $people->people->get(
'people/me',
array('personFields' => 'emailAddresses,names,photos')
);
$id = preg_replace('/[^0-9]/', '', $me->getResourceName());
$email = $me->getEmailAddresses()[0]->value;
$name = $me->getNames()[0]->displayName;
$avtar = $me->getPhotos()[0]->getUrl();
} catch (Google_Exception $e) {
// error
echo $e->getMessage();
}
}
I also disabled Google+ API to make sure the application is not using it anymore anywhere.
With latest version of Google API PHP Client you can fetch profile details from Google_Client object itself.
$token = $client->fetchAccessTokenWithAuthCode($_GET['code']);
$attributes = $client->verifyIdToken($token['id_token'], GOOGLE_CLIENT_ID);
print_r($attributes);
Refer this article.
Obviously, the lines
$plus = new Google_Service_Plus($client);
and
$me = $plus->people->get('me');
You need to use google email API, see https://developers.google.com/gmail/api/quickstart/php , so the first line will be
$service = new Google_Service_Gmail($client);
and second ... hmmm ... not sure there WILL be any avatar after removing of google plus ...

Google API Oauth 2.0 cron job?

I have created a php script that uses the Google Analytics API, I want to run it with a cron job once an hour. It works fine in my browser, but I need to sign in from time to time with my gmail account and grant access.
How can I save my gmail login data in the php script, so it signs in automatically? This script will only use my login data, so it can be hard coded.
<?php
require_once 'Google/autoload.php';
session_start();
// ******************************************************** //
// Get these values from https://console.developers.google.com
// Be sure to enable the Analytics API
// ******************************************************** //
$client_id = 'xxxxxxxx';
$client_secret = 'xxxxxxxx';
$redirect_uri = 'http://example.com/xxxx';
$client = new Google_Client();
$client->setApplicationName("Client_Library_Examples");
$client->setClientId($client_id);
$client->setClientSecret($client_secret);
$client->setRedirectUri($redirect_uri);
$client->setScopes(array('https://www.googleapis.com/auth/analytics.readonly'));
$client->setAccessType('offline'); // Gets us our refreshtoken
//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>";
print "Access from google: " . $_SESSION['token']."<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 "<b>Account:</b> ",$item['name'], " " , $item['id'], "<br /> \n";
foreach($item->getWebProperties() as $wp) {
echo '-----<b>WebProperty:</b> ' ,$wp['name'], " " , $wp['id'], "<br /> \n";
$views = $wp->getProfiles();
if (!is_null($views)) {
// note sometimes a web property does not have a profile / view
foreach($wp->getProfiles() as $view) {
echo '----------<b>View:</b> ' ,$view['name'], " " , $view['id'], "<br /> \n";
} // closes profile
}
} // Closes web property
} // closes account summaries
}
//Adding Dimensions
$params = array('dimensions' => 'ga:pagePath', 'metrics' => 'ga:timeOnPage,ga:uniquePageviews');
// requesting the data
$data = $service->data_ga->get("ga:xxxxxxxx", date("Y-m-d"), date("Y-m-d"), "ga:users,ga:sessions", $params );
?><html>
<?php echo date("Y-m-d") . " - ".date("Y-m-d"). "\n";?>
<table>
<tr>
<?php
//Printing column headers
foreach($data->getColumnHeaders() as $header){
print "<td>".$header['name']."</td>";
}
?>
</tr>
<?php
//printing each row.
foreach ($data->getRows() as $row) {
if($row[1]<7.0 && $row[2]>100 ){
$length = strlen($row[0]);
if($length<12){
$row[0] = substr($row[0], 3);
print $row[0];
$short_url=$row[0];
$blocked=1;
//PDO
// configuration
$dbhost = "localhost";
$dbname = "xxxxxxxxx";
$dbuser = "xxxxxxxxx";
$dbpass = "xxxxx";
// database connection
$conn = new PDO("mysql:host=$dbhost;dbname=$dbname",$dbuser,$dbpass);
// query
$sql = "UPDATE urls SET blocked = :blocked WHERE short_url = :short_url";
$q = $conn->prepare($sql);
$q->execute(array(':short_url'=>$short_url,
':blocked'=>$blocked ));
}
print "<tr><td>".$row[0]."</td><td>".$row[1]."</td><td>".$row[2]."</td><td>".$row[3]."</td></tr>";
}
}
//printing the total number of rows
?>
<tr><td colspan="2">Rows Returned <?php print $data->getTotalResults();?> </td></tr>
</table>
</html>
?>
Use a service account instead.
A service account doesn’t need to prompt a user for access because you have to set it up. Go to the Google Analytics website in the Admin section for the Account you want to retrieve data from. This is very important it must be at the account level add this email address as a new user. just give them read access.
<?php
require_once 'Google/autoload.php';
session_start();
/************************************************
The following 3 values an befound in the setting
for the application you created on Google
Developers console. Developers console.
The Key file should be placed in a location
that is not accessable from the web. outside of
web root. web root.
In order to access your GA account you must
Add the Email address as a user at the
ACCOUNT Level in the GA admin.
************************************************/
$client_id = '[Your client id]';
$Email_address = '[YOur Service account email address Address]';
$key_file_location = '[Locatkon of key file]';
$client = new Google_Client();
$client->setApplicationName("Client_Library_Examples");
$key = file_get_contents($key_file_location);
// seproate additional scopes with a comma
$scopes ="https://www.googleapis.com/auth/analytics.readonly";
$cred = new Google_Auth_AssertionCredentials($Email_address,
array($scopes),
$key);
$client->setAssertionCredentials($cred);
if($client->getAuth()->isAccessTokenExpired()) {
$client->getAuth()->refreshTokenWithAssertion($cred);
}
$service = new Google_Service_Analytics($client);
//Adding Dimensions
$params = array('dimensions' => 'ga:userType');
// requesting the data
$data = $service->data_ga->get("ga:89798036", "2014-12-14", "2014-12-14", "ga:users,ga:sessions", $params );
?>
<html>
Results for date: 2014-12-14<br>
<table border="1">
<tr>
<?php
//Printing column headers
foreach($data->getColumnHeaders() as $header){
print "<td><b>".$header['name']."</b></td>";
}
?>
</tr>
<?php
//printing each row.
foreach ($data->getRows() as $row) {
print "<tr><td>".$row[0]."</td><td>".$row[1]."</td><td>".$row[2]."</td></tr>";
}
?>
<tr><td colspan="2">Rows Returned <?php print $data->getTotalResults();?> </td></tr>
</table>
</html>
code ripped from Google Service account Php

Getting duplicate files while trying to upload CSV files to google spreadsheet

I have applied file insertion code i.e to upload csv files to the google drive. All is working perfectly but I am getting duplicate files instead of getting one at a time. I have to upload two different files at a time but I am getting 4 files, need help in this case
This is google.php file where I have included "Google_Client.php","Google_DriveService.php" and file "insert.php" for the insertion in google drive which contain function insertFile($service, $title, $description, $parentId, $mimeType, $filename)
<?php
require_once 'google-api-php-client/src/Google_Client.php';
require_once 'google-api-php-client/src/contrib/Google_DriveService.php';
require 'insert.php';
session_start();
$title = 'Total Likes/Reblogs';
$description = 'Total Likes/Reblogs';
$title1 = 'Total Likes/Reblogs per post';
$description1 = 'Total Likes/Reblogs per post';
$parentId = '';
$mimeType = 'text/csv';
$filename = 'total.csv';
$fileNamePerPost = 'totalPerPost.csv';
$client = new Google_Client();
$client->setApplicationName("Google+ PHP Starter Application");
$service = new Google_DriveService($client);
if (isset($_REQUEST['logout'])) {
unset($_SESSION['access_token']);
}
if (isset($_GET['code'])) {
$client->authenticate($_GET['code']);
$_SESSION['access_token'] = $client->getAccessToken();
header('Location: http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF']);
}
if (isset($_SESSION['access_token'])) {
$client->setAccessToken($_SESSION['access_token']);
}
if ($client->getAccessToken()) {
insertFile($service, $title, $description, $parentId, $mimeType, $filename);
insertFile($service, $title1, $description1, $parentId, $mimeType, $fileNamePerPost);
} else {
$state = mt_rand();
$client->setState($state);
echo $_SESSION['state'] = $state;
$authUrl = $client->createAuthUrl();
print "<a class='login' href='$authUrl'>Connect Me!</a>";
}
?>
Once OAuth 2.0 callback is handled, you need to stop executing. header(...) doesn't stop the script and inserts 2 files. Once the first execution is finished, redirection inserts the same files again.

google+ oAuth contacts full list in PHP

i am using googles latest api to retrieve the contact list. This code seems to output in XML the first 20 items of my list.
Question: how can i output the entire list?
<?php
require_once '../../src/apiClient.php';
session_start();
$client = new apiClient();
$client->setApplicationName('Google Contacts PHP Sample');
$client->setScopes("http://www.google.com/m8/feeds/");
// Documentation: http://code.google.com/apis/gdata/docs/2.0/basics.html
// Visit https://code.google.com/apis/console?api=contacts to generate your
// oauth2_client_id, oauth2_client_secret, and register your oauth2_redirect_uri.
// $client->setClientId('insert_your_oauth2_client_id');
// $client->setClientSecret('insert_your_oauth2_client_secret');
// $client->setRedirectUri('insert_your_redirect_uri');
// $client->setDeveloperKey('insert_your_developer_key');
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 (isset($_REQUEST['logout'])) {
unset($_SESSION['token']);
$client->revokeToken();
}
if ($client->getAccessToken()) {
$req = new apiHttpRequest("https://www.google.com/m8/feeds/contacts/default/full");
$val = $client->getIo()->authenticatedRequest($req);
// The contacts api only returns XML responses.
/* * * * * * * * * produced an error
$response = json_encode(simplexml_load_string($val->getResponseBody()));
print "<pre>" . print_r(json_decode($response, true), true) . "</pre>";
*/
// fix
$response = $val->getResponseBody();
print "<pre>" . print_r($response) . "</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>";
}
?>
i saw this response , but have no idea how to implement it
Firstly you need to ask for version 3 as the extendedProperties are
not returned. Here's a c-n-p from some working code.
function get($xmlfile) {
try {
#$feed = simplexml_load_file($xmlfile. '&v=3.0');
if ($feed === FALSE) {
throw new Exception(file_get_contents($xmlfile));
}
} catch (Exception $e) {
return array('error' => true, 'payload' => $e->getMessage());
}
return array('error' => false, 'payload' => $xmlData);
}
Next thing to look for is something to tell simplexml that you want to
use the gd namespace. Another example:
$this->nsGd = $xmlData->children('http://schemas.google.com/g/2005');
...
$this->email = #(string)$this->nsGd->email->attributes()->address;
...
foreach ($this->nsGd->extendedProperty as $x) {
if ($x->attributes()->name == 'ethnicity') {
$this->ethnicity = $x->attributes()->value;
}
}
Have you tried using the max-results query parameter? From the Contacts API documentation.
Note: The feed may not contain all of the user's contacts, because there's a default limit on the number of results returned. For more
information, see the max-results query parameter in Retrieving
contacts using query parameters.
So, you could send a request such as: https://www.google.com/m8/feeds/contacts/default/full?max-results=1000

google api contacts php simplexml

I am looking to fetch the contact's first name from google contacts without any luck. However, I am able to extract the email address no problem. Can someone show me what i am doing wrong?
$xmlresponse=file_get_contents('https://www.google.com/m8/feeds/contacts/default/full?oauth_token='.$accesstoken);
//reading xml using SimpleXML
$xml= new SimpleXMLElement($xmlresponse);
$xml->registerXPathNamespace('gd', 'http://schemas.google.com/g/2005');
$nameFirst = $xml->xpath('//gd:givenName'); // I have also tried //gd:name
$result = $xml->xpath('//gd:email');
foreach($nameFirst as $nameF){
echo $nameF->getName();
}
foreach ($result as $title) {
echo $title->attributes()->address . "<br>";
}
?>
The XML I got from the Google Contacts API was mixed, the name was the node value of a normal XML node "title" but the email was a parameter in a gdata tag gd:email. Given the possibility of multiple email addresses I used the following to extract an array of single name/email pairs:
$req = new Google_HttpRequest("https://www.google.com/m8/feeds/contacts/default/property-email/");
$val = $this->client->getIo()->authenticatedRequest($req);
$xml = simplexml_load_string($val->getResponseBody());
$xml->registerXPathNamespace('gd', 'http://schemas.google.com/g/2005');
$output_array = array();
foreach ($xml->entry as $entry) {
foreach ($entry->xpath('gd:email') as $email) {
$output_array[] = array((string)$entry->title, (string)$email->attributes()->address);
}
}
The example above (from google client api examples) does not work for emails. I tried a lot and for me the response contains other information but not emails.
I found a google group's discussion where they talk about that, seems to be a bug where simplexml doesn't see some gd: information.
I used simpleXMLElements and xpath as Claude did, but also for me I can get only emails.
There's a PHP client-side library that Google supplies for interacting with the various services it offers. Contacts is one of them.
The example code for contacts service uses the trick of json encoding and decoding the result:
require_once '../../src/apiClient.php';
session_start();
$client = new apiClient();
$client->setApplicationName('Google Contacts PHP Sample');
$client->setScopes("http://www.google.com/m8/feeds/");
// Documentation: http://code.google.com/apis/gdata/docs/2.0/basics.html
// Visit https://code.google.com/apis/console?api=contacts to generate your
// oauth2_client_id, oauth2_client_secret, and register your oauth2_redirect_uri.
// $client->setClientId('insert_your_oauth2_client_id');
// $client->setClientSecret('insert_your_oauth2_client_secret');
// $client->setRedirectUri('insert_your_redirect_uri');
// $client->setDeveloperKey('insert_your_developer_key');
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 (isset($_REQUEST['logout'])) {
unset($_SESSION['token']);
$client->revokeToken();
}
if ($client->getAccessToken()) {
$req = new apiHttpRequest("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>";
}

Categories