Automatically access google calendar - php

I need help dealing with google calendar. My code is below:
<?php
require_once 'google-api-php-client/src/Google_Client.php';
require_once 'google-api-php-client/src/contrib/Google_CalendarService.php';
session_start();
$client = new Google_Client();
$client->setApplicationName("Google Calendar PHP Starter Application");
// Visit https://code.google.com/apis/console?api=calendar to generate your
// client id, client secret, and to register your redirect uri.
$client->setClientId('client id');
$client->setClientSecret('client secret');
$client->setRedirectUri('redirect uri');
$client->setDeveloperKey('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']);
exit();
}
if (isset($_SESSION['token'])) {
$client->setAccessToken($_SESSION['token']);
}
if ($client->getAccessToken()) {
$calList = $cal->calendarList->listCalendarList();
print "<h1>Calendar List</h1><pre>" . print_r($calList, true) . "</pre>";
$_SESSION['token'] = $client->getAccessToken();
// Create a new event and display it.
// Caution: every time you run this script a new event is created. Oh well.
$event = new Google_Event();
$event->setSummary('Appointment');
$event->setLocation('Somewhere');
$start = new Google_EventDateTime();
$start->setDateTime('2013-08-24T10:00:00.000-07:00');
$event->setStart($start);
$end = new Google_EventDateTime();
$end->setDateTime('2013-08-25T10:25:00.000-07:00');
$event->setEnd($end);
$createdEvent = $cal->events->insert('primary', $event);
$events = $cal->events->listEvents('primary');
echo "<pre>" . print_r($events, true) . "</pre>";
}
else {
$authUrl = $client->createAuthUrl();
print "<a class='login' href='$authUrl'>Connect Me!</a>";
exit();
}
?>
Basically this code has a connect me link and when clicked, asks the user to input their gmail account. However, I want to skip this entire process of allowing the person to enter their username and password information and just add the event when I run this code. Does the idea of using service account for google api access solve this or does it involve storing a token in a database and constantly changing it work (which I am struggling to do)? Any help would be appreciated.

Related

insert event to google calendar using php not working

I am using google api to insert event into google calendar but there is a problem. when i run it return me an error:
404
Error: invalid_request
Missing required parameter: scope
Learn more
Request Details
response_type=code
access_type=online
client_id=#####.com
redirect_uri=http://index.php
state=
scope=
approval_prompt=auto
Here is my code please check and let me know what i am doing wrong
require_once __DIR__ . '/google-api-php-client-master/src/Google/vendor/autoload.php';
require_once __DIR__ . "/google-api-php-client-master/src/Google/Client.php";
error_reporting(E_ALL);
//require_once 'google-api-php-client/src/Google_Client.php';
require_once __DIR__ . '/google-api-php-client-master/src/Google/Calendar.php';
session_start();
if ((isset($_SESSION)) && (!empty($_SESSION))) {
echo "There are cookies<br>";
echo "<pre>";
print_r($_SESSION);
echo "</pre>";
}
$scopes ="https://www.googleapis.com/auth/calendar.readonly";
$client = new Google_Client();
$client->setApplicationName("Google Calendar PHP Starter Application");
$client->setClientId('####.com');
$client->setClientSecret(FG#####');
$client->setRedirectUri('http://index.php');
$client->setDeveloperKey('h#####');
$cal = new Google_Service_Calendar_Calendar($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']);
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('Halloween');
$event->setLocation('The Neighbourhood');
$start = new Google_EventDateTime();
$start->setDateTime('2013-9-29T10:00:00.000-05:00');
$event->setStart($start);
$end = new Google_EventDateTime();
$end->setDateTime('2013-9-29T10:25:00.000-05:00');
$event->setEnd($end);
$createdEvent = $cal->events->insert('###', $event);
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();
//echo "<pre>"; print_r($authUrl); die;
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>";

Error Using PHP to add an event to Google Calendar

Like so many others before me, I'm having great difficulty getting full functionality to a PHP script that adds/deletes/Updates Google Calendar events.
My code, from the Daimto web site works using Oauth2 in that it lists the current events in my main calendar.
However when I add some code to add an event, the page is blank and I'm unable to trap an error.
The code is:
<?php
require_once realpath(dirname(__FILE__) . '/../src/Google/autoload.php');
session_start();
// ******************************************************** //
// Get these values from https://console.developers.google.com
// Be sure to enable the Analytics API
// ******************************************************** //
$client_id = 'xxx.apps.googleusercontent.com';
$client_secret = 'xxxkQO8K';
$redirect_uri = 'xxx/GoogleCalendar/tests/MGC_NEW.php';
$client = new Google_Client();
$client->setApplicationName("primary");
$client->setClientId($client_id);
$client->setClientSecret($client_secret);
$client->setRedirectUri($redirect_uri);
$client->setAccessType('offline'); // Gets us our refreshtoken
$client->setScopes(array('https://www.googleapis.com/auth/calendar'));
//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='http://www.marchgolfclub.co.uk?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";
// get events
$events = $service->events->listEvents($calendarListEntry->id);
foreach ($events->getItems() as $event) {
/*Code to add holiday and Bank Holidays etc.*/
//echo "-----".$event->getSummary()."<br>";
}
}
$pageToken = $calendarList->getNextPageToken();
if ($pageToken) {
$optParams = array('pageToken' => $pageToken);
$calendarList = $service->calendarList- >listCalendarList($optParams);
} else {
break;
}
}
//THIS IS WHERE THE CODE BREAKS DOWN
echo "<hr><font size=+1>I have access to your calendar</font>";
$event = new Google_Service_Calendar_Event($client);
$event->setSummary(‘Interview’);
$event->setLocation(‘Hell’);
$start = new Google_Service_Calendar_EventDateTime();
$start->setDateTime(‘2015-10-03T10:00:00.000-07:00’);
$event->setStart($start);
$end = new Google_Service_Calendar_EventDateTime();
$end->setDateTime(‘2015-10-03T10:25:00.000-07:00′);
$event->setEnd($end);
$attendee1 = new Google_Service_Calendar_EventAttendee();
$attendee1->setEmail(’email#abc.com’);
// …
$attendees = array($attendee1);
$event->attendees = $attendees;
//$createdEvent = $service->events->insert(‘primary’, $event);
//Google code error was fixed
$createdEvent = $service->events->insert($calName, $event);
//echo $createdEvent->getId();
var_dump($createdEvent);
echo "<br><font size=+1>Event created</font>";
//END OF BROKEN CODE
}
?>`
Can anyone help?

(401) Unauthorized when trying to insert a moment using the Google+ API

Using code below I successfully received a token and using this token also get user detail, but when I try to post/insert moment in user wall I see the following error message
Fatal error: Uncaught exception 'Google_Service_Exception' with message 'Error calling POST https:--www.googleapis.com/plus/v1/people/me/moments/vault: (401) Unauthorized' in $_SESSION['access_token_gp']
I got user token when user login using my site in login page I ask for below permission
$client->addScope("email");
$client->addScope("https://www.googleapis.com/auth/plus.stream.write");
$client->addScope("https://www.googleapis.com/auth/plus.login");
If I print_r($tokenInfo); you will see all scope which I ask at login time.
The full code:
session_start();
require_once realpath(dirname(__FILE__) . '/google-api-php-client-master/autoload.php');
$client_id = 'my_client_id';
$client_secret = 'my_secret_key';
$redirect_uri = 'my_redirect_url';
// code to post in google plus start here //
$client = new Google_Client();
$client->setClientId($client_id);
$client->setClientSecret($client_secret);
$client->setRedirectUri($redirect_uri);
if (isset($_SESSION['access_token_gp'])) {
// Verify the token
$token = json_decode($_SESSION['access_token_gp']);
$reqUrl = 'https://www.googleapis.com/oauth2/v1/tokeninfo?access_token='.$token->access_token;
$req = new Google_Http_Request($reqUrl);
$tokenInfo = get_object_vars(json_decode($client->getAuth()->authenticatedRequest($req)->getResponseBody()));
if($tokenInfo['expires_in'] <= 0){
$client->authenticate($_SESSION['access_token_gp']);
$_SESSION['access_token_gp'] = $client->getAccessToken();
} else {
$client->setAccessToken($_SESSION['access_token_gp']);
}
$plusservicemoment = new Google_Service_Plus_Moment();
$plusservicemoment->setType("http://schemas.google.com/AddActivity");
$plusService = new Google_Service_Plus($client);
$item_scope = new Google_Service_Plus_ItemScope();
$item_scope->setId($tokenInfo['user_id']);
$item_scope->setType("http://schemas.google.com/AddActivity");
$item_scope->setName("The madexme Platform");
$item_scope->setDescription("A page that describes just how madexme is work!");
//$item_scope->setImage("full image path here");
$plusservicemoment->setTarget($item_scope);
$result = $plusService->moments->insert('me','vault',$plusservicemoment);
//print_r($result);
}
// code to post in google plus end here //
Make sure you have the latest client lib from GitHub. There is something wrong with your Oauth2 connection. This code is partially converted from my Google Google Calendar API tutorial. I don't have the power to test it right now. But this should be close. I will test it tonight.
<?php
require_once 'Google/Client.php';
require_once 'Google/Service/Plus.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/plus.login'));
//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_Plus($client);
$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);
?>
Again I hope you understand that this is not going to show up on the users Google+ page / timeline.

Get post from Google+ without browser's authentication in google's account via PHP

I'm want to get google+ posts via PHP, but google requires my login via browser.
It's possible provide the account's authentication via PHP, allowing me to get the posts without login every time I want to get the posts?
The code is:
<?php
require_once 'src/Google_Client.php';
require_once 'src/contrib/Google_PlusService.php';
session_start();
$client = new Google_Client();
$client->setApplicationName("Google+ PHP Starter Application");
// Visit https://code.google.com/apis/console?api=plus to generate your
// client id, client secret, and to register your redirect uri.
$client->setClientId('clientid');
$client->setClientSecret('clientsecret');
$client->setRedirectUri('http://localhost/OLA/google+/simple.php/b.html');
$client->setDeveloperKey('apikey');
$plus = new Google_PlusService($client);
if (isset($_GET['logout'])) {
unset($_SESSION['token']);
}
if (isset($_GET['code'])) { // login stuff <-------
if (strval($_SESSION['state']) !== strval($_GET['state'])) {
die("The session state did not match.");
}
$client->authenticate();
$_SESSION['token'] = $client->getAccessToken();
$redirect = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL));
}
if (isset($_SESSION['token'])) {
$client->setAccessToken($_SESSION['token']);
}
if ($client->getAccessToken()) {
//$me = $plus->people->get('me');
//print "Your Profile: <pre>" . print_r($me, true) . "</pre>";
$params = array('maxResults' => 100);
$activities = $plus->activities->listActivities('me', 'public', $params);
//print "Your Activities: <pre>" . print_r($activities, true) . "</pre>";
$params = array(
'orderBy' => 'recent',
'maxResults' => '20'//20
);
$q = "tag";
$results = $plus->activities->search($q, $params);
//code ....
// The access token may have been updated lazily.
$_SESSION['token'] = $client->getAccessToken();
} else {
// This is the part that logs me in via browser <------
$state = mt_rand();
$client->setState($state);
$_SESSION['state'] = $state;
$authUrl = $client->createAuthUrl();
print "<a class='login' href='$authUrl'>Connect Me!</a>";
}
?>
Yep, just call as you would and use the simple API access key - you can retrieve public information, but you will have to supply to long numeric ID for the user you're retrieving posts for rather than using the string 'me'. Take a look at the latest version of the library as well: https://github.com/google/google-api-php-client as well. You need to setup your client as you were doing, with an API key from a project which has the Google+ enabled on https://developers.google.com/console
$client = new Google_Client();
$client->setApplicationName("Post Fetcher");
$client->setDeveloperKey('PUT_YOUR_API_KEY_HERE_OR_IT_WONT_WORK');
$plus = new Google_Service_Plus($client);
$activities = $this->plus->activities
->listActivities("118051310819094153327", "public");

Create Simple Google Calendar Event in PHP

I'm having a heck of a time trying to get a very simple event added to a calendar using the Google Calendar API, and I would love it if someone could point out my (probably obvious) issue. I'm using code that I found here. I've put the code in the "google-api-php-client/examples.calendar" directory, where a simple example can be found.
<?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('worked.html'); //I made a file called "worked.html" in the same directory that just says "it worked!"
$client->setDeveloperKey('SecretLongDeveloperKey');
$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()){
$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('secretLongCalendarId#group.calendar.google.com', $event);
}
echo $createdEvent->getId();
?>
When I access this script, I get a 404 error. I've tried going through the code and commenting out lines in an attempt to find the culprit - it appears to be the second-to-last line, which actually inserts the event.
Any advice? I'd really appreciate some pointers, as I cannot seem to get even the simplest of examples to work.
Your code almost works.
However, you redirect to "worked.html". That way your event does not get created after the redirect of authentication. Also the setRedirectUri should match what you entered in Google API plus console (see "Redirect URIs") AND it should be THIS file because this file is entering the event after the redirect. (You don't need the "worked.html")
So your simple.php should look like this (ALSO change the "Redirect URIs" on Google Api to http://localhost/simple.php, you need to specify the domain but can use localhost, in setRedirectUri you can specify the same)
<?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://###/index.php');
$client->setDeveloperKey('###');
$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']);
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('Halloween');
$event->setLocation('The Neighbourhood');
$start = new Google_EventDateTime();
$start->setDateTime('2013-9-29T10:00:00.000-05:00');
$event->setStart($start);
$end = new Google_EventDateTime();
$end->setDateTime('2013-9-29T10:25:00.000-05:00');
$event->setEnd($end);
$createdEvent = $cal->events->insert('###', $event);
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>";
?>
Also, like #BigMacAttack already stated, you only need the
$authURL = $client->createAuthURL(); once, only if getAccessToken failed.
Happy Halloween ;-)
Edit: I cleaned up the code a lot with working links to login and logout and log-messages.
The last portion of your code isn't using correct logic. The crux of the problem is with if (!$client->getAccessToken()). This statement, in the context of your sample code, roughly translates to: If you fail to get the access token, create the event. Obviously this is not what you want to happen. ;)
Instead try this:
if ($client->getAccessToken()){
//succeeded in getting an access token, so create and insert the event
} else {
$authUrl = $client->createAuthUrl();
//failed to get an access token, so display $authurl as a link to open the auth window
}

Categories