Topics covering webhook creation & management, event handling, Pub/Sub, and Eventbridge, in Shopify apps.
Hi!
I am developing a webhook listener for my store, in order to connect it to an SMS sending service.
However, I'm stuck at the stage of checking the integrity of the requests I receive (checking if they are really from Shopify).
I am following the documentation to implement this, but even when I copy and paste the provided code, I always get the code 401 (unauthorized). I believe I'm using the correct verification key (the one in the notifications tab, under the webhooks created).
Can anyone tell me what is going on? Was there an update in the dependencies of the code that made it obsolete?
Thanks!
Code:
```
# The following example uses Python and the Flask framework to verify a webhook request:
from flask import Flask, request, abort
import hmac
import hashlib
import base64
app = Flask(__name__)
# The Shopify app's client secret, viewable from the Partner Dashboard. In a production environment, set the client secret as an environment variable to prevent exposing it in code.
CLIENT_SECRET = 'my_client_secret'
def verify_webhook(data, hmac_header):
digest = hmac.new(CLIENT_SECRET.encode('utf-8'), data, digestmod=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 ('', 200)
```
I ran into the same issue recently, but I'm not using flask.
Try CLIENT_SECRET.encode('ascii') instead of CLIENT_SECRET.encode('utf-8'),