Home > other >  How do I get a Webhook JSON written to the Cloud Firestore?
How do I get a Webhook JSON written to the Cloud Firestore?

Time:09-22

I have a WooCommerce Webhook that wants me to send a JSON to a URL, I believe this is a POST http request.

I've used Webhook.site to test the Webhook, and it is displaying the correct JSON payload.

Developers have suggested I use cloud functions to receive the JSON, parse the JSON and write it to the Cloud Firestore.

Is there documentation available on Cloud Functions for Firebase, or Google Cloud Platform's Cloud Functions that detail this process?

I haven't found anything within the Cloud Firestore documentation.

Another available solution might be sending the Webhook JSON to Cloud Storage, but I also haven't managed to get that working. I think I might need to integrate authentication into the HTTP requests headers for that to succeed.

References and Documentation:
"Extend Cloud Firestore with Cloud Functions" https://firebase.google.com/docs/firestore/extend-with-functions
"Cloud Functions - HTTP Functions" https://cloud.google.com/functions/docs/writing/http

CodePudding user response:

What triggers the webhook? The Firestore triggers work when a document is created/modified/deleted and not any external event. You are probably looking for (Firebase) Call functions via HTTP requests (You can also do same directly with Google Cloud Functions). You can write a function as shown below:

exports.myWebhookFunction = functions.https.onRequest((req, res) => {

  const webhookBody = req.body;
  // parse data
  // Add to Firestore/Storage

  // Terminate function
});

When you deploy this function, you'll get an URL (from CLI or also in dashboard) for it which you can set a webhook delivery URL in your WooCommerce webhook.

CodePudding user response:

The classical approach is to use an HTTPS Cloud Function which will expose an endpoint at the following URL: https://<region>-<project-id>.cloudfunctions.net/<cloud-function-name>

Here is a code skeleton, as a basis:

// cloud-function-name = myWebhook
exports.myWebhook = functions.https.onRequest(async (req, res) => {
    const body = req.body; //body is an array of JavaScript objects

    // Get the details of the WooCommerce event, most probably from the body
    const updateObj = {...}

    // Write to Firestore

    await admin.firestore().collection('...').doc('...').set(updateObj);

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

});

More details on this kind of Cloud Functions in this official video, including how to manage errors and send back corresponding HTTP codes to the caller.

  • Related