简体   繁体   English

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

[英]how can i add the sendgrid webhook event Json response in a firebase cloud firestore using node.js

I have no idea how to implement this thing but before that, I have done a part of SendGrid where any document is created then it will send the email to the user.我不知道如何实现这个东西,但在此之前,我已经完成了 SendGrid 的一部分,其中创建了任何文档,然后它将电子邮件发送给用户。 but this part what I am asking I has no idea how to proceed.this is my first part of this implementation wherein any collection if a new record is created then it will send email to the particular email and there is a response called event Object I want to write a cloud function to store the data.但这部分我要问的是我不知道如何继续。这是我这个实现的第一部分,其中如果创建了新记录,则任何集合都会向特定电子邮件发送电子邮件,并且有一个名为事件对象 I 的响应想写一个云函数来存储数据。 and I don't know how to start this function or proceed with this problem.我不知道如何启动此功能或继续解决此问题。

"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: "amarjeetkumars34@gmail.com",
          from: "singhamarjeet045@gmail.com",
          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));
  });

and the expected output of my question be like a collection name XYZ wherein an object there are three fields like我的问题的预期输出就像一个集合名称 XYZ,其中一个对象有三个字段,例如

{email:"xyz@gmail.com",
event:"processed",
timestamp:123555558855},
{email:"xyz@gmail.com",
event:"recieved",
timestamp:123555558855},
{email:"xyz@gmail.com",
event:"open",
timestamp:123555558855}

As you will read in the Sendgrid documentation :正如您将在Sendgrid 文档中读到的:

SendGrid's Event Webhook will notify a URL of your choice via HTTP POST with information about events that occur as SendGrid processes your email SendGrid 的事件 Webhook 将通过 HTTP POST 通知您选择的 URL,其中包含有关在 SendGrid 处理您的电子邮件时发生的事件的信息

To implement the HTTP endpoint in your Firebase Project, you will implement an HTTPS Cloud Function that will be called by the Sendgrid webhook through an HTTPS POST request.要在 Firebase 项目中实现 HTTP 端点,您将实现一个HTTPS 云函数,该函数将由 Sendgrid Webhook 通过 HTTPS POST 请求调用。

Each call from the Sendgrid webhook will concern a specificevent and you will be able, in your Cloud Function, to get the value of the event ( processed , delivered , etc...).来自 Sendgrid webhook 的每个调用都将涉及一个特定的事件,您将能够在您的云函数中获取事件的值(已processed 、已delivered等...)。

Now, you need in your Cloud Function to be able to link a specific event with a specific email that was previously sent through your Cloud Function.现在,您需要在您的 Cloud Function 中将特定事件与之前通过您的 Cloud Function 发送的特定电子邮件相关联。 For that you should use custom arguments .为此,您应该使用自定义参数

More precisely, you would add to your msg object (that you pass to the send() method) a unique identifier.更准确地说,您将向您的msg对象(您传递给send()方法)添加一个唯一标识符。 A classical value is a Firestore document ID, like event.params.officeId but could be any other unique ID that you generate in you Cloud Function.经典值是 Firestore 文档 ID,例如event.params.officeId但可以是您在 Cloud Function 中生成的任何其他唯一 ID。


Example of implementation实施例

In your Cloud Function that sends the email, pass the officeId in a custom_args object, as shown below:在发送电子邮件的云功能,通过officeIdcustom_args对象,如下图所示:

 exports.sentMail = functions.firestore
  .document("/Offices/{officeId}")
  .onCreate((documentSnapshot,event) => {

    const documentData = documentSnapshot.data();

    const officeId = event.params.officeId;

    const msg = {
          to: "amarjeetkumars34@gmail.com",
          from: "singhamarjeet045@gmail.com",
          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;
      });
  });

Note that you get the data of the newly created document (the one which triggers the Cloud Function) through documentSnapshot.data() : you don't need to query for the same document in your Cloud Function.请注意,您通过documentSnapshot.data()获取新创建的文档(触发 Cloud Function 的documentSnapshot.data() :您不需要在 Cloud Function 中查询相同的文档。


Then, create a simple HTTPS Cloud Function , as follows:然后,创建一个简单的HTTPS 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();
        })

})

Deploy it and grab its URL as shown in the terminal: it should be like https://us-central1-<your-project-id>.cloudfunctions.net/sendgridWebhook .部署它并获取它在终端中显示的 URL:它应该像https://us-central1-<your-project-id>.cloudfunctions.net/sendgridWebhook

Note that here I use admin.firestore().collection('Offices')... .请注意,这里我使用admin.firestore().collection('Offices')... You may use const db = newProject.firestore(); ... db.collection('Offices')...您可以使用const db = newProject.firestore(); ... db.collection('Offices')... const db = newProject.firestore(); ... db.collection('Offices')...

Also note that the body of the HTTPS POST request sent by the Sendgrid webhook contains an array of JavaScript objects, therefore we will use Promise.all() to treat these different objects, ie write to the Firestore document with officeId the different events.还要注意,Sendgrid webhook 发送的 HTTPS POST 请求的主体包含一个 JavaScript 对象数组,因此我们将使用Promise.all()来处理这些不同的对象,即使用officeId将不同的事件写入 Firestore 文档。

Then you need to set-up the Webhook in the Sendgrid platform, in the "Mail Settings/Event Notification" section, as explained in the doc and as shown below.然后,您需要在 Sendgrid 平台中的“邮件设置/事件通知”部分中设置 Webhook,如文档中所述,如下所示。

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在Cloud Functions for Firebase项目中使用sinon在node.js中存根构造函数? - How can I stub a constructor in node.js using sinon in a Cloud Functions for Firebase project? 如何使用firestore在node.js中获取谷歌云函数执行事件 - How to get Google cloud function execution event in node.js using firestore 使用官方的Node.js SendGrid API发送电子邮件时,响应JSON中可能出现哪些错误消息? - What are the possible error messages in the response JSON when sending email using the official Node.js SendGrid API? 如何使用node.js在JSON中向数组添加字符串? - How can I add strings to an array in a JSON using node.js? 使用节点 js 将 JSON 写入云 Firestore - Write JSON into cloud firestore using node js Node.JS Firebase 云 Function - HTTP 请求 - 返回 Z0ECD11C1D7A287401D148A2F3 响应客户端 - Node.JS Firebase Cloud Function - HTTP Request - Return JSON response to client 如何使用 Sendgrid 和 Node.js 发送本地主机链接 - How to send localhost link using Sendgrid and Node.js 如何在 node.js 中运行 d3-cloud - How can I run d3-cloud in node.js 无法从 API 响应中提取 JSON - Google Cloud Vision API(Node.js 库) - Can't extract JSON from API response - Google Cloud Vision API (Node.js library) Node.js使用sendgrid发送模板 - Node.js using sendgrid to send template
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM