Validating payload from Facebook webhook in Ruby on Rails


Validating Payloads

  1. Generating aSHA1 signature using the received payload and your app’s App Secret (You can find this in Fb Developer Application Homepage).
  2. Comparing this generated signature to the signature in the X-Hub-Signature header (everything after sha1=). If the signatures matches, the payload is genuine and hence request is validated.

Read Payload

payload =

Get Signature Header

sig_header = request.headers["X-Hub-Signature"]
# Only considering part after sha1= in signature header
sig_header.slice! "sha1="
app_secret = Figaro.env.FB_APP_SECRET

Generate SHA Signature from Payload and APP Secret

sign = get_sha_sign(payload, app_secret)def get_sha_sign(payload, app_secret)    
return OpenSSL::HMAC.hexdigest('sha1'), app_secret.encode("ASCII"), payload.encode("ASCII"))

Validate Signatures

if sign != sig_header      
raise"Invalid Signature")
render plain: "OK"
Rails Validate Facebook Webhook Payload


  1. Handle route properly, correctly map the callback URL to the above handle_webhook method. Remember a POST request is received in the case of webhooks.
  2. Can’t verify CSRF token authenticity.
    Internal Error: ActionController::InvalidAuthenticityToken
    This is a common issue you might simple the method isn’t able to handle the request. What I advise you to do here is adding skip_before_action :verify_authenticity_token just below the class declaration in the controller containing the webhook handler.
    You can read more about this here
  3. Invalid App Secret
    A pretty common mistake is APP Secret is not set. Verify if your app secret is being retrieved via rails console. Figaro or env can be a simple option to work with env variables.




Building, 📍Bengaluru

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Controlling 5V DC Motor using Raspberry Pi 3 Model B+

How to Increase your Business Process through SharePoint Development

Cardano Ecosystem News — July 2021 — from Cardano 360 Update

What it means to be a developer in Nigeria.

Why I use JUCE

AWS EC2 - T2 Instance Family

Bringing Home the Bacon

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Aman Kumar

Aman Kumar

Building, 📍Bengaluru

More from Medium

Using The ‘Faker’ Ruby Gem

Simple Password Resets with BCrypt and Action Mailer — Ruby on Rails

How to Create a Rails 6 API with Devise-JWT

Is Rails worth learning in 2022?