Webhook Validation: Python/Flask working example? HMAC.

Solved
Highlighted
Shopify Partner
1 0 0

Hey all.

I've trying to get the webhook validation up and running for a while with no success.

I've seen the Ruby example, and was wondering if there's a Python example to validade the webhook sent to a Flask app.

Thanks a lot.

0 Likes
Highlighted
Shopify Partner
4 1 1

This is an accepted solution.

Take a look at Verifying webhooks section of the Using webhooks article, and click the Python button.

1 Like
Highlighted
New Member
2 0 1
digest = hmac.new(SECRET.encode('utf-8'), data, hashlib.sha256).digest()

works for me instead of what's there 

0 Likes
Highlighted
Tourist
6 0 0

@davidkong0987 

Do you mind sharing the rest of your code? What I have so far is:

 

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

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

@app.route('/', methods=['POST'])
def main(request):
    print('Received Webhook...')

    data = request.get_data()
    hmac_header = request.headers.get('X-Shopify-Hmac-SHA256')
    verified = verify_webhook(data, hmac_header)
    
    if not verified:
        # do stuff...
        return 'Integrity of request compromised...', 401
    
    # do stuff...
    print('Verified request...')

 

 But it isn't working! I have no idea why and the docs don't help either.

0 Likes
Highlighted
New Member
2 0 1
import hmac
import hashlib
import base64
from flask import Flask

app = Flask(__name__)

SECRET = ''



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

@app.route('/productCreation', methods=['POST'])
def productCreation():
    data = request.data
    verified = verify_webhook(data, request.headers.get('X-Shopify-Hmac-SHA256'))
1 Like
Highlighted
Tourist
6 0 0

@davidkongthank you so much!!!

0 Likes