Google Calendar API with PHP – Service Account - php

I've been trying for several days now to get a Google Calendar API up and running with absolutely no luck. I'm using PHP and a service account for authentication. I have followed this tutorial (http://www.daimto.com/google-calendar-api-with-php-service-account/) and the code below is from that tutorial.
I have setup my developers console to allow the calendar API, and I have added the developers email address to the calendar share section.
When I run this code, I just get a blank page - no error, no text of any kind, just a blank white page. I'm completely lost - any help would be much appreciated. Cheers
<?php
require 'vendor/autoload.php';
session_start();
$client_id = '123456789-qwertyuiop.apps.googleusercontent.com';
$Email_address = '123456789-qwertyuiop#developer.gserviceaccount.com';
$key_file_location = 'path_to_key/key.p12';
$client = new Google_Client();
$client->setApplicationName("Client_Library_Examples");
$key = file_get_contents($key_file_location);
// separate additional scopes with a comma
$scopes ="https://www.googleapis.com/auth/calendar.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_Calendar($client);
?>
<html><body>
<?php
$calendarList = $service->calendarList->listCalendarList();
while(true) {
foreach ($calendarList->getItems() as $calendarListEntry) {
echo $calendarListEntry->getSummary()."<br>\n";
// get events
$events = $service->events->listEvents($calendarListEntry->id);
foreach ($events->getItems() as $event) {
echo "-----".$event->getSummary()."<br>";
}
}
$pageToken = $calendarList->getNextPageToken();
if ($pageToken) {
$optParams = array('pageToken' => $pageToken);
$calendarList = $service->calendarList->listCalendarList($optParams);
} else {
break;
}
}
?>

Related

How to access user data with Google Webmaster Tools API

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

Google API error

I am trying to use google API to get events off calendars on an account. I am using a service account. I am receiving two errors when I attempt to manually echo the code or it will remain a blank page if I use foreach(...).
Here are the two errors:
Fatal error: Uncaught exception 'Google_Service_Exception' with message 'Error calling GET https://www.googleapis.com/calendar/v3/users/me/calendarList/primary: (404) Not Found' in C:\wamp\www\newOLP\scripts\oAuth2\Google\Http\REST.php on line 110
( ! ) Google_Service_Exception: Error calling GET https://www.googleapis.com/calendar/v3/users/me/calendarList/primary: (404) Not Found in C:\wamp\www\newOLP\scripts\oAuth2\Google\Http\REST.php on line 110
Here is my code:
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.
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 = $jsonDecode['client_id'];
$Email_address = $jsonDecode['client_email'];
$key_file_location = 'privateKey.p12';
$client = new Google_Client();
$client->setApplicationName("CalCon");
$key = file_get_contents($key_file_location);
// separate additional scopes with a comma
$scopes ="https://www.googleapis.com/auth/calendar.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_Calendar($client);
?>
<html><body>
<?php
$calendarList = $service->calendarList->listCalendarList();
echo $service->calendars->get('primary')->getSummary()."<br />";
echo $service->calendarList->get('primary')->getSummary();
while(true) {
foreach ($calendarList->getItems() as $calendarListEntry) {
echo $calendarListEntry;
echo "hi";
echo $calendarListEntry->getSummary()."<br>\n";
// get events
$events = $service->events->listEvents($calendarListEntry->id);
foreach ($events->getItems() as $event) {
echo "-----".$event->getSummary()."<br>";
}
}
$pageToken = $calendarList->getNextPageToken();
if ($pageToken) {
$optParams = array('pageToken' => $pageToken);
$calendarList = $service->calendarList->listCalendarList($optParams);
} else {
break;
}
}
?>
</body></html>

Google Calendar API inserting event

So, I downloaded this API library https://github.com/google/google-api-php-client.git
And installed it on server, then set up very simple script to add an event to my google calendar, first part of script makes sure your connection is good, second part tries to add event. So, connection is good, but adding event is not.. it gives me back
`Fatal error: Uncaught exception 'Google_Service_Exception' with message 'Error calling POST https://www.googleapis.com/calendar/v3/calendars/primary/events: (403) Insufficient Permission'`
here is the script, can someone help?
<?php
session_start();
require '../google-api-php-client-master/src/Google/autoload.php';
require_once '../google-api-php-client-master/src/Google/Client.php';
require_once '../google-api-php-client-master/src/Google/Service/Calendar.php';
$client_id = '574154490008-l55646vdpf62f7nrim9dodhtg6ssv4qv.apps.googleusercontent.com';
$Email_address = '574154490008-l55646vdpf62f7nrim9dodhtg6ssv4qv#developer.gserviceaccount.com';
$key_file_location = 'someproject-9e09f9db466c.p12';
$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/calendar.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_Calendar($client);
?>
<html><body>
<?php
$calendarList = $service->calendarList->listCalendarList();
print_r($calendarList);
while(true) {
foreach ($calendarList->getItems() as $calendarListEntry) {
echo "<a href='Oauth2.php?type=event&id=".$calendarListEntry->id." '>".$calendarListEntry->getSummary()."</a><br>\n";
}
$pageToken = $calendarList->getNextPageToken();
if ($pageToken) {
$optParams = array('pageToken' => $pageToken);
$calendarList = $service->calendarList->listCalendarList($optParams);
} else {
break;
}
}
//--------------- trying to insert EVENT
$event = new Google_Service_Calendar_Event();
$event->setSummary('Appointment');
$event->setLocation('Somewhere');
$start = new Google_Service_Calendar_EventDateTime();
$start->setDateTime('2015-04-16T10:00:00.000-07:00');
$event->setStart($start);
$end = new Google_Service_Calendar_EventDateTime();
$end->setDateTime('2015-04-16T10:25:00.000-07:00');
$event->setEnd($end);
$attendee1 = new Google_Service_Calendar_EventAttendee();
$attendee1->setEmail('some#gmail.com');
// ...
$attendees = array($attendee1
//, ...
);
$event->attendees = $attendees;
$createdEvent = $service->events->insert('primary', $event);
echo $createdEvent->getId();
?>
</html>
Ok, So I just edited this line $scopes ="https://www.googleapis.com/auth/calendar"; I deleted ".readonly" so now I am getting eventId back as if I was inserting events successfully, but events are not showing up in the calendar.
You need share the calendar with your service account!
In the field e-mail put your e-mail (service account), that means like:
914304219907-rt42vptejtgg9fhb9btthdb2gbuctonp#developer.gserviceaccount.com

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 Calendar API, getItem and getSummery returns nothing

I seem to have bumped into a google calendar api problem. and I can't really see where I have made the error so an extra set of eyes would be greatly appreciated. The problem in short is that the part of the code that should output the events.. doesn't (the "result" part of the code.
require_once "./google-api-php-client/src/Google/Client.php";
require_once "./google-api-php-client/src/Google/Service/Calendar.php";
// Service Account info
$client_id = "XXXXXX-XXXXXXXXXXXXXXXXXXXXX.apps.googleusercontent.com";
$app_name = "Some-name";
$service_account_name = 'XXXXX-XXXXXXXXXXXXXXXXXXXXXXX#developer.gserviceaccount.com';
$key_file_location = 'google-api-php-client/Some-name-xxxxxxxxxx.p12';
$cal_id = "primary";
// Service Account info
$client_id = $client_id;
$service_account_name = $service_account_name;
$key_file_location = $key_file_location;
// Calendar id
$calName = $cal_id;
$client = new Google_Client();
$client -> setApplicationName($app_name);
$service = new Google_Service_Calendar($client);
$key = file_get_contents($key_file_location);
$cred = new Google_Auth_AssertionCredentials(
$service_account_name,
array('https://www.googleapis.com/auth/calendar.readonly'),
$key
);
$client->setAssertionCredentials($cred);
$cals = $service->calendarList->listCalendarList();
print_r($cals);
echo "<br>events<br>";
$events = $service->events->listEvents($calName);
var_dump($events);
echo "<br>result:<br>";
// the following is what returns nothing, works fine until this point.
$i = 0;
foreach ( $events->getItems() as $event ) {
echo 'i:'.$i.' '.$event->getSummary();
$i++;
}
echo 'end';
Change $events to the below line:
$events = $service->events->listEvents('primary', $params);
Instead of primary, add $calName and also send $params in listEvents method.
Hope this works.

Categories