Как изменить событие в API Календаря Google с сервером - PullRequest
0 голосов
/ 27 сентября 2018

У меня работает oauth2 - когда пользователь входит в мое приложение, он должен войти в свою учетную запись Google.Затем они могут вручную синхронизировать все события из календаря моего веб-сайта с их Календарем Google.

НО, как я могу сделать так, чтобы мой сервер мог изменять свои события Календаря Google (добавлять, редактировать, удалять)без их фактического присутствия на компьютере?Потому что сейчас он использует $_SESSION, чтобы проверить, вошел ли пользователь в свою учетную запись Google.

Например, вот как вставить / добавить событие через API в Календарь Google:

$client = new Google_Client();
$client->setAuthConfig('client_secrets.json');
$client->addScope(Google_Service_Calendar::CALENDAR);
$client->setAccessType("offline");
$service = new Google_Service_Calendar($client);

if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {

    $event = new Google_Service_Calendar_Event(array(
      'summary' => 'Google I/O 2015',
      'location' => '800 Howard St., San Francisco, CA 94103',
      'description' => 'A chance to hear more about Google\'s developer products.',
      'start' => array(
        'dateTime' => '2015-05-28T09:00:00-07:00',
        'timeZone' => 'America/Los_Angeles',
      ),
      'end' => array(
        'dateTime' => '2015-05-28T17:00:00-07:00',
        'timeZone' => 'America/Los_Angeles',
      ),
    ));

    $event = $service->events->insert('primary', $event);
} else {
    $redirect_uri = '/oauth.php';
    header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
    exit();
}

Но, как вы можете видеть, для этого требуется access_token, который хранится в $_SESSION, и если токена доступа нет, он перенаправит их для входа в свою учетную запись Google.

Как можномой сервер зайти в свою учетную запись Календаря Google в background и добавить / изменить / удалить события?

1 Ответ

0 голосов
/ 13 ноября 2018

Вы должны создать «приложение» на console.developers.google.com и создать для него «учетные данные авторизации».Вы получите файл json, который вам нужно использовать для аутентификации

Подробнее читайте здесь https://developers.google.com/api-client-library/php/auth/web-app#creatingcred

Вы можете использовать это https://github.com/googleapis/google-api-php-client

Так что редактирование будет выглядетькак

include_once 'google.api.php';

$eventId = '010101010101010101010101'; 
$calendarID='xyxyxyxyxyxyxyxyxy@group.calendar.google.com';

// Get Event for edit 
$event = $service->events->get($calendarID, $eventId);    

$event->setSummary('New title');
$event->setDescription('New describtion');

$event->setStart(
new Google_Service_Calendar_EventDateTime(['dateTime' => date("c", strtotime("2018-09-20 09:40:00")),'timeZone' => 'Europe/Moscow'])
);

$event->setEnd(
new Google_Service_Calendar_EventDateTime(['dateTime' => date("c", strtotime("2018-09-20 10:40:00")),'timeZone' => 'Europe/Moscow'])
);

$updatedEvent = $service->events->update($calendarID, $eventId, $event);

Где google.api.php будет выглядеть примерно так

 require_once __DIR__ .'/vendor/autoload.php';
 function getClient()
 {
$client = new Google_Client();
$client->setApplicationName('Google Calendar API PHP Quickstart');
$client->setScopes(Google_Service_Calendar::CALENDAR);
$client->setAuthConfig('credentials.json');
$client->setAccessType('offline');

// Load previously authorized credentials from a file.
$credentialsPath = 'token.json';
if (file_exists($credentialsPath)) {
    $accessToken = json_decode(file_get_contents($credentialsPath), true);
} else {
    // Request authorization from the user.
    $authUrl = $client->createAuthUrl();
    printf("Open the following link in your browser:\n%s\n", $authUrl);
    print 'Enter verification code: ';
    $authCode = trim(fgets(STDIN));

    // Exchange authorization code for an access token.
    $accessToken = $client->fetchAccessTokenWithAuthCode($authCode);

    // Store the credentials to disk.
    if (!file_exists(dirname($credentialsPath))) {
        mkdir(dirname($credentialsPath), 0700, true);
    }
    file_put_contents($credentialsPath, json_encode($accessToken));
    printf("Credentials saved to %s\n", $credentialsPath);
}
$client->setAccessToken($accessToken);

// Refresh the token if it's expired.
if ($client->isAccessTokenExpired()) {
    $client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
    file_put_contents($credentialsPath, json_encode($client->getAccessToken()));
}
return $client;
 }


 // Get the API client and construct the service object.
 $client = getClient();
 $service = new Google_Service_Calendar($client);

 // Print the next 10 events on the user's calendar.
 $calendarId = 'primary';
 $optParams = array(
'maxResults' => 10,
'orderBy' => 'startTime',
'singleEvents' => true,
'timeMin' => date('c'),
 );
 $results = $service->events->listEvents($calendarId, $optParams);

 if (empty($results->getItems())) {
   print "No upcoming events found.\n";
 } else {
   print "Upcoming events:\n";
   foreach ($results->getItems() as $event) {
     $start = $event->start->dateTime;
     if (empty($start)) {
        $start = $event->start->date;
     }
     printf("%s (%s)\n", $event->getSummary(), $start);
   }
 }
...