google api contacts php simplexml - php

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>";
}

Related

"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.

How to list Management Profiles with Google Analytics PHP API?

I am trying to retrieve the Google Analytics Management Profiles using the latest PHP client API (https://github.com/google/google-api-php-client).
I have the following code snippet:
// we've got the token, so set it
$google_client->setAccessToken($_SESSION['access_code']);
if ($google_client->getAccessToken()) {
$profiles = $google_analytics_service->management_profiles->listManagementProfiles("~all", "~all");
print "<h1>Profiles</h1><pre>" . print_r($profiles, true) . "</pre>";
}
/* $url = 'https://www.googleapis.com/analytics/v3/management/accounts/~all/webproperties/~all/profiles'; */
/* // json decode as array */
/* $analytics_auth = json_decode($_SESSION['access_code'], true); */
/* $ch = curl_init($url . '?access_token=' . $analytics_auth['access_token']); */
/* curl_exec($ch); */
/* curl_close($ch); */
The error message I get with the above is:
Error calling GET https://www.googleapis.com/analytics/v3/management/accounts/~all/webproperties/~all/profiles?key=AIza[SNIP]: (403) Access Not Configured
Note: However I decided to run the same with cURL and it returns a JSON array with the profiles (the commented code). Is this a bug, or me? What I do notice is that my access_token starts with "ya29".
I think you are missing a step:
<?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("{developerkey}");
$client->setClientId('{clientID}.apps.googleusercontent.com');
$client->setClientSecret('{Client secret}');
$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>"; // fix syntax
print "Access from google: " . $_SESSION['token'];
?>
Due to issue with the session_start and headers its a bit out of order. I added some comments to help you understand what its doing. Its a simple script but you can test it here Dummy Example for Hal9k
The 403 problem was because the correct IP address wasn't set for the server applications key. This can be set in the Google Developers' Console. It's odd, however, that using cURL bypassed this.
Public API access
Use of this key does not require any user action or consent, does not grant access to any account information, and is not used for authorization.
Key for server applications API key: AI[snip]
IPs: 91.[snip] 109.[snip] Make sure correct IP address is set here

Get post from Google+ without browser's authentication in google's account via PHP

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");

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 Analytics Data Export API V3

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>";
}

Categories