Google Calendar API inserting event - php

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

Related

How to insert event into a private Google Calendar with PHP?

I'm trying to add new events into my private Google Calendar, but I get (403) Forbidden message. I've searched the internet but I found no answer to my issue.
My scope is set to read/write, and the credentials should be ok, because I can read out all of my events so the connection works fine.
Here's the code:
$service_account = $this->service_account;
$json_key = json_decode(file_get_contents($this->json_url));
$scopes = 'https://www.googleapis.com/auth/calendar';
$application_name = 'Calendar';
$client = new Google_Client();
$client->setApplicationName($application_name);
$cred = new Google_Auth_AssertionCredentials($service_account, array($scopes), $json_key->private_key);
$client->setAssertionCredentials($cred);
if($client->getAuth()->isAccessTokenExpired()) {
$client->getAuth()->refreshTokenWithAssertion($cred);
}
$google_service = new Google_Service_Calendar($client);
$calendar_ids = $this->calendar_ids;
$event = new Google_Service_Calendar_Event();
$event->setSummary($service);
$event->setDescription($user);
$event->setLocation($location);
$start = new Google_Service_Calendar_EventDateTime();
$start->setDateTime($this->sqlDateToGcalDate($start_date));
$event->setStart($start);
$end = new Google_Service_Calendar_EventDateTime();
$end->setDateTime($this->sqlDateToGcalDate($end_date));
$event->setEnd($end);
$google_service->events->insert($calendar_ids[$steed], $event);
$google_service->events->insert($calendar_ids[$location], $event);

Google Calendar API with PHP – Service Account

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

Google Api v3 get modified event via watch(web_hook)

Am using Google Api v3 for adding and modifying google events .
most of the thing works fine except am unable to get the changes made in google events
am using the below code :
require_once 'google-api-php-client/src/Google/Client.php';
require_once 'google-api-php-client/src/Google/Service/Analytics.php';
require_once 'google-api-php-client/src/Google/Service/Calendar.php';
$client_id = 'my-client_id'; // works without this
$Email_address = 'my-Email_address';
$key_file_location = 'my-key_file_location.p12';
$client = new Google_Client();
$client->setApplicationName("app-name"); // works without random names
$key = file_get_contents($key_file_location);
$scopes = array('https://www.googleapis.com/auth/calendar', 'https://www.googleapis.com/auth/calendar.readonly');
$cred = new Google_Auth_AssertionCredentials($Email_address, $scopes , $key);
$client->setAssertionCredentials($cred);
if ($client->getAuth()->isAccessTokenExpired())
{
$client->getAuth()->refreshTokenWithAssertion($cred);
}
$service = new Google_Service_Calendar($client);
$cals = $service->calendarList->listCalendarList();
$event = new Google_Service_Calendar_Event();
$event->setSummary('04/03 appointment -1');
$start = new Google_Service_Calendar_EventDateTime();
$start->setDateTime('2015-03-27T11:00:00.000-00:00');
$start->setTimeZone('Asia/Calcutta');
$event->setStart($start);
$end = new Google_Service_Calendar_EventDateTime();
$end->setDateTime('2015-03-27T11:25:00.000-00:00');
$end->setTimeZone('Asia/Calcutta');
$event->setEnd($end);
$attendee1 = new Google_Service_Calendar_EventAttendee();
$attendee1->setEmail('myemail#gmail.com');
$attendees = array($attendee1);
$event->attendees = $attendees;
$recurringEvent = $service->events->insert('randome-id#group.calendar.google.com', $event);
echo $dynamicId = $recurringEvent->getId();
$events = $service->events->listEvents('randome-id#group.calendar.google.com');
echo "<br>start - into web hoot <br>";
$service = new Google_Service_Calendar($client);
$channel = new Google_Service_Calendar_Channel($client);
$channel->setId($dynamicId);
$channel->setType('web_hook');
echo '<br>';
echo $url = 'https://mydomain.com.return.php';
$channel->setAddress($url);
$timetoExpire = time()+3600000;
$optParams = array('ttl' => $timetoExpire);
$channel->setParams($optParams);
try
{
echo "<br>";
$watchEvent = $service->events->watch('randome-id#group.calendar.google.com', $channel);
print_r($watchEvent);
echo "<br>hook applied<br>";
}
catch(Exception $e)
{
echo $e;
echo "web hook not working<br />.";
}
echo "<br>end";
exit;
return response comes properly in https://mydomain.com.return.php but still am not sure how to read the response
and am unsure
what is
[resourceId] =7U94nhlXTXH_tK13-5JIrZTBWU0
[resourceUri] =https://www.googleapis.com/calendar/v3/calendars/randome-id#group.calendar.google.com/events?alt=json
please help me to figure out how to get the modified event date in goggle calender Thanks in advance

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();
}
?>

Events added through Google API PHP client not showing in Calendar

I'm using Google API PHP client to add events to my calendar. ID is returned successfully after the insert & When I fetch that event using the ID it displays summary & everything correctly & for some reason , the event is showing up in my calendar
I'm using Service Account Credentials. Is there something to be enabled to get this working?
Here's my Code
session_start();
require dirname(__FILE__).'/google-api-php-client-master/autoload.php';
$client_id = '<client ID>';
$service_account_name = '<Service Account Name>';
$key_file_location = dirname(__FILE__).'/API-Project-96c2a9122085.p12';
if (!strlen($service_account_name) || !strlen($key_file_location)) {
echo missingServiceAccountDetailsWarning();
}
$client = new Google_Client();
$client->setApplicationName("Client_Library_Examples");
$service = new Google_Service_Calendar($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/calendar'),$key);
$client->setAssertionCredentials($cred);
if ($client->getAuth()->isAccessTokenExpired()) {
$client->getAuth()->refreshTokenWithAssertion($cred);
}
$_SESSION['service_token'] = $client->getAccessToken();
$event = new Google_Service_Calendar_Event();
$event->setSummary("WHY IS THIS NOT WOKING?");
$start = new Google_Service_Calendar_EventDateTime();
$start->setDateTime(date('Y-m-d\TH:i:s',strtotime('2014-12-24 10:00:00')));
$start->setTimeZone('Australia/Melbourne');
$event->setStart($start);
$end = new Google_Service_Calendar_EventDateTime();
$end->setDateTime(date('Y-m-d\TH:i:s',strtotime('2014-12-26 12:00:00')));
$end->setTimeZone('Australia/Melbourne');
$event->setEnd($end);
$newEvent = $service->events->insert('primary', $event);
$newEvent->getId();
$event = $service->events->get('primary', $newEvent->getId());
echo '<pre>'; print_r($event); echo '</pre>';
With the new Google_Client API, you need to share your calendar to yourself.
$scope = new Google_Service_Calendar_AclRuleScope();
$scope->setType('user');
$scope->setValue( 'Your Email Goes Here' );
$rule = new Google_Service_Calendar_AclRule();
$rule->setRole( 'owner' );
$rule->setScope( $scope );
$result = $service->acl->insert('primary', $rule);
Let me know if you still have issue.

Categories