douhuan1497 2018-09-27 14:30
浏览 120

如何使用服务器修改Google Calendar API上的活动

I got oauth2 working - when a user logs into my application, they have to log into their Google account. Then they can make manually sync all events from my website's calendar to their Google Calendar.

BUT, how can I make it so that my server will be able to modify their Google Calendar (add, edit, delete) events without them actually being present at the computer? Because right now, it uses $_SESSION to check if the user is logged into their Google account.

For example, here is how to insert/add an event via API into Google Calendar:

$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();
}

But as you can see, that requires an access_token which is stored in $_SESSION, and if there is no access token, then it will redirect them to login into their Google Account.

How can my server access their Google Calendar account in the background and add/edit/remove events?

  • 写回答

1条回答 默认 最新

  • dou1908 2018-11-13 14:11
    关注

    You must create "application" in console.developers.google.com and create "authorization credentials" for it. You will get a json file which you need to use for auth

    Read here for more detail https://developers.google.com/api-client-library/php/auth/web-app#creatingcred

    You can use this https://github.com/googleapis/google-api-php-client

    So edit will look like

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

    Where google.api.php will be something like this

     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:
    %s
    ", $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
    ", $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.
    ";
     } else {
       print "Upcoming events:
    ";
       foreach ($results->getItems() as $event) {
         $start = $event->start->dateTime;
         if (empty($start)) {
            $start = $event->start->date;
         }
         printf("%s (%s)
    ", $event->getSummary(), $start);
       }
     }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大
  • ¥15 Oracle中如何从clob类型截取特定字符串后面的字符
  • ¥15 想通过pywinauto自动电机应用程序按钮,但是找不到应用程序按钮信息
  • ¥15 如何在炒股软件中,爬到我想看的日k线
  • ¥15 seatunnel 怎么配置Elasticsearch
  • ¥15 PSCAD安装问题 ERROR: Visual Studio 2013, 2015, 2017 or 2019 is not found in the system.
  • ¥15 (标签-MATLAB|关键词-多址)
  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端