使用 PHP 的 Gmail 推送通知

Gmail Push Notification using PHP

阅读 Gmail API 文档,我注意到 Gmail API provides a way to push notification 到后端端点 URL。这个想法是当用户收到一封新电子邮件时在我们的后端调用 process() (避免拉取方法)。

我创建了一个新订阅 (Cloud Pub/Sub API) 并测试了从云平台控制台发布一条新消息。 API 按预期工作。但是现在,我不知道如何通知Gmail API 开始监视用户INBOX 的变化。我们可以在Python中使用watch()stop(),但是PHP呢?

Google 发现服务 API 是简单的休息 API。您可以将它们与任何能够执行 HTTP Post 和 HTTP Get 的语言一起使用。

Google 非常善于简化开发人员的工作,因此他们创建了许多开源客户端库来帮助开发人员。 Google APIs PHP Client library 就是这样一个库。它为您处理大部分艰苦的工作。

在您的身份验证流程正常运行后,我会查看 PHP Quickstart tutorial first then move on to User.watch

使用 HTTP 的代码示例 POST:

// Google API
$client = getClient();

// Variables
$user = 'me';
$access_token = $client->getAccessToken()['access_token'];
$topic_name = 'projects/xxxx/topics/xxxx';

// POST request    
$ch = curl_init('https://www.googleapis.com/gmail/v1/users/' . $user . '/watch');

curl_setopt_array($ch, array(
    CURLOPT_POST => TRUE,
    CURLOPT_RETURNTRANSFER => TRUE,
    CURLOPT_HTTPHEADER => array(
        'Authorization: Bearer ' . $access_token,
        'Content-Type: application/json'
    ),
    CURLOPT_POSTFIELDS => json_encode(array(
        'topicName' => $topic_name,
        'labelIds' => ["INBOX"]
    ))
));

to grant publish privilegesserviceAccount:gmail-api-push@system.gserviceaccount.com 是必需的。