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?
Related
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>";
At the very first time,I'm trying to get my google account profile picture by using google api. So I have referred Refer this site.
so in my google-plus-access.php:
<?php
require_once 'google-api-php-client-master/src/Google/autoload.php'; // or wherever autoload.php is located
session_start();
$client = new Google_Client();
$client->setApplicationName("Google+ PHP Starter Application");
$client->setClientId('MY_CLIENT_ID');
$client->setClientSecret('MY_SECRET_KEY');
$client->setRedirectUri('http://localhost/G-api');
$client->setDeveloperKey('MY_DEV_KEY');
$client->setScopes(array('https://www.googleapis.com/auth/plus.me'));
//$plus = new apiPlusService($client);
$plus = $client -> createAuthUrl();
if(isset($_REQUEST['logout']))
{
unset($_SESSION['access_token']);
}
if(isset($_GET['code']))
{
echo $_GET['code'];
$client->authenticate();
$_SESSION['access_token'] = $client->getAccessToken();
header('Location: http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF']);
}
if(isset($_SESSION['access_token']))
{
echo $_SESSION['access_token'];
$client->setAccessToken($_SESSION['access_token']);
}
if ($client->getAccessToken()) {
$me = $plus->people->get('me');
echo $me;
$optParams = array('maxResults' => 100);
$activities = $plus->activities->listActivities('me', 'public', $optParams);
$_SESSION['access_token'] = $client->getAccessToken();
} else {
$authUrl = $client->createAuthUrl();
echo '<pre>';
print_r($authUrl); // this block is running!!!
echo '</pre>';
}
echo "</br>";
?>
And in my index.php:
<?php
include('google-plus-access.php');
?>
<img src="<?php echo(substr($me['image']['url'],0,stripos($me['image']['url'],'?sz='))); ?>?sz=200" />
but i'm getting the result as:
https://accounts.google.com/o/oauth2/auth?response_type=code&redirect_uri=http%3A%2F%2Flocalhost%2FG-api&client_id=887633147241-8ragvhdi97lga3n829qogpl5aoima7l5.apps.googleusercontent.com&scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fplus.me&access_type=online&approval_prompt=auto
In my console I'm getting the below error:
My output scree is looking like this :
EDIT:
In my console i'm getting GET http://localhost/G-api/%3Cbr%20/%3E%3Cb%3ENotice%3C/b%3E:%20%20Undefined%20…/G-api/index.php%3C/b%3E%20on%20line%20%3Cb%3E7%3C/b%3E%3Cbr%20/%3E?sz=200 403 (Forbidden) this.
These things are done in local.So some body making me scared that we can't do this is local and we have create domain for that.So kindly help me to do this.
Check your code $me is created in the if // this block is running!!!
is in the else.
You are trying to use $me which hasn't been created.
if ($client->getAccessToken()) {
$me = $plus->people->get('me'); //Daimto: This doesn't run so you cant use it
echo $me;
$optParams = array('maxResults' => 100);
$activities = $plus->activities->listActivities('me', 'public', $optParams);
$_SESSION['access_token'] = $client->getAccessToken();
} else {
$authUrl = $client->createAuthUrl();
echo '<pre>';
print_r($authUrl); // this block is running!!!
echo '</pre>';
}
You also need to create a service, $plus->people->get('me'); isn't going to work because $plus isn't a Google_Service_Plus. You should check out the example found here user-sample.php
$googlePlus = new Google_Service_Plus($client);
$userProfile = $googlePlus->people->get('me');
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();
}
?>
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
}
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.