Search code examples
node.jsfirebasefunctiongocardless

Handling gocardless webhook with firebase functions


I'm using GoCardless (sandbox account) webhook for a billing project. I've follow the steps on this guide using Nodejs locally (with ngrok) to handle the webhooks and it works, my intention is to use firebase functions as server, but when I deploy the code on firebase and test the code it throws 'timeout error', I don know if I'm missing something about firebase functions... This is the code on firebase:

    const functions = require('firebase-functions');
    const webhooks = require("gocardless-nodejs/webhooks");
    const webhookEndpointSecret = "xxxxxx";
    exports.events = functions.https.onRequest((request, response) => {
    if (request.method !== "POST") {
        response.writeHead(405);
        response.end();
        return;
    }
    let data = "";
    request.on("data", chunk => {
        data += chunk;
    });
    request.on("end", () => {
        try {
            const signatureHeader = request.headers["webhook-signature"];
            const events = webhooks.parse(
                data,
                webhookEndpointSecret,
                signatureHeader
            );
            events.forEach(event => {
                if (event.resource_type !== "mandates") {
                    //continue;
                }
                switch (event.action) {
                    case "created":
                        console.log(
                            `Mandate ${event.links.mandate} has been created, yay!`
                        );
                        break;
                    case "cancelled":
                        console.log(`Oh no, mandate ${event.links.mandate} was cancelled!`);
                        break;
                    default:
                        console.log(`${event.links.mandate} has been ${event.action}`);
                }
            });
            response.writeHead(204);
            response.end();
        } catch (e) {
            response.writeHead(403);
            response.end();
        }
    });
});

Thanks!


Solution

  • Ok, I finally figured out how was going on... the problem was that the 'data' variable was empty. I solved the problem getting the request body like this:

    let data = request.rawBody.toString();
    

    I hope this can be useful for someone else.