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
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)
";
echo "";
print_r($_SESSION);
echo "
";
}
$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 "
Logging out";
unset($_SESSION['token']);
}
if (isset($_GET['code'])) {
echo "
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 "
I got the token = ".$_SESSION['token']; // <-- not needed to get here unless location uncommented
}
if (isset($_SESSION['token'])) {
echo "
Getting access";
$client->setAccessToken($_SESSION['token']);
}
if ($client->getAccessToken()){
echo "
I have access to your calendar";
$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 "
Event created";
echo "
Already connected (No need to login)";
} else {
$authUrl = $client->createAuthUrl();
print "
Connect Me!";
}
$url = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
echo "
Logout";
?>
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.