How to access user data with Google Webmaster Tools API - php

I'm just starting to use the api libraries from google and I'm having some trouble accessing to user data. For experimentation I used code from a previos question in this field.
My code executes a petition for the google search console api but it returns an empty array. I autorized the service account from the admin console (https://developers.google.com/identity/protocols/OAuth2ServiceAccount) so I don't know why doesn't it return anything.
set_include_path(get_include_path() . PATH_SEPARATOR . '$path/google-api-php-client-master/src');
require_once realpath('$path/google-api-php-client-master/src/Google/autoload.php');
$client_id = "my-client-id";
$service_account_name = "my-service-account-name#developer.gserviceaccount.com";
$key_file_location = "privatekey.p12";
$client = new Google_Client();
$client->setApplicationName("WMtools_application");
$service = new Google_Service_Webmasters($client);
if (isset($_SESSION['service_token'])) {
$client->setAccessToken($_SESSION['service_token']);
}
$key = file_get_contents($key_file_location);
$cred = new Google_Auth_AssertionCredentials(
$service_account_name,
array('https://www.googleapis.com/auth/webmasters.readonly'),
$key
);
try{
$client->setAssertionCredentials($cred);
if ($client->getAuth()->isAccessTokenExpired()) {
$client->getAuth()->refreshTokenWithAssertion($cred);
}
$_SESSION['service_token'] = $client->getAccessToken();
}catch(Exception $e){
echo "Exception captured", $e->getMessage(), "\n";
}
try{
$results = $service->sites->listSites();
$siteList = $results->siteEntry;
var_dump($siteList);
}catch(Exception $e2){
echo "No results", $e2->getMessage(), "\n";
}

I solved the problem. The case is that i have delegated domain-wide authority to my service account and I didn't include in my petition to the API the user email from whom I want to access the data. To solve It just need to add it to the google_Auth_AssertionCredentials this way:
$cred = new Google_Auth_AssertionCredentials(
$service_account_name,
array('https://www.googleapis.com/auth/webmasters.readonly'),
$key
);
$cred->sub = $service_account_user_email; //example#google.com

Related

Unable to remove label in GMAIL PHP API

I am working on a project where I have several labels associated with every email. I want to remove the labels using gmail PHP API. I have followed the documentation and I have done all the steps. But, I do not know why I get Error, when I try to remove the label.
This is the code that is associated with the project. Please help me with any thoughts.
$client_id = 'aoppedisano#tecnavi.com';
$service_account_name = 'anthony#teak-truck- 130612.iam.gserviceaccount.com';
$key_file_location = 'anthony.p12';
$userid_from='aoppedisano#tecnavi.com';
$client = new Google_Client();
var_dump($client);
$client->setScopes(array('https://www.googleapis.com/auth/gmail.modify'));
$client->setApplicationName("Client_Library_Examples");
if (isset($_SESSION['service_token'])) {
$client->setAccessToken($_SESSION['service_token']);
}
$key = file_get_contents($key_file_location);
$cred = new Google_Auth_AssertionCredentials(
$service_account_name,
array(
/*
'https://www.googleapis.com/auth/gmail.send',
'https://www.googleapis.com/auth/gmail.compose',
'https://www.googleapis.com/auth/gmail.modify',
*/
'https://www.googleapis.com/auth/gmail.readonly'
),
$key
);
//var_dump($cred);
$cred->sub=$userid_from; //<-- Important!
$client->setAssertionCredentials($cred);
if ($client->getAuth()->isAccessTokenExpired()) {
$client->getAuth()->refreshTokenWithAssertion($cred);
}
$service = new Google_Service_Gmail($client);
$messageId=$_REQUEST["id"];
$userId = 'me';
$optParamsGet = [];
$optParamsGet['format'] = 'full';
$message = $service->users_messages->get('me',$messageId,$optParamsGet);
$labelsToRemove=$_REQUEST['label'];
$labelsToAdd=[];
$message=modifyMessage($service,$userId, $messageId, $labelsToAdd, $labelsToRemove);
function modifyMessage($service, $userId, $messageId, $labelsToAdd, $labelsToRemove) {
$mods = new Google_Service_Gmail_ModifyMessageRequest();
$mods->setAddLabelIds($labelsToAdd);
$mods->setRemoveLabelIds($labelsToRemove);
try {
$message = $service->users_messages->modify($userId, $messageId, $mods);
print 'Message with ID: ' . $messageId . ' successfully modified.';
return $message;
} catch (Exception $e) {
print 'An error occurred: ' . $e->getMessage();
}
}
As given in Standard Error Responses for Google APIs, 403: insufficientPermissions error code means that the authenticated user does not have sufficient permissions to execute this request.
To delete labels, you should have this scope code in your permissions:
https://www.googleapis.com/auth/gmail.labels
For more details about scopes, please go through Choose Auth Scopes.

Google Tasks - insert task from webpage

I'm trying to add a new task from my website to the Google Tasks. I checked the Google Tasks Api docs, and this is the code what I figured out:
<?php
session_start();
require_once 'google-api-php-client-master/autoload.php';
//Google credentials
$client_id = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.apps.googleusercontent.com';
$service_account_name = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.gserviceaccount.com';
$key_file_location = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.p12';
if (!strlen($service_account_name) || !strlen($key_file_location))
echo missingServiceAccountDetailsWarning();
$client = new Google_Client();
$client->setApplicationName("Whatever the name of your app is");
if (isset($_SESSION['service_token'])) {
$client->setAccessToken($_SESSION['service_token']);
}
$key = file_get_contents($key_file_location);
$cred = new Google_Auth_AssertionCredentials(
$service_account_name,
array('https://www.googleapis.com/auth/tasks'),
$key
);
$client->setAssertionCredentials($cred);
if($client->getAuth()->isAccessTokenExpired()) {
try {
$client->getAuth()->refreshTokenWithAssertion($cred);
} catch (Exception $e) {
var_dump($e->getMessage());
}
}
$_SESSION['service_token'] = $client->getAccessToken();
// Set task data
$task = new Task();
$task->setTitle('New Task');
$task->setNotes('Please complete me');
$task->setDue(new TaskDateTime('2015-02-26T12:00:00.000Z'));
$result = $service->insertTasks('#default', $task);
echo $result->getId();
?>
It says me "Fatal error: Class 'Task' not found in /customers/1/b/5/xxxxxxx.xx/httpd.www/test2/test2.php on line 34".
What do I do wrong? And what else should I do to get this code work?
The doc is for stable api. If you are using master version, it has to be like this:
$task = new Google_Service_Tasks_Task();
$task->setTitle('New Task');
$task->setNotes('Please complete me');
$task->setDue(new TaskDateTime('2015-02-26T12:00:00.000Z'));
$result = $service->tasks->insert('#default', $task);
echo $result->getId();

Google API Insufficient Permissions listing files

I am trying to create an app that (using a Drive service account) lists files in a given folder and allows users to search the content of those files. I am getting a 403 Insufficient Permissions error which I cannot explain.
I have edited the code from the Google API PHP Client Example:
$client_id = '[REMOVED]'; //Client ID
$service_account_name = '[REMOVED]'; //Email Address
$key_file_location = 'key.p12'; //key.p12
$client = new Google_Client();
$client->setApplicationName("Client_Library_Examples");
service = new Google_Service_Drive($client);
if (isset($_SESSION['service_token'])) {
$client->setAccessToken($_SESSION['service_token']);
}
$key = file_get_contents($key_file_location);
$cred = new Google_Auth_AssertionCredentials(
$service_account_name,
array(
'https://www.googleapis.com/auth/drive',
'https://www.googleapis.com/auth/drive.file'
),
$key
);
$client->setAssertionCredentials($cred);
if ($client->getAuth()->isAccessTokenExpired()) {
$client->getAuth()->refreshTokenWithAssertion($cred);
}
$_SESSION['service_token'] = $client->getAccessToken();
$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) {
echo "<br/>An error occurred: " . $e->getMessage();
$pageToken = NULL;
}
} while ($pageToken);
echo "<pre>";
print_r($result);
echo "</pre>";
echo "<br />Execution completed.";
The exact error message ($e->getMessage() in the catch above) is Error calling GET https://www.googleapis.com/drive/v2/files: (403) Insufficient Permission - I thought the /drive and /drive.file scopes gave me all the permissions I needed?
First, a quick note: You are requesting both the Drive scope and the Drive.File scope. The later is a subset of the former, so there is no need to request it. You should remove 'https://www.googleapis.com/auth/drive.file' line.
As to the insufficient permissions, this is possibility due to incorrect Developer Console configuration. You should double check that both the API and SDK are enabled for this particular project.
I had the same issue. I created a new secret in the Google Developer Console and re-authenticated. This fixed the problem.

Uncaught exception 'Google_Auth_Exception' with message 'Invalid code'

i'm tring to migrate my google calendar access from Zend to new google API since they closed the service in november. My web app uses google api to create some events.
I'm facing a recurring message that i could not resolve : Uncaught exception 'Google_Auth_Exception' with message 'Invalid code'
Here's my code :
define('STDIN',fopen("php://stdin","r"));
require_once '../../utils/google-api-php-client-master/autoload.php';
/**********************
OAUTH 2.0 AUTHORIZATION
***********************/
$client = new Google_Client();
// OAuth2 client ID and secret can be found in the Google Developers Console.
$client->setClientId('XXXXXX);
$client->setClientSecret('XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX');
$client->setRedirectUri('XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX');
$client->addScope('https://www.googleapis.com/auth/calendar');
$service = new Google_Service_Calendar($client);
$authUrl = $client->createAuthUrl();
//Request authorization
print "Please visit:\n$authUrl\n\n";
print "Please enter the auth code:";
echo(trim(fgets(STDIN)));
$authCode = trim(fgets(STDIN));
// Exchange authorization code for access token
$accessToken = $client->authenticate($authCode);
$client->setAccessToken($accessToken);
Could someone please help me ?
I finally got this stuff to start working myself and a lot of searching. I was also using Zend before. There is a very good website at Daimto.com where you can see a bunch of tutorials. Here is the code that worked for me to add an event using the code form Daimto.com and adding code for adding an event in the body. Remember you need ot have the service email added to the share of your google calendar too!
<?php
session_start();
require_once './google-api-php-client/src/Google/Client.php';
require_once './google-api-php-client/src/Google/Service/Calendar.php';
$client_id = '6846057_YOUR_CLIENT_ID_HERE_pg3q8r6.apps.googleusercontent.com';
$Email_address = '68460_YOUR_SERVICE_EMAIL_HERE_developer.gserviceaccount.com';
$key_file_location = '_KEY_FILE_LOCATION_HERE_8.p12';
$client = new Google_Client();
$client->setApplicationName("_APP_NAME_HERE_");
$key = file_get_contents($key_file_location);
// seproate additional scopes with a comma
$scopes ="https://www.googleapis.com/auth/calendar";
$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_Calendar($client);
?>
<html><body>
<?php
//$service = new Google_Service_Calendar($client);
//
$event = new Google_Service_Calendar_Event();
$event->setSummary('Event 2');
$event->setLocation('Somewhere');
$start = new Google_Service_Calendar_EventDateTime();
$start->setDateTime('2015-06-22T19:00:00.000+01:00');
$start->setTimeZone('Europe/London');
$event->setStart($start);
$end = new Google_Service_Calendar_EventDateTime();
$end->setDateTime('2015-06-22T19:25:00.000+01:00');
$end->setTimeZone('Europe/London');
$event->setEnd($end);
//
$calendar_id = "nm_GOOGLE_CAL_ID_HERE_#group.calendar.google.com";
//
$new_event = null;
//
try {
$new_event = $service->events->insert($calendar_id, $event);
//
$new_event_id= $new_event->getId();
} catch (Google_ServiceException $e) {
syslog(LOG_ERR, $e->getMessage());
}
//
$event = $service->events->get($calendar_id, $new_event->getId());
//
if ($event != null) {
echo "Inserted:";
echo "EventID=".$event->getId();
echo "Summary=".$event->getSummary();
echo "Status=".$event->getStatus();
}
?>

PHP Google Cloud Storage

I'm trying to use Google Cloud Storage in my PHP project - but not on the AppEngine platform. All the links and tutorials I found always use the AppEngine platform and therefor can use the gs:// links. Does anyone know how to connect and for example list objects in a bucket - or at least connect to the storage trough php without AppEngine?
try this code:
set_include_path("../src/" . PATH_SEPARATOR . get_include_path());
require_once 'Google/Client.php';
require_once("Google/Service/Storage.php");
$client_id = '<client-id>'; //Client ID
$service_account_name = '<service_account_name(email)>'; //Email Address
$key_file_location = 'key.p12'; //your key.p12 file
echo pageHeader("Service Account Access");
if ($client_id == '<YOUR_CLIENT_ID>'
|| !strlen($service_account_name)
|| !strlen($key_file_location)) {
echo missingServiceAccountDetailsWarning();
}
$client = new Google_Client();
$client->setApplicationName("<your application name>");
$service = new Google_Service_Storage($client);
if (isset($_SESSION['service_token'])) {
$client->setAccessToken($_SESSION['service_token']);
}
$key = file_get_contents($key_file_location);
$cred = new Google_Auth_AssertionCredentials(
$service_account_name,
array('https://www.googleapis.com/auth/devstorage.full_control'),
$key
);
$client->setAssertionCredentials($cred);
if($client->getAuth()->isAccessTokenExpired()) {
$client->getAuth()->refreshTokenWithAssertion($cred);
}
$_SESSION['service_token'] = $client->getAccessToken();
$acl = new Google_Service_Storage_ObjectAccessControl();
$acl->setEntity('allUsers');
$acl->setRole('READER');
$acl->setBucket('<your bucket name>');
$acl->setObject('your object name');
$service = new Google_Service_Storage($client);
$return_value = $service->objects->get('<bucket_name>','<object-name>');
You can use the JSON api.
To see it in action go here:
https://developers.google.com/apis-explorer/#p/storage/v1/storage.objects.list
Then enable OAuth2 in the top right and fill in your bucket name to see an example request and response.

Categories