使用PHP实现Gmail推送通知

4
阅读Gmail API文档,我注意到Gmail API提供了一种推送通知的方式,可以将其推送到后端终端URL。这个想法是在用户收到新邮件时调用我们的后端中的process()方法(避免拉取的方法)。
我创建了一个新的订阅(Cloud Pub/Sub API)并且测试了从Cloud Platform Console发布新消息。API像预期的那样工作。但现在,我不知道如何通知Gmail API开始监视用户的收件箱的变化。我们可以在Python中使用watch()stop(),但PHP怎么办?

enter image description here

2个回答

2
Google发现服务API是简单的REST API。你可以在任何能够执行HTTP POST和HTTP Get的语言中使用它们。
Google非常擅长为开发者提供便利,因此他们创建了许多开源客户端库来帮助开发者。其中一个就是Google APIs PHP Client library,它可以为你处理大部分繁重的工作。
我建议你先查看PHP Quickstart教程,然后在验证流程正常运作后再转到User.watch

0

使用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"]
    ))
));

需要授予发布权限serviceAccount:gmail-api-push@system.gserviceaccount.com

enter image description here


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接