我想为Google Calendar API设置推送通知,每当Google Calendar API上的特定资源发生变化时,我的服务器就会收到通知。我想使用PHP的Google API客户端库来执行此操作。
但似乎他们没有方法在PHP库中查看Google日历资源。也许其他库也有一种watch
方法,但是我对此不太确定。
基本上,要为特定资源设置推送通知,您必须将发布请求发送到这样的URL ...
POST https://www.googleapis.com/calendar/v3/calendars/[email protected]/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://mydomain.com/notifications" // Your receiving URL.
}
我可以使用PHP中的curl轻松地做到这一点,但是我的问题是该请求未获得Google OAuth令牌的授权,因此会导致错误。
我想知道是否有解决此问题的方法。
更新
我试图在不添加适当标题的情况下将连接发送给Google,因此出现授权错误。更正了该部分后,我仍然遇到Invalid Credentials
错误。这是我的片段的样子...
$url = sprintf("https://www.googleapis.com/calendar/v3/calendars/%s/events/watch", $calendar);
/* setup the POST parameters */
$fields = array(
'id' => "some_unique_key",
'type' => "web_hook",
'address' => sprintf("http://%s//event_status/update_google_events", $_SERVER['SERVER_NAME'])
);
/* convert the POST parameters to URL query */
$fields_string = '';
foreach ($fields as $key => $value) {
$fields_string .= sprintf("%s=%s&", $key, $value);
}
rtrim($fields_string, '&');
/* setup POST headers */
$headers[] = 'Content-Type: application/json';
$headers[] = 'Authorization: OAuth ' . $access_token;
/* send POST request */
$channel = curl_init();
curl_setopt($channel, CURLOPT_HTTPHEADER, $headers);
curl_setopt($channel, CURLOPT_URL, $url);
curl_setopt($channel, CURLOPT_RETURNTRANSFER, true);
curl_setopt($channel, CURLOPT_POST, true);
curl_setopt($channel, CURLOPT_POSTFIELDS, $fields_string);
curl_setopt($channel, CURLOPT_CONNECTTIMEOUT, 2);
curl_setopt($channel, CURLOPT_TIMEOUT, 3);
$response = curl_exec($channel);
curl_close($channel);
error_log($response);
这是我解决问题的方法。我在Google游乐场闲逛了一下,以弄清自己在做错什么。
我所做的就是
Authorization
POST请求的部分从OAUth {access_token}
Bearer {access_token}
更改为。基本上只是遵循Google的文档来设置推送通知。
$url = sprintf("https://www.googleapis.com/calendar/v3/calendars/%s/events/watch", $calendar);
/* setup the POST parameters */
$fields = json_encode(array(
'id' => "some_unique_key",
'type' => "web_hook",
'address' => sprintf("http://%s//event_status/update_google_events", $_SERVER['SERVER_NAME'])
));
/* setup POST headers */
$headers[] = 'Content-Type: application/json';
$headers[] = 'Authorization: Bearer ' . $access_token;
/* send POST request */
$channel = curl_init();
curl_setopt($channel, CURLOPT_HTTPHEADER, $headers);
curl_setopt($channel, CURLOPT_URL, $url);
curl_setopt($channel, CURLOPT_RETURNTRANSFER, true);
curl_setopt($channel, CURLOPT_POST, true);
curl_setopt($channel, CURLOPT_POSTFIELDS, $fields);
curl_setopt($channel, CURLOPT_CONNECTTIMEOUT, 2);
curl_setopt($channel, CURLOPT_TIMEOUT, 3);
$response = curl_exec($channel);
curl_close($channel);
error_log($response);
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句