Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validating payload from Facebook webhook

EDIT:

The comment by CBroe is the solution. Ensure the payload from Facebook is not parsed before making the hash.


I'm trying to validate the contents of a webhook payload from the Instagram Graph API using the steps in the Facebook developer docs.

I can't seem to generate a matching hash, despite following all the steps in the docs. To be clear, my code is creating a hash successfully, it just doesn't match the one Facebook is sending with the webhook.

My code is below (with dummy values used for app secret and payload contents). Any help would be greatly appreciated.

const crypto = require('crypto')

// Escape special characters
const escapeUnicode = str => {
    return str.replace(/[\u00A0-\uffff]/gu, function (c) {
        return "\\u" + ("000" + c.charCodeAt().toString(16)).slice(-4)
    })
}

// Dummy values
const payload = {
    "object": "instagram",
    "entry": [
        {
            "id": "some-id",
            "time": 1234567890,
            "changes": [
                {
                    "value": {
                        "media_id": "some-id",
                        "impressions": 0,
                        "reach": 0,
                        "taps_forward": 0,
                        "taps_back": 0,
                        "exits": 0,
                        "replies": 0
                    },
                    "field": "story_insights"
                }
            ]
        }
    ]
}

// Create hash
const hmac = crypto.createHmac('sha1', 'my-app-secret')
hmac.update(escapeUnicode(JSON.stringify(payload)))
const hash = `sha1=${hmac.digest('hex')}`
like image 696
Lewis Donovan Avatar asked Jul 16 '26 17:07

Lewis Donovan


1 Answers

I was struggling with the same problem too. For future readers, this is the solution if you are using ExpresJS and bodyparser (Found here)

app.use(bodyParser.json({
    verify: (req, res, buf) => {
        req.rawBody = buf
    }
}));

Then for calculating the checksum of the payload, simply pass req.rawBody as the paylod,

const crypto = require('crypto');
const calculatedChecksum = crypto.createHmac('sha1', APP_SECRET)
                                 .update(req.rawBody)
                                 .digest('hex');
like image 60
Jahir Avatar answered Jul 19 '26 07:07

Jahir



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!