Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validate X-Hub-Signature-256 meta / whatsapp webhook request

I can't manage to validate the X-Hub-Signature-256 for my meta / whatsapp webhook in flask successfully.

Can anyone tell me where the error is or provide me with a working example?

import base64
import hashlib
import hmac
import os

from dotenv import load_dotenv
from flask import Flask, jsonify, request
from werkzeug.middleware.proxy_fix import ProxyFix

load_dotenv()

API_SECRET = os.environ.get('API_SECRET')

app = Flask(__name__)
app.wsgi_app = ProxyFix(app.wsgi_app, x_for=1, x_host=1)


def verify_webhook(data, hmac_header):

    hmac_recieved = str(hmac_header).removeprefix('sha256=')
    digest = hmac.new(API_SECRET.encode('utf-8'), data,
                      digestmod=hashlib.sha256).digest()
    computed_hmac = base64.b64encode(digest)

    return hmac.compare_digest(computed_hmac, hmac_recieved.encode('utf-8'))


@app.route("/whatsapp", methods=["GET", "POST"])
def whatsapp_webhook():


    if request.method == "POST":

        try:
            data = request.get_data()

            if not verify_webhook(data, request.headers.get('X-Hub-Signature-256')):
                return "", 401

        except Exception as e:
            print(e)
            return "", 500

    return jsonify({"status": "success"}, 200)
like image 460
Gurkenkönig Avatar asked Jan 26 '26 23:01

Gurkenkönig


1 Answers

For those who are curious about locating the elusive "API_SECRET," you can conveniently find it within your facebook application settings:

Facebook Developer Dashboard

like image 120
Christian M Avatar answered Jan 28 '26 13:01

Christian M