我如何使用node.js在Firebase云Firestore中添加sendgrid webhook事件Json响应

问题描述 投票:0回答:1

我不知道如何实现该功能,但在此之前,我已经完成了SendGrid的一部分,即在其中创建任何文档,然后它将电子邮件发送给用户。但是我要问的是我不知道如何进行。这是该实现的第一部分,其中任何集合(如果创建了新记录)都会将电子邮件发送到特定电子邮件,并且有一个名为“事件对象I”的响应。想写一个云函数来存储数据。而且我不知道如何启动此功能或解决此问题。

"use strict";
const functions = require("firebase-functions");
const admin = require("firebase-admin");

var serviceAccount1 = require("./key.json");

const newProject = admin.initializeApp({
  credential: admin.credential.cert(serviceAccount1),
  databaseURL: "xyz"
});
const sgMail = require("@sendgrid/mail");
const sgMailKey = "key";
sgMail.setApiKey(sgMailKey);


 exports.sentMail = functions.firestore
  .document("/Offices/{officeId}")
  .onCreate((documentSnapshot,event) => {
    const documentData = documentSnapshot.data()
    const officeID = event.params.officeId;
    console.log(JSON.stringify(event))
    const db = newProject.firestore();
    return db.collection("Offices").doc(officeID).get()
      .then(doc => {
        const data = doc.data();
        const msg = {
          to: "[email protected]",
          from: "[email protected]",
          text: "hello from this side",
          templateId: "d-8ecfa59aa9d2434eb8b7d47d58b4f2cf",
          substitutionWrappers: ["{{", "}}"],
          substitutions: {
            name: data.name
          }
        };
        return sgMail.send(msg);
      })
      .then(() => console.log("payment mail sent success"))
      .catch(err => console.log(err));
  });

和我的问题的预期输出就像一个集合名称XYZ,其中一个对象有三个字段,如

{email:"[email protected]",
event:"processed",
timestamp:123555558855},
{email:"[email protected]",
event:"recieved",
timestamp:123555558855},
{email:"[email protected]",
event:"open",
timestamp:123555558855}
node.js firebase google-cloud-firestore google-cloud-functions sendgrid
1个回答
1
投票

您将在Sendgrid documentation中阅读:

SendGrid的事件Webhook将通过HTTP通知您选择的URLPOST包含有关作为SendGrid进程发生的事件的信息您的电子邮件

要在Firebase项目中实现HTTP终结点,您将实现一个HTTPS Cloud Function,Sendgrid Webhook会通过HTTPS POST请求调用此event

每个来自Sendgrid Webhook的呼叫都将涉及一个特定的processed,并且您将能够在Cloud Function中获取事件的值(deliveredcustom arguments等。]。>>

现在,您需要在Cloud Function中将特定事件与以前通过Cloud Function发送的特定电子邮件相关联。为此,您应该使用msg

更确切地说,您将向您的send()对象添加(传递给event.params.officeId方法的唯一标识符)。经典值是Firestore文档ID,例如officeId,但可以是您在Cloud Function中生成的任何其他唯一ID。


实施示例

在发送电子邮件的Cloud Function中,在custom_args对象中传递 exports.sentMail = functions.firestore .document("/Offices/{officeId}") .onCreate((documentSnapshot,event) => { const documentData = documentSnapshot.data(); const officeId = event.params.officeId; const msg = { to: "[email protected]", from: "[email protected]", text: "hello from this side", templateId: "d-8ecfa59aa9d2434eb8b7d47d58b4f2cf", substitutionWrappers: ["{{", "}}"], substitutions: { name: documentData.name }, custom_args: { "officeId": officeId } }; return sgMail.send(msg) .then(() => { console.log("payment mail sent success")); return null; }) .catch(err => { console.log(err) return null; }); }); ,如下所示:

documentSnapshot.data()

请注意,您通过HTTPS Cloud Function获取了新创建的文档(触发Cloud Function的数据:您无需在Cloud Function中查询同一文档。


然后,创建一个简单的exports.sendgridWebhook = functions.https.onRequest((req, res) => { const body = req.body; //body is an array of JavaScript objects const promises = []; body.forEach(elem => { const event = elem.event; const eventTimestamp = elem.timestamp; const officeId = elem.officeId; const updateObj = {}; updateObj[event] = true; updateObj[event + 'Timestamp'] = eventTimestamp; promises.push(admin.firestore().collection('Offices').doc(officeId).update(updateObj)); }); return Promise.all(promises) .then(() => { return res.status(200).end(); }) ,如下:

https://us-central1-<your-project-id>.cloudfunctions.net/sendgridWebhook

})

如终端所示部署它并获取其URL:应该像admin.firestore().collection('Offices')...

注意,这里我使用const db = newProject.firestore(); ... db.collection('Offices')...。您可以使用Promise.all()

[还要注意,Sendgrid Webhook发送的HTTPS POST请求的主体包含一个JavaScript对象数组,因此我们将使用Promise.all()处理这些不同的对象,即,使用officeId将不同的事件写入Firestore文档。

然后,您需要在Sendgrid平台的“邮件设置/事件通知”部分中设置Webhook,如doc中所述,如下所示。

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.