簡體   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

我不知道如何實現這個東西,但在此之前,我已經完成了 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: "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));
  });

我的問題的預期輸出就像一個集合名稱 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}

正如您將在Sendgrid 文檔中讀到的:

SendGrid 的事件 Webhook 將通過 HTTP POST 通知您選擇的 URL,其中包含有關在 SendGrid 處理您的電子郵件時發生的事件的信息

要在 Firebase 項目中實現 HTTP 端點,您將實現一個HTTPS 雲函數,該函數將由 Sendgrid Webhook 通過 HTTPS POST 請求調用。

來自 Sendgrid webhook 的每個調用都將涉及一個特定的事件,您將能夠在您的雲函數中獲取事件的值(已processed 、已delivered等...)。

現在,您需要在您的 Cloud Function 中將特定事件與之前通過您的 Cloud Function 發送的特定電子郵件相關聯。 為此,您應該使用自定義參數

更准確地說,您將向您的msg對象(您傳遞給send()方法)添加一個唯一標識符。 經典值是 Firestore 文檔 ID,例如event.params.officeId但可以是您在 Cloud Function 中生成的任何其他唯一 ID。


實施例

在發送電子郵件的雲功能,通過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;
      });
  });

請注意,您通過documentSnapshot.data()獲取新創建的文檔(觸發 Cloud Function 的documentSnapshot.data() :您不需要在 Cloud Function 中查詢相同的文檔。


然后,創建一個簡單的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();
        })

})

部署它並獲取它在終端中顯示的 URL:它應該像https://us-central1-<your-project-id>.cloudfunctions.net/sendgridWebhook

請注意,這里我使用admin.firestore().collection('Offices')... 您可以使用const db = newProject.firestore(); ... db.collection('Offices')... const db = newProject.firestore(); ... db.collection('Offices')...

還要注意,Sendgrid webhook 發送的 HTTPS POST 請求的主體包含一個 JavaScript 對象數組,因此我們將使用Promise.all()來處理這些不同的對象,即使用officeId將不同的事件寫入 Firestore 文檔。

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

在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM