Создание простого события календаря Google в PHP

У меня есть чертовски время, пытаясь получить очень простое событие, добавленное в календарь с помощью Google Calendar API, и мне было бы очень приятно, если бы кто-нибудь мог указать на мою (возможно, очевидную) проблему. Я использую код, который я нашел здесь . Я поместил код в каталог google-api-php-client / examples.calendar, где можно найти простой пример.

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

Когда я получаю доступ к этому скрипту, я получаю ошибку 404. Я попытался пройти через код и прокомментировать строки, пытаясь найти виновника – это, как представляется, вторая по последней строке, которая фактически вставляет событие.

Любой совет? Я бы очень признателен за некоторые указатели, поскольку, по-видимому, я не могу получить даже самые простые примеры для работы.

Related of "Создание простого события календаря Google в PHP"

Ваш код почти работает.

Однако вы перенаправляетесь на «work.html». Таким образом, ваше событие не создается после перенаправления проверки подлинности. Также setRedirectUri должен соответствовать тому, что вы ввели в Google API плюс консоль (см. «Перенаправление URI») И это должен быть ЭТО файл, потому что этот файл вводит событие после перенаправления. (Вам не нужен «work.html»)

Итак, ваш simple.php должен выглядеть так (ТАКЖЕ изменить «URI перенаправления» на Google Api на http://localhost/simple.php , вам нужно указать домен, но можете использовать localhost, в setRedirectUri вы можете указать то же самое)

 <?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>"; ?> с <?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>"; ?> 

Кроме того, как уже говорилось в @BigMacAttack, вам нужно только
$authURL = $client->createAuthURL(); один раз, только если getAccessToken не удалось.

Счастливого Хэллоуина 😉

Редактирование : я много очистил код с помощью рабочих ссылок для входа и выхода из системы и сообщений журнала.

Последняя часть вашего кода не использует правильную логику. Суть проблемы заключается в if (!$client->getAccessToken()) . Этот оператор в контексте вашего примерного кода примерно переводится на: Если вам не удалось получить токен доступа, создайте событие. Очевидно, это не то, что вы хотите. 😉

Вместо этого попробуйте следующее:

 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 }