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
Related
I am working with google drive API with PHP. Basically i create a auth credentials and stuck at a point where i want to list of google drive files. Here is my code which i try.
<?php
require_once realpath(dirname(__FILE__) . '/gac/src/Google/autoload.php');
$client = new Google_Client();
session_start();
$client->setClientId('xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx');
$client->setClientSecret('xxxxxxxxxxxxxxxxxxxxxxxxxxxx');
$client->setRedirectUri('http://www.my-website-name.com/drive_test');
$client->setScopes(array('https://www.googleapis.com/auth/drive.file'));
if (isset($_GET['code']) || (isset($_SESSION['access_token']) && $_SESSION['access_token'])) {
if (isset($_GET['code'])) {
$client->authenticate($_GET['code']);
$_SESSION['access_token'] = $client->getAccessToken();
} else
$client->setAccessToken($_SESSION['access_token']);
$service = new Google_Service_Drive($client);
echo "<pre>";
$all_files = "";
$all_files = retrieveAllFiles($service);
print_r($all_files);
die;
} else {
$authUrl = $client->createAuthUrl();
header('Location: ' . $authUrl);
exit();
}
/**
* Retrieve a list of File resources.
*
* #param Google_Service_Drive $service Drive API service instance.
* #return Array List of Google_Service_Drive_DriveFile resources.
*/
function retrieveAllFiles($service) {
$result = array();
$pageToken = NULL;
do {
try {
$parameters = array();
if ($pageToken) {
$parameters['pageToken'] = $pageToken;
}
$files = $service->files->listFiles($parameters);
$result = array_merge($result, $files->getItems());
$pageToken = $files->getNextPageToken();
} catch (Exception $e) {
print "An error occurred: " . $e->getMessage();
$pageToken = NULL;
}
} while ($pageToken);
return $result;
}
?>
I am getting output like this.
Array
(
)
Please help me to solve this issue. Thank you.
Oh yes, finally i found the issue and fix it. It's a permission issue. I just replace this code
$client->setScopes(array('https://www.googleapis.com/auth/drive.file'));
With new code
$client->setScopes(array('https://www.googleapis.com/auth/drive'));
and everythig
I'm new to Google API and am having trouble getting the Analytics API to work. So far I've set up the Developer Console, created a project, and generated the relevant credentials. My registered email ID is myname#mycompany.com, and the redirect URI is set to http://www.mycompany.com/oauth2callback by default. The JavaScript Origins is set to http://www.mycompany.com.
When I run the project from localhost, I'm able to initiate the OAuth procedure. But when I hit the "allow" button, I'm sent to http://www.mycompany.comand nothing happens. What could I be doing wrong? Do I need to be running this script from the mycompany.com doamin for it to work? Lastly, how can I run it from localhost?
<?php
include_once "google_api/autoload.php";
session_start();
$client = new Google_Client();
$client->setApplicationName("Hello Analytics API Example");
$client->setClientId('XXXXXXXXXXXXXXXXX');
$client->setClientSecret('XXXXXXXXXXXXXXXXXXXX');
//$client->setRedirectUri('XXXXXXXXXXXXXXXXXXX');
$client->setRedirectUri('XXXXXXXXXXXXXXXXXX');
$client->setDeveloperKey('XXXXXXXXXXXXXXXXXXXX');
$client->setScopes(array('https://www.googleapis.com/auth/analytics.readonly'));
// Magic. Returns objects from the Analytics Service instead of associative arrays.
//print_r($client);
//$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
{
// Create analytics service object. See next step below.
$analytics = new apiAnalyticsService($client);
runMainDemo($analytics);
}
function runMainDemo(&$analytics) {
try {
// Step 2. Get the user's first view (profile) ID.
$profileId = getFirstProfileId($analytics);
if (isset($profileId)) {
// Step 3. Query the Core Reporting API.
$results = getResults($analytics, $profileId);
// Step 4. Output the results.
printResults($results);
}
} catch (apiServiceException $e) {
// Error from the API.
print 'There was an API error : ' . $e->getCode() . ' : ' . $e->getMessage();
} catch (Exception $e) {
print 'There wan a general error : ' . $e->getMessage();
}
}
function getFirstprofileId(&$analytics) {
$accounts = $analytics->management_accounts->listManagementAccounts();
if (count($accounts->getItems()) > 0) {
$items = $accounts->getItems();
$firstAccountId = $items[0]->getId();
$webproperties = $analytics->management_webproperties
->listManagementWebproperties($firstAccountId);
if (count($webproperties->getItems()) > 0) {
$items = $webproperties->getItems();
$firstWebpropertyId = $items[0]->getId();
$profiles = $analytics->management_profiles
->listManagementProfiles($firstAccountId, $firstWebpropertyId);
if (count($profiles->getItems()) > 0) {
$items = $profiles->getItems();
return $items[0]->getId();
} else {
throw new Exception('No views (profiles) found for this user.');
}
} else {
throw new Exception('No webproperties found for this user.');
}
} else {
throw new Exception('No accounts found for this user.');
}
}
function getResults(&$analytics, $profileId) {
return $analytics->data_ga->get(
'ga:' . $profileId,
'2012-03-03',
'2012-03-03',
'ga:sessions');
}
function printResults(&$results) {
if (count($results->getRows()) > 0) {
$profileName = $results->getProfileInfo()->getProfileName();
$rows = $results->getRows();
$sessions = $rows[0][0];
print "<p>First view (profile) found: $profileName</p>";
print "<p>Total sessions: $sessions</p>";
} else {
print '<p>No results found.</p>';
}
}
If you want to be able to request there data automated you will need to store the refreshtoken. If you only want them to be able to access there data when they are on your site then this should get you started.
The latest Google PHP client lib can be found here. Github
<?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("{devkey}");
$client->setClientId('{clientid}.apps.googleusercontent.com');
$client->setClientSecret('{clientsecret}');
$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>";
print "Access from google: " . $_SESSION['token'];
?>
Code ripped from the tutorial Google Analytics Oauth2 with php.
Update: After looking at your code I think part of your problem may be that you aren't linking the redirectURi to a page. It cant just be a directory you must give it the php page that it should redirect to.
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");
I have been Googling this for going on hours now. I have followed the Hello Analytics tutorial.
The application runs fine until the user has granted permission from the Google 'consent screen' at which point i receive the following error:
There wan a general error : Error calling GET My url
(403) Access Not Configured. Please use Google Developers Console to
activate the API for your project.
I have checked in the developer console and Analytics API is enabled and, after reading other posts on this, have added Google+ and Drive access.
NOTE: I am running this application locally and redirecting the redirecting back to 127.0.0.1.
I have added my code below for reference although I think the issue is to do with my google console account and / or running this application locally.
Appreciate any help with this guys. Please let me know if any further information is required.
==================================================================================
// --------------------- Google libraries
require_once 'google-api-php-client/src/Google_Client.php';
require_once 'google-api-php-client/src/contrib/Google_AnalyticsService.php';
session_start();
// --------------------- Application credentials
$client = new Google_Client();
$client->setApplicationName('Interim Testing Tool');
$client->setClientId('xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.apps.googleusercontent.com');
$client->setClientSecret('xxxxxxxxxxxxxxxxxxxxxxxx');
$client->setRedirectUri('http://127.0.0.1');
$client->setDeveloperKey('xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx');
$client->setScopes(array('https://www.googleapis.com/auth/analytics.readonly'));
// Returns objects from the Analytics Service instead of associative arrays.
$client->setUseObjects(true);
// --------------------- Client access checks
// Handle authorization flow from the server
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));
}
// Retrieve and use stored credentials if set
if (isset($_SESSION['token'])) {
$client->setAccessToken($_SESSION['token']);
}
if (!$client->getAccessToken()) {
// CLient not logged in create a connect button
$authUrl = $client->createAuthUrl();
print "<a class='login' href='$authUrl'>Connect Me!</a>";
} else {
$analytics = new Google_AnalyticsService($client);
runMainDemo($analytics);
}
//-------------------------------------------------------------- Run main demo
function runMainDemo($analytics) {
try {
// Get the user's first view (profile) ID.
$profileId = getFirstProfileId($analytics);
if (isset($profileId)) {
// Query the Core Reporting API.
$results = getResults($analytics, $profileId);
// Output the results.
printResults($results);
}
} catch (apiServiceException $e) {
// Error from the API.
print 'There was an API error : ' . $e->getCode() . ' : ' . $e->getMessage();
} catch (Exception $e) {
print 'There wan a general error : ' . $e->getMessage();
}
}
// ------------------------------------------------------------------ Get first profile id
function getFirstprofileId($analytics) {
$accounts = $analytics->management_accounts->listManagementAccounts();
if (count($accounts->getItems()) > 0) {
$items = $accounts->getItems();
$firstAccountId = $items[0]->getId();
$webproperties = $analytics->management_webproperties->listManagementWebproperties($firstAccountId);
if (count($webproperties->getItems()) > 0) {
$items = $webproperties->getItems();
$firstWebpropertyId = $items[0]->getId();
$profiles = $analytics->management_profiles->listManagementProfiles($firstAccountId, $firstWebpropertyId);
if (count($profiles->getItems()) > 0) {
$items = $profiles->getItems();
return $items[0]->getId();
} else {
throw new Exception('No views (profiles) found for this user.');
}
} else {
throw new Exception('No webproperties found for this user.');
}
} else {
throw new Exception('No accounts found for this user.');
}
}
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>";
}