簡體   English   中英

Google 日歷推送通知設置

[英]Google Calendar Push Notifications SetUp

我正在嘗試使用 PHP 和 V3 api 為 Google 日歷設置推送通知。

我已經獲得了 Auth2.0 權限,並且可以通過我的應用程序在 google 上創建事件。 現在我想知道用戶何時對谷歌日歷(CRUD 操作)進行任何更改。

這是我的代碼:

private $imageService;
public $google_client;
public $google_calendar;

public function __construct()
{
    $this->imageService = new ImageService();
    $this->google_client = new Google_Client();
    $this->google_client->setApplicationName($_ENV['GOOGLE_APP_NAME']);
    $this->google_client->setDeveloperKey($_ENV['GOOGLE_API_KEY']);
    $this->google_client->setClientId($_ENV['CLIENT_ID']);
    $this->google_client->setClientSecret($_ENV['CLIENT_SECRET']);
    $this->google_client->setAccessType('offline');
    $this->google_client->setIncludeGrantedScopes(true);
    $this->google_client->setScopes(array('email', 'profile', 'https://www.googleapis.com/auth/plus.me', 'https://www.googleapis.com/auth/calendar'));
    $this->google_calendar = new Google_Service_Calendar($this->google_client);

}

 public function googleCalendarWatch($uuid){

    $channel =  new Google_Service_Calendar_Channel($this->google_client);
    $channel->setId($uuid);
    $channel->setType('web_hook');
    $channel->setAddress("https://example.com/google/googleNotifications");
    $channel->setExpiration("1919995862000");
    $this->google_calendar->events->watch('primary', $channel);

}

這個輸出:

Google_Service_Calendar_Channel Object (
    [internal_gapi_mappings:protected] => Array ( ) 
    [address] => 
    [expiration] => 1426272395000 
    [id] => aee2b430-34bf-42bc-a597-ada46db42799 
    [kind] => api#channel 
    [params] => 
    [payload] => 
    [resourceId] => 51IKGpOwCJ6EMraQMUc1_04MODk 
    [resourceUri] => https://www.googleapis.com/calendar/v3/calendars/primary/events?key=AIzaSyBFUvq3OZO6ugAKvz7l8NgLS0V6DUJq8Vc&alt=json 
    [token] => 
    [type] => 
    [modelData:protected] => Array ( ) 
    [processed:protected] => Array ( ) )

到目前為止,我不知道為什么地址返回 null,也許這就是問題所在。 但我不知道如何修復它。

另請閱讀: #26730263並查看我自己的代碼,沒有太大區別。

我做了谷歌說的所有事情,注冊域,添加憑據,api 密鑰,允許推送域等等。

為每個單獨的資源創建一個通知渠道,然后對該資源的任何修改都會收到通知。 以下信息直接來自 Google(創建通知渠道)。

發出監視請求:

每個可觀看的 Google 日歷 API 資源在以下形式的 URI 處都有一個關聯的 watch 方法:

https://www.googleapis.com/**apiName**/**apiVersion**/**resourcePath**/watch

要為有關特定資源更改的消息設置通知通道,請向資源的 watch 方法發送 POST 請求。 每個通知通道都與特定用戶和特定資源(或資源集)相關聯。 除非當前用戶擁有或有權訪問此資源,否則監視請求不會成功。

例子:

開始觀察給定日歷上一系列事件的變化:

POST https://www.googleapis.com/calendar/v3/calendars/my_calendar@gmail.com/events/watch
Authorization: Bearer auth_token_for_current_user
Content-Type: application/json

{
  "id": "01234567-89ab-cdef-0123456789ab", // Your channel ID.
  "type": "web_hook",
  "address": "https://example.com/notifications", // Your receiving URL.
  ...
  "token": "target=myApp-myCalendarChannelDest", // (Optional) Your channel token.
  "expiration": 1426325213000 // (Optional) Your requested channel expiration time.
  }
}

參考: Google(創建通知渠道) (2018 年 3 月 19 日)。

  • 地址?
  • 令牌?
<?php
require __DIR__ . '/vendor/autoload.php';

if (php_sapi_name() != 'cli') {
    throw new Exception('This application must be run on the command line.');
}

/**
 * Returns an authorized API client.
 * @return Google_Client the authorized client object
 */
function getClient()
{
    $client = new Google_Client();
    $client->setApplicationName('Google Calendar API PHP Quickstart');
    $client->setScopes(Google_Service_Calendar::CALENDAR_READONLY);
    $client->setAuthConfig('credentials.json');
    $client->setAccessType('offline');
    $client->setPrompt('select_account consent');

    // Load previously authorized token from a file, if it exists.
    // The file token.json stores the user's access and refresh tokens, and is
    // created automatically when the authorization flow completes for the first
    // time.
    $tokenPath = 'token.json';
    if (file_exists($tokenPath)) {
        $accessToken = json_decode(file_get_contents($tokenPath), true);
        $client->setAccessToken($accessToken);
    }

    // If there is no previous token or it's expired.
    if ($client->isAccessTokenExpired()) {
        // Refresh the token if possible, else fetch a new one.
        if ($client->getRefreshToken()) {
            $client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
        } 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);
            $client->setAccessToken($accessToken);

            // Check to see if there was an error.
            if (array_key_exists('error', $accessToken)) {
                throw new Exception(join(', ', $accessToken));
            }
        }
        // Save the token to a file.
        if (!file_exists(dirname($tokenPath))) {
            mkdir(dirname($tokenPath), 0700, true);
        }
        file_put_contents($tokenPath, 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);
$events = $results->getItems();

if (empty($events)) {
    print "No upcoming events found.\n";
} else {
    print "Upcoming events:\n";
    foreach ($events 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