Verify webhook code snippet for python flask not working as expected

I was following this bit of doc - https://shopify.dev/apps/webhooks/configuring#verify-the-request-is-from-shopify to verify my webhook was actually coming from shopify.

While this documentation is absolutely clear and useful , I found some issues with the example code provided for Python Flask which is

from flask import Flask, request, abort
import hmac
import hashlib
import base64

app = Flask(__name__)

SECRET = 'hush'

def verify_webhook(data, hmac_header):
    digest = hmac.new(SECRET, data.encode('utf-8'), hashlib.sha256).digest()
    computed_hmac = base64.b64encode(digest)

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

@app.route('/webhook', methods=['POST'])
def handle_webhook():
    data = request.get_data()
    verified = verify_webhook(data, request.headers.get('X-Shopify-Hmac-SHA256'))

    if not verified:
        abort(401)

    # process webhook payload
    # ...

    return ('Webhook verified', 200)

First this line

SECRET = 'hush'

should be changed to

SECRET = b"your_app_secret"

That b is necessary to give the hmac.new function a bytes input for key rather than a str

Secondly,

on this line

digest = hmac.new(SECRET, data.encode('utf-8'), hashlib.sha256).digest()

data does not need to be encoded again. just giving data as the argument works fine.

digest = hmac.new(SECRET, data, hashlib.sha256).digest()

like this.

I am new to this platform and I thought this might help any future learner like me who wants to implement webhook in Flask

1 Like

Hi @tamjid_rayhan

thank you very much. I was just fighting with this issue.

Kind regards from Heidelberg in Germany
Thomas

1 Like