【问题标题】:How to modify event on Google Calendar API with server如何使用服务器修改 Google Calendar API 上的事件
【发布时间】:2018-09-27 14:30:01
【问题描述】:

我让 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 日历帐户并添加/编辑/删除活动?

【问题讨论】:

    标签: php google-api synchronization google-calendar-api


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-03-23
      • 2023-03-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多