使用 Cloud Functions 将 Json Webhook 写入 Cloud Firestore。云函数部署失败。加载用户代码时函数失败

Write Json Webhook to Cloud Firestore with Cloud Functions. Cloud Function Failed to Deploy. Function failed on loading user code

我有一个 Webhook,它向我的 Cloud Function URL 传送复杂的 JSON 负载,并将该 JSON 写入我的 Cloud Firestore 中的集合和文档。

我相信 Google Cloud Functions 上的 Node.JS 运行时使用 Express 中间件 HTTP 框架。

我有一个 WooCommerce Webhook 要我发送 JSON 到 URL,我相信这是一个 POST http 请求。

我已经使用 Webhook.site 测试了 Webhook,它显示了正确的 JSON 负载。

开发人员建议我使用云函数接收 JSON、解析 JSON 并将其写入 Cloud Firestore。

// cloud-function-name = wooCommerceWebhook
exports.wooCommerceWebhook = functions.https.onRequest(async (req, res) => {
    const payload = req.body;

    // Write to Firestore - People Collection
    await admin.firestore().collection("people").doc().set({
        people_EmailWork: payload.billing.email,
    });

// Write to Firestore - Volociti Collection
    await admin.firestore().collection("volociti").doc("fJHb1VBhzTbYmgilgTSh").collection("orders").doc("yzTBXvGja5KBZOEPKPtJ").collection("orders marketplace orders").doc().set({
        ordersintuit_CustomerIPAddress: payload.customer_ip_address,
    });

    // Write to Firestore - Companies Collection
    await admin.firestore().collection("companies").doc().set({
        company_AddressMainStreet: payload.billing.address_1,
    });
    return res.status(200).end();
});

如果有帮助的话,我有我的云函数部署失败的日志。

Function cannot be initialized. Error: function terminated. Recommended action: inspect logs for termination reason. Additional troubleshooting documentation can be found at https://cloud.google.com/functions/docs/troubleshooting#logging

我的package.json:

{
  "name": "sample-http",
  "version": "0.0.1"
}

您需要为Node.js正确define the dependency with the Firebase Admin SDK,并进行初始化,如下图

您还需要更改声明函数的方式:exports.wooCommerceWebhook = async (req, res) => {...} 而不是 exports.wooCommerceWebhook = functions.https.onRequest(async (req, res) => {...});。您使用的是通过 CLI 部署的 Cloud Functions。

package.json

{
  "name": "sample-http",
  "version": "0.0.1",
  "dependencies": {    "firebase-admin": "^9.4.2"  }
}

index.js

const admin = require('firebase-admin')
admin.initializeApp();

exports.wooCommerceWebhook = async (req, res) => {  // SEE COMMENT BELOW
    const payload = req.body;

    // Write to Firestore - People Collection
    await admin.firestore().collection("people").doc().set({
      people_EmailWork: payload.billing.email,
    });

    // Write to Firestore - Volociti Collection
    await admin.firestore().collection("volociti").doc("fJHb1VBhzTbYmgilgTSh").collection("orders").doc("yzTBXvGja5KBZOEPKPtJ").collection("orders marketplace orders").doc().set({
      ordersintuit_CustomerIPAddress: payload.customer_ip_address,
    });

   // Write to Firestore - Companies Collection
   await admin.firestore().collection("companies").doc().set({
       company_AddressMainStreet: payload.billing.address_1,
   });

   return res.status(200).end();
 };