Last active
August 16, 2023 21:26
-
-
Save tvirot/ac7defc85a11ad3791ff581c41aed6d4 to your computer and use it in GitHub Desktop.
Google Cloud Function for Facebook Webhook
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const config = require('./config.json'); | |
const bigquery = require('@google-cloud/bigquery')(); | |
function insertRows(rows) { | |
bigquery | |
.dataset(config.DATASET) | |
.table(config.TABLE) | |
.insert(rows) | |
.then((data) => { | |
console.log(`${rows.length} rows inserted.`); | |
console.log(data[0]); | |
}) | |
.catch((err) => { | |
console.error(`ERROR: ${err}`); | |
}); | |
} | |
function processData(req, res) { | |
// See the structure of JSON payloads here: | |
// https://developers.facebook.com/docs/graph-api/webhooks#callback | |
let n_entries = 0; | |
let n_changes = 0; | |
let changes = []; | |
req.body.entry.forEach((e) => { | |
n_entries++; | |
e.changes.forEach((c) => { | |
n_changes++; | |
let value = c.value; | |
value.id = e.id; | |
changes.push(value); | |
}); | |
}); | |
res.status(200).send(); | |
insertRows(changes); | |
console.log(changes); | |
console.log(`${n_entries} entries, ${n_changes} changes`); | |
} | |
exports.webhook = function webhook(req, res) { | |
switch (req.method) { | |
case 'GET': | |
// Handle verification requests | |
if (req.query['hub.mode'] === 'subscribe' && | |
req.query['hub.verify_token'] === config.VERIFY_TOKEN) { | |
res.status(200).send(req.query['hub.challenge']); | |
} else { | |
res.sendStatus(403); | |
} | |
break; | |
case 'POST': | |
// Notifications are sent using POST requests | |
processData(req, res); | |
break; | |
default: | |
res.status(500).send({ error: `Request method error: ${req.method}`}); | |
break; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thaks you this help me !