PHP Google Calendar API: Adding Multiple Events at Once - php

Using version 3 of the Google Calendar API. I can add one event at a time, but I want to add multiple events at once. Any idea how to do this? I assign $authUrl to my template below, the user clicks a link that says "add all items to google calendar", authorizes that Google can access the account, it goes back to my callback URL with $_GET['code'] assigned so the whole $client->getAccessToken() block gets executed.
Obviously I'm using dummy data now, but I want to populate the fields with data from expression engine. I have that data available, but for the sake of simplicity for this question, spared the crap and put in test data.
This code works for one event:
$client = new apiClient();
$client->setApplicationName("Band Calendar");
$cal = new apiCalendarService($client);
if (isset($_GET['logout'])) {
unset($_SESSION['token']);
}
if (isset($_GET['code'])) {
$client->authenticate();
$_SESSION['token'] = $client->getAccessToken();
header('Location: http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF']);
}
if (isset($_SESSION['token'])) {
$client->setAccessToken($_SESSION['token']);
}
$authUrl = $client->createAuthUrl();
if ($client->getAccessToken()) {
$event = new Event();
$event->setSummary("test title");
$event->setLocation("test location");
$start = new EventDateTime();
$start->setDateTime('2012-03-03T09:25:00.000-05:00');
$event->setStart($start);
$end = new EventDateTime();
$end->setDateTime('2012-03-03T10:25:00.000-05:00');
$event->setEnd($end);
$attendee1 = new EventAttendee();
$attendee1->setEmail('email#email.com');
$attendees = array($attendee1);
$event->attendees = $attendees;
$createdEvent = $cal->events->insert('primary', $event);
echo $createdEvent->getId();
$_SESSION['token'] = $client->getAccessToken();
}
I've noticed that there's a "class Events" that I can instantiate (rather than just instantiating a single Event object) and that it has an $items member variable. I'm guessing I can add a bunch of Event objects to the $item member variable and then send a bunch of events at once, but can't seem to get it right. Anyone have experience with this?

Judging from the PHP and Java documentation for v3 this is not possible. Calendar.Events (in Java) is a wrapper around a calendar's event-related methods in the API: you can ask it to insert one event, but you cannot use it as a representation of several events and e.g. pass it to the server (for bulk insert).
At least that's what I've concluded for now. (I could also use the feature.)

Related

Google API and OAuth 2.0

I'm trying to use google calendar API with php library and i'm facing issues on the authentification of the user to the google api.
I have a question. I've seen some come where you had to set the Api key / developer key to the Google_Client object with the method setDeveloperKey(), but i've also seen some people who don't. Could someone explain to me what difference does it make ?
The thing i'd like to do is to connect a user who have a google account to my application so he can add, list, remove, etc, events from a calendar. This is what i'm doing for the moment for the authentification :
$client = new Google_Client();
$client->setApplicationName("Test GCAL");
$client->setClientId($clientid);
$client->setClientSecret($clientsecret);
$client->setRedirectUri($callback_url);
$client->setAccessType("offline");
$client->setApprovalPrompt("force");
$client->setScopes("https://www.googleapis.com/auth/calendar");
$service = new Google_Service_Calendar($client);
Am i doing it right ?
Does someone have a working commented code that i can analyse ? I can't find one that's working on the internet.. Or maybe a tutorial that explain everything about google api and oauth stuff. I'm so confused about tokens and nobody seems to use refresh tokens, and to me that's essential.. But maybe i'm wrong ?
Thanks for your answers
I don't think you NEED to use setDeveloperKey I suspect that its only used for public APIs to enable you to use them but I haven't really tested it or thought about it before. I will have to look into that a bit more.
This is the code I use for connecting to Google Calendar with Oauth2. ripped directly from the Accessing Google Calendar with PHP – Oauth2 tutorial
<?php
require_once 'Google/Client.php';
require_once 'Google/Service/Calendar.php';
require_once 'CalendarHelper.php';
session_start();
$client = new Google_Client();
$client->setApplicationName("Client_Library_Examples");
$client->setDeveloperKey("AIzaSyBBH88dIQPjcl5nIG-n1mmuQ12J7HThDBE");
$client->setClientId('2046123799103-i6cjd1hkjntu5bkdkjj5cdnpcu4iju8p.apps.googleusercontent.com');
$client->setClientSecret('6s4YOx3upyJhtwnetovfK40e');
$client->setRedirectUri('http://localhost/google-api-php-client-samples/Calendar/oauth2Pure.php');
$client->setAccessType('offline'); // Gets us our refreshtoken
$client->setScopes(array('https://www.googleapis.com/auth/calendar.readonly'));
//For loging out.
if (isset($_GET['logout'])) {
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 (!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'])) {
$client->setAccessToken($_SESSION['token']);
print "<a class='logout' href='".$_SERVER['PHP_SELF']."?logout=1'>LogOut</a><br>";
$service = new Google_Service_Calendar($client);
$calendarList = $service->calendarList->listCalendarList();;
print_r($calendarList);
while(true) {
foreach ($calendarList->getItems() as $calendarListEntry) {
echo $calendarListEntry->getSummary()."<br>\n";
}
$pageToken = $calendarList->getNextPageToken();
if ($pageToken) {
$optParams = array('pageToken' => $pageToken);
$calendarList = $service->calendarList->listCalendarList($optParams);
} else {
break;
}
}
}
?>

Trying to create event in google calendar

i was started working on google calendar recently. i gone through their documentation but it was not clear.
The code following is to insert event into users calendar.
<?php
require_once dirname(__FILE__).'/Google/Client.php';
require_once dirname(__FILE__).'/Google/Service/Analytics.php';
require_once dirname(__FILE__).'/Google/Service/Calendar.php';
$scriptUri = "http://".$_SERVER["HTTP_HOST"].$_SERVER['PHP_SELF'];
$client = new Google_Client();
$client->setAccessType('online');
$client->setApplicationName('MYAPP');
$client->setClientId('XXXXXXXXXXXX');
$client->setClientSecret('XXXXXXXXXXXX');
$client->setRedirectUri($scriptUri);
$client->setDeveloperKey('XXXXXXXXXXXXXXXXX'); // API key
$scopes = array('https://www.googleapis.com/auth/calendar');
$client->setScopes($scopes);
$cal = new \Google_Service_Calendar($client);
if (isset($_GET['logout'])) { // logout: destroy token
unset($_SESSION['token']);
die('Logged out.');
}
if (isset($_GET['code'])) {
$client->authenticate($_GET['code']);
$_SESSION['token'] = $client->getAccessToken();
}
if (isset($_SESSION['token'])) { // extract token from session and configure client
$token = $_SESSION['token'];
$client->setAccessToken($token);
}
if (!$client->getAccessToken()) { // auth call to google
$authUrl = $client->createAuthUrl();
header("Location: ".$authUrl);
die;
}
$event = new Google_Event();
$event->setSummary('Halloween');
$event->setLocation('The Neighbourhood');
$start = new Google_EventDateTime();
$start->setDateTime('2012-10-31T10:00:00.000-05:00');
$event->setStart($start);
$end = new Google_EventDateTime();
$end->setDateTime('2012-10-31T10:25:00.000-05:00');
$event->setEnd($end);
$createdEvent = $cal->events->insert("xxxxxx#gmail.com", $event); //Returns array not an object
echo $createdEvent->id;
But am getting fatal error like
Class 'Google_Event' not found
Please help with this issue. i searched in Stack overflow for the same problem . i didn't get any solution. any type of help is appreciated
I just found the solution for myself.
It turns out that they changed all the names again.
Replace Google by Google_Service_Calendar_
Eg:
$event = new Google_Service_Calendar_Event();
becomes now :
$event = new Google_Service_Calendar_Event();
It will work !
I have no working code as I opted for the Service Account method.
Maybe you can try removing the
" $client->setDeveloperKey('XXXXXXXXXXXXXXXXX'); " which often gives error.
You can also modify your config.php file and opt for offline mode. (see documentation).
Finally you can refresh token with this code :
if($client->isAccessTokenExpired()) {
$client->authenticate();
$NewAccessToken = json_decode($client->getAccessToken());
$client->refreshToken($NewAccessToken->refresh_token);
}
Finally, you can logout, delete cache so that you get a new token. Hope it helps

How to create Google calendar entry w/o user?

Recently I've decided to give users at my site the following functionality: online time slot booking in calendars of my employees. All employees have Google accounts linked to our domain in Google Apps (free edition). Users make booking in some front-end (e.g. not directly in employees Google calendars), then request is processed at our PHP server and if it is correct, server should be able to create new calendar entry in selected employee Google calendar. Note - neither user, nor employee should not be asked for authentication during booking.
I've scanned Google calendar v3 API and forums and still didn't get neither clear answer not concise examples - is such scenario possible with Google calendar? Can someone help me to answer the Q (and if possible - share a link with proper example)?
Are you familiar with adding an event with authentication? Like i answered here.
And like in the code below. If you are... you can go to the next level ;)
(You can download the Google Api Php-client on this page. On this page there is a tutorial. It's for Google+ but the principle is the same)
The first time you would always need authentication. There is no way around that. In the example below you get a token back after authentication, which includes an access_token and a refresh_token. The access_token is only valid for 3600 seconds and is used for direct access. When the access_token is expired you get a 401 error and you can use the refresh_token (together with client_id, client_secret and the correct grant_type) to request a new access_token.
You can find some more information on this page (at the bottom "Using a Refresh Token"). There are some limits in numbers to request these, mentioned on that page at the bottom.
This is some testing code i made the last time i helped someone with this. It only shows getting the authentication and storing the token in a cookie. It does not request a new access_token after it expires.
But as i already said you need to store the token (in a database?) and when you get a 401 you need to request a new access_token with the client_id, client_secret, correct grant_type and refresh_token. There is no (re-)authentication necessary for that.
<?php
error_reporting(E_ALL);
require_once 'google-api-php-client/src/Google_Client.php';
require_once 'google-api-php-client/src/contrib/Google_CalendarService.php';
session_start();
if ((isset($_SESSION)) && (!empty($_SESSION))) {
echo "There are cookies<br>";
echo "<pre>";
print_r($_SESSION);
echo "</pre>";
}
$client = new Google_Client();
$client->setApplicationName("Google Calendar PHP Starter Application");
$client->setClientId('###');
$client->setClientSecret('###');
$client->setRedirectUri('http://###/add_calendar.php'); // <- registered web-page
//$client->setDeveloperKey('###'); // <- not always needed
$cal = new Google_CalendarService($client);
if (isset($_GET['logout'])) {
echo "<br><br><font size=+2>Logging out</font>";
unset($_SESSION['token']);
}
if (isset($_GET['code'])) {
echo "<br>I got a code from Google = ".$_GET['code']; // You won't see this if redirected later
$client->authenticate(); // $_GET['code']
$_SESSION['token'] = $client->getAccessToken();
header('Location: http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF']);
// not strictly necessary to redirect but cleaner for the url in address-bar
echo "<br>I got the token = ".$_SESSION['token']; // <-- not needed to get here unless location uncommented
}
if (isset($_SESSION['token'])) {
echo "<br>Getting access";
$client->setAccessToken($_SESSION['token']);
}
if ($client->getAccessToken()){
echo "<hr><font size=+1>I have access to your calendar</font>";
$event = new Google_Event();
$event->setSummary('=== I ADDED THIS ===');
$event->setLocation('The Neighbourhood');
$start = new Google_EventDateTime();
$start->setDateTime('2013-11-29T10:00:00.000-05:00');
$event->setStart($start);
$end = new Google_EventDateTime();
$end->setDateTime('2013-11-29T10:25:00.000-05:00');
$event->setEnd($end);
$createdEvent = $cal->events->insert('###', $event); // <- ### = email of calendar
echo "<br><font size=+1>Event created</font>";
echo "<hr><br><font size=+1>Already connected</font> (No need to login)";
} else {
$authUrl = $client->createAuthUrl();
print "<hr><br><font size=+2><a href='$authUrl'>Connect Me!</a></font>";
}
$url = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
echo "<br><br><font size=+2><a href=$url?logout>Logout</a></font>";
?>
Edit:
If you don't want the initial authentication Google has its "Service Acounts", as you pointed out.
(I didn't know about these :)
I dug up some links where you can find code to use after you got the key-file.
Edit Google calendar events from Google service account: 403
Access Google calendar events from with service account: { "error" : "access_denied" }. No google apps
Google OAuth 2.0 Service Account - Calendar API (PHP Client)
https://groups.google.com/forum/#!topic/google-api-php-client/B7KXVQvx1k8
https://groups.google.com/forum/?fromgroups#!topic/google-api-php-client/IiwRBKZMZxw
Edit #2: YES, got it working. (even with my free Google account ;)
Here is the working code:
<?
error_reporting(E_ALL);
require_once 'google-api-php-client/src/Google_Client.php';
require_once 'google-api-php-client/src/contrib/Google_CalendarService.php';
session_start();
echo "Busy<br>";
const CLIENT_ID = 'xxxxxxxxxx.apps.googleusercontent.com';
const SERVICE_ACCOUNT_NAME = 'xxxxxxxxxxx#developer.gserviceaccount.com';
const KEY_FILE = 'xxxxxxxxxxxxxxxxxxx-privatekey.p12';
const CALENDAR_NAME = 'xxxxxxx#gmail.com';
$client = new Google_Client();
$client->setApplicationName("mycal");
if (isset($_SESSION['token'])) {
$client->setAccessToken($_SESSION['token']);
}
$key = file_get_contents(KEY_FILE);
$client->setClientId(CLIENT_ID);
$client->setAssertionCredentials(new Google_AssertionCredentials(
SERVICE_ACCOUNT_NAME,
array('https://www.google.com/calendar/feeds/'),
$key)
);
$client->setClientId(CLIENT_ID);
$service = new Google_CalendarService($client);
$event = new Google_Event();
$event->setSummary('=== I MADE THIS ===');
$event->setLocation('Somewhere else');
$start = new Google_EventDateTime();
$start->setDateTime('2013-11-30T10:00:00.000-02:00');
$event->setStart($start);
$end = new Google_EventDateTime();
$end->setDateTime('2013-11-30T10:25:00.000-02:00');
$event->setEnd($end);
$createdEvent = $service->events->insert(CALENDAR_NAME, $event);
echo "Done<br>";
?>
I needed to make a "new project" on https://cloud.google.com/console#/project. I couldn't use the existing one. After activating "Calendar API" and registering a new Web-app with Certificate i only needed to share my calendar with the xxxx#developer.gserviceaccount.com and above code worked
(without authentication).
Edit #3: and now it also seems to be working in the default "Google+ API Project"

Insert Moment in Google+ using Google PHP Client

I'm trying to insert some activity app in a Google+ profile as shown in this documentation page:
https://developers.google.com/+/api/latest/moments/insert
I successfully obtain the access token needed, but seems the moments->insert method doesn't make anything.
If successful I would expect to see something on this page, once made the access, but nothing happen
https://plus.google.com/u/0/apps/activities
That's my code
<?php
require_once '../google-api-php-client/Google_Client.php';
require_once '../google-api-php-client/contrib/Google_PlusService.php';
session_start();
$client = new Google_Client();
$client->setClientId('xxxxxxxxxxxx-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.apps.googleusercontent.com');
$client->setClientSecret('xxxxxxxxxxxxxxxxxxxxxxxx');
$client->setRedirectUri('http://www.myregisteredcallbackurl.com');
$client->setAccessType('offline');
$client->setScopes(array('https://www.googleapis.com/auth/plus.login'));
$client->setApprovalPrompt('force');
$plus = new Google_PlusService($client);
if (isset($_GET['logout'])) {
unset($_SESSION['token']);
}
if (isset($_GET['code'])) {
$client->authenticate($_GET['code']);
$_SESSION['token'] = $client->getAccessToken();
header('Location: http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF']);
}
if (isset($_SESSION['token'])) {
echo 'Logout<br><br>'.PHP_EOL.PHP_EOL;
$client->setAccessToken($_SESSION['token']);
$moment = new Google_Moment();
$moment->setType('http://schemas.google.com/AddActivity');
$itemScope = new Google_ItemScope();
$itemScope->setUrl('https://developers.google.com/+/plugins/snippet/examples/thing');
$moment->setTarget($itemScope);
$plus->moments->insert('me', 'vault', $moment);
}
if ($client->getAccessToken()) {
$_SESSION['token'] = $client->getAccessToken();
} else {
$authUrl = $client->createAuthUrl();
echo 'Connect<br>';
}
You need to add the requestvisibleactions permissions to your scope. The easiest way to do this is to switch from the conventional OAuth 2.0 flow to the new Google+ Sign-In flow - the Google+ team provides a PHP sample for Google+ Sign-In. If you want to continue using the older OAuth flow, you need to append request_visible_actions=[the app activity types] to your authorization URL.
Related questions:
Google+ PHP moments not working
Google+ Insert moment using dot-net-client
Google+ unable to insert moment
In your code, you are really close, the following seems to work for me:
$client = new Google_Client();
$client->setClientId('YOUR_CLIENT_ID');
$client->setClientSecret('YOUR_CLIENT_SECRET');
$client->setRedirectUri('http://example.com/callback.php');
$client->setAccessType('offline');
$client->setScopes(array('https://www.googleapis.com/auth/plus.login'));
$client->setRequestVisibleActions(array('https://schemas.google.com/AddActivity'));
$plus = new Google_PlusService($client);
To check the app activities that you have written, visit the app activity log.

creating google calendar event

am trying to create google calendar event using the following code given below, but am getting class Event not found . How to create a new event. please help
<?php
require_once '../../src/Google_Client.php';
require_once '../../src/contrib/Google_CalendarService.php';
session_start();
$client = new Google_Client();
$client->setApplicationName("Google Calendar PHP Starter Application");
$client->setClientId('');
$client->setClientSecret('');
$client->setRedirectUri('simple.php');
$client->setDeveloperKey('insert_your_developer_key');
$cal = new Google_CalendarService($client);
if (isset($_GET['logout'])) {
unset($_SESSION['token']);
}
if (isset($_GET['code'])) {
$client->authenticate($_GET['code']);
$_SESSION['token'] = $client->getAccessToken();
header('Location: http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF']);
}
if (isset($_SESSION['token'])) {
$client->setAccessToken($_SESSION['token']);
}
$authUrl = $client->createAuthUrl();
if (!$client->getAccessToken()) {
here am creating the new event
$event = new Event();
$event->setSummary("test title");
$event->setLocation("test location");
$start = new EventDateTime();
$start->setDateTime('04-03-2012 09:25:00:000 -05:00');
$event->setStart($start);
$end = new EventDateTime();
$end->setDateTime('04-03-2012 10:25:00:000 -05:00');
$createdEvent = $cal->events->insert('primary', $event);
echo $createdEvent->getId();
}
I had the exact same problem. Their documentation very incomplete. The class names are wrong in their example. Here is the code I got to work:
$event = new Google_Event();
$event->setSummary('Halloween');
$event->setLocation('The Neighbourhood');
$start = new Google_EventDateTime();
$start->setDateTime('2012-10-31T10:00:00.000-05:00');
$event->setStart($start);
$end = new Google_EventDateTime();
$end->setDateTime('2012-10-31T10:25:00.000-05:00');
$event->setEnd($end);
$createdEvent = $cal->events->insert('[calendar id]', $event); //Returns array not an object
echo $createdEvent->id;
$cal->events->insert returns an array, not an object like in their example code. If you want it to return an object you need to define it in your Google_Client call, like so:
$client = new Google_Client(array('use_objects' => true));
I had this problem too, and it seems things have changed with Google's API again.
Using the code example in the docs I was trying do
$calendar = new Calendar();
This threw an error for class Calendar not found. Turns out everything was renamed and I had to do the following:
$calendar = new Google_Service_Calendar_Calendar();
Seems like an ok naming convention to avoid conflicts, but it would have been nice to update the docs. So to solve OP's problem today he would now solve his issue using:
$event = new Google_Service_Calendar_Event();
You can look through the file Google/Service/Calendar.php and you should see all the relevant classes named with this naming convention.

Categories