簡體   English   中英

如何使用服務器修改Google Calendar API上的事件

[英]How to modify event on Google Calendar API with server

我可以使用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日歷帳戶並添加/編輯/刪除事件?

您必須在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);
   }
 }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM