Skip to content

Instantly share code, notes, and snippets.

@tvirot
Last active August 16, 2023 21:26
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tvirot/ac7defc85a11ad3791ff581c41aed6d4 to your computer and use it in GitHub Desktop.
Save tvirot/ac7defc85a11ad3791ff581c41aed6d4 to your computer and use it in GitHub Desktop.
Google Cloud Function for Facebook Webhook
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;
}
};
@AntonioArroyave
Copy link

Thaks you this help me !

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment