我正在使用 node.js 创建一个应用程序,该应用程序在每次收到电子邮件时从 Gmail 获取推送,将其与 CRM 中的第三方数据库进行检查,并在电子邮件中创建一个新字段包含在那里。我在使用 Google 的新 Cloud Pub/Sub 时遇到了问题,这似乎是无需持续轮询即可从 Gmail 获取推送的唯一方法。
我已经阅读了这里的说明:https://cloud.google.com/pubsub/prereqs但我不明白这应该如何从我桌面上的应用程序中工作。似乎 pub/sub 可以连接到经过验证的域,但我无法让它直接连接到我计算机上的 .js 脚本。我已将 api key 保存在 json 文件中并使用以下内容:
var gcloud = require('gcloud');
var pubsub;
// From Google Compute Engine:
pubsub = gcloud.pubsub({
projectId: 'my-project',
});
// Or from elsewhere:
pubsub = gcloud.pubsub({
projectId: 'my-project',
keyFilename: '/path/to/keyfile.json'
});
// Create a new topic.
pubsub.createTopic('my-new-topic', function(err, topic) {});
// Reference an existing topic.
var topic = pubsub.topic('my-existing-topic');
// Publish a message to the topic.
topic.publish('New message!', function(err) {});
// Subscribe to the topic.
topic.subscribe('new-subscription', function(err, subscription) {
// Register listeners to start pulling for messages.
function onError(err) {}
function onMessage(message) {}
subscription.on('error', onError);
subscription.on('message', onMessage);
// Remove listeners to stop pulling for messages.
subscription.removeListener('message', onMessage);
subscription.removeListener('error', onError);
});
但是,我收到错误,好像它没有连接到服务器,在 API 列表中我只看到错误,没有实际成功。我显然做错了什么,知道可能是什么吗?
提前谢谢你!
最佳答案
TL;DR
您无法从客户端订阅推送通知。
Set up an HTTPS server to handle the messages. Messages will be sent to the URL endpoint that you configure, representing that server's location. Your server must be reachable via a DNS name and must present a signed SSL certificate. (App Engine applications are preconfigured with SSL certificates.)
只需订阅您服务器上的推送通知,当您收到通知时,您就可以知道它关注的是谁。您将从通知中获得的数据是它所关注的用户以及相关的 historyId,如下所示:
// This is all the data the notifications will give you.
{"emailAddress": "user@example.com", "historyId": "9876543210"}
然后你可以例如通过 Socket.io 发出事件如果相关用户在线,则发送给相关用户,并让他与客户端提供的 historyId 进行同步。
关于node.js - Google Cloud Pub/Sub API - 推送电子邮件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31599021/