php zend gdata - Get list of google docs using oauth - php

I've got my session with the valid token that i set up this way :
$session_token = Zend_Gdata_AuthSub::getAuthSubSessionToken($_GET['token']);
// Store the session token in our session.
$_SESSION['cal_token'] = $session_token;
Then i want to be able to do this:
$service = Zend_Gdata_Docs::AUTH_SERVICE_NAME;
$client = Zend_Gdata_ClientLogin::getHttpClient($user, $pass, $service);
$docs = new Zend_Gdata_Docs($client);
$feed = $docs->getDocumentListFeed();
But using the token. Instead of the authentication with user/pass/service
I already looked at some example of this but i didn't find any way to make it work.
Thank you everyone!

// Retrieve user's list of Google Docs
$client = Zend_Gdata_AuthSub::getHttpClient($_SESSION['cal_token']);
$docs = new Zend_Gdata_Docs($client);
$feed = $docs->getDocumentListFeed();
foreach ($feed->entries as $entry) {
echo "$entry->title\n";
}

Related

Google admin SDK custom scheme issue

I need help on custom scheme on Google.
I successfully get the user list from delegation.
Below is my code.
$client = new \Google_Client();
$client->setApplicationName('xx');
$scopes = array('www.googleapis.com/auth/admin.directory.user','www.googleapis.com/auth/admin.directory.userschema');
$client->setAuthConfig('C:\Users\xx\xx\public\client_secret.json');
$client->setScopes($scopes);
$user_to_impersonate = 'xx.sg';
$client->setSubject($user_to_impersonate);
$dir = new \Google_Service_Directory($client);
$r = $dir->users->get('xxx#xx.com');
dd($r);
Userscheme have been added to Google also.
But the custom scheme I got is empty.
https://i.stack.imgur.com/0JcfZ.png
If I use projection = full in developers.google.com/admin it works.
https://i.stack.imgur.com/9s3MQ.png
Can someone help?
The documentation says:
You can fetch custom fields in a user profile by setting the projection parameter in a users.get or users.list request to custom or full.
so I would replace your line:
$r = $dir->users->get('xxx#xx.sg');
with:
$optParams = array('projection' => 'full');
$r = $dir->users->get('xxx#xx.sg', $optParams);

How to get ConversionValue from google adwords api v2001502

I've downloaded the PHP client library for Google Adwords API. I need to fetch 'ConversionsManyPerClick' data from the api, I can't find an option for the same from the client library. But the same time i am able to take this data as file by using this 'AD_PERFORMANCE_REPORT' method. Please help me.
function DownloadCriteriaReportExample(AdWordsUser $user, $filePath) {
// Load the service, so that the required classes are available.
$user->LoadService('ReportDefinitionService');
// Create selector.
$selector = new Selector();
$selector->fields = array('Headline','Description1','Description2','DisplayUrl','AdGroupName','CampaignName','Clicks','ConversionsManyPerClick');
$selector->predicates[] = new Predicate('Status', 'NOT_IN', array('PAUSED'));
$reportDefinition = new ReportDefinition();
$reportDefinition->selector = $selector;
$reportDefinition->reportName = 'ad performance report #' . uniqid();
$reportDefinition->dateRangeType = 'LAST_30_DAYS';
$reportDefinition->reportType = 'AD_PERFORMANCE_REPORT';
$reportDefinition->downloadFormat = 'CSV';
$reportDefinition->includeZeroImpressions = FALSE;
$options = array('version' => 'v201502');
ReportUtils::DownloadReport($reportDefinition, $filePath, $user, $options);
}
Thanks in advance.
Please read the following documentation and also try to modify the core plugin
https://developers.google.com/adwords/api/docs/guides/conversion-tracking

Need help updating a user with Google PHP API Library

I'm trying to use the newest Google PHP API Lib to update users and i can't find any examples on how to use it to update.
The closest example I can find is this Cannot update user information using Google PHP API Client library but it doesn't have enough info to add on to.
Below is what I have and it's copied off of another job that pulls from the users list. But that is scoped to 'https://www.googleapis.com/auth/admin.directory.user.readonly https://www.googleapis.com/auth/admin.directory.group.readonly https://www.googleapis.com/auth/admin.directory.orgunit.readonly'
and doesn't update anything.
I've searched and searched and cannot seem to find an example of PHP updating a user.
session_start();
require 'vendor/autoload.php';
$SCOPE = 'https://www.googleapis.com/auth/admin.directory.user';
$SERVICE_ACCOUNT_EMAIL = 'BLAHBLAH#developer.gserviceaccount.com';
$SERVICE_ACCOUNT_PKCS12_FILE_PATH = 'blahblah.p12';
$client = new Google_Client();
$client->setApplicationName('BLahBlah.apps.googleusercontent.com');
$adminService = new Google_Service_Directory($client);
$key = file_get_contents($SERVICE_ACCOUNT_PKCS12_FILE_PATH);
$cred = new Google_Auth_AssertionCredentials($SERVICE_ACCOUNT_EMAIL, array($SCOPE), $key);
$cred->sub = "chriswhittle#lahlah.com";
$client->setAssertionCredentials($cred);
$email = "fred#tom.com";
$requestUrl = "https://www.googleapis.com/admin/directory/v1/users/" . urlencode($email) ;
$requestMethod = 'PUT';
$data = array("title" => "Cool Guy");
$requestHeader = array('Content-Type' => 'application/json', 'Content-Length' => 'CONTENT_LENGTH');
$request = new Google_Http_Request($requestUrl, $requestMethod,$requestHeader,$data);
$httpRequest = $client->getAuth()->authenticatedRequest($request);
The code was fine, I had to go into our google apps domain security settings and grant user edit access. and adjust the body data to match the json... Here is an example.
$data = array("organizations" => array(array("name"=>"My Company","title"=>"Director, Information Technology","primary"=>true,"customType"=>"Other","department"=>"Information Technology")),"name"=>array("familyName"=> "Admin"));

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

how can I append querystring to object?

Google has chanced some things with their calendar API, and now I need to fix some strange symbols that are adding themselves to text. I found this thread which exactly describes the issue I'm dealing with:
http://www.google.com/support/forum/p/Calendar/thread?tid=25ac3d762b235a51&hl=en
The solution is to append "&hl=en" or "?hl=en" to the end of my 'basic' URL feed.
I'm confunsed how to do that though, because I am retrieving the feed as an object with Zend_Gdata:
<?php
// load library
require_once 'Zend/Loader.php';
Zend_Loader::loadClass('Zend_Gdata');
Zend_Loader::loadClass('Zend_Gdata_ClientLogin');
Zend_Loader::loadClass('Zend_Gdata_Calendar');
Zend_Loader::loadClass('Zend_Http_Client');
// create authenticated HTTP client for Calendar service
$gcal = Zend_Gdata_Calendar::AUTH_SERVICE_NAME;
$user = "xxxxx";
$pass = "xxxxx";
$client = Zend_Gdata_ClientLogin::getHttpClient($user, $pass, $gcal);
$gcal = new Zend_Gdata_Calendar($client);
$query = $gcal->newEventQuery();
$query->setUser('xxxxx#group.calendar.google.com');
$secondary=true;
$query->setVisibility('private');
$query->setProjection('basic');
$query->setOrderby('starttime');
$query->setSortOrder('ascending');
//$query->setFutureevents('true');
$startDate=date('Y-m-d h:i:s');
$endDate="2015-12-31";
$query->setStartMin($startDate);
$query->setStartMax($endDate);
$query->setMaxResults(30);
try {
$feed = $gcal->getCalendarEventFeed($query);
} catch (Zend_Gdata_App_Exception $e) {
echo "Error: " . $e->getResponse();
}
?>
I tried to do this with no luck:
$query->setProjection('basic?hl=en');
Note: I've not used any of this before so I apologize if this doesn't work :)
The documentation says that getCalendarEventFeed() can take a URL as the parameter.
So we can change this...
$feed = $gcal->getCalendarEventFeed($query);
... to this in order to add the parameter to the query string:
$eventUrl = $query->getQueryUrl() . '?hl=en';
$feed = $gcal->getCalendarEventFeed($eventUrl);
Obviously, this is a simplified example - you should still perform the following two checks:
Make sure $query is an instance of Zend_Gdata_Query before calling getQueryUrl() on it.
Ensure that there are no other query parameters already added to $eventUrl so that we can use &hl=en rather than ?hl=en. You could probably use Zend_Uri for this.

Categories