SHA256 webhook signature from WooCommerce never verifies

后端 未结 6 937
再見小時候
再見小時候 2021-01-02 23:47

I am receiving webhooks from a woocommerce site into a nodejs/express application. I am trying to verify the webhook\'s signature to prove authenticity, yet the hash I compu

6条回答
  •  执念已碎
    2021-01-03 00:11

    Since this is the top Google result for this question and there isn't a complete answer out there, here's a Python version using Flask that validates the WooCommerce webhook signature. It took a bit of trial and error, hope it helps someone out there:

    import json
    import base64
    import hmac
    import hashlib
    
    from flask import Flask, request, Response
    
    app = Flask(__name__)
    
    # The WooCommerce webhook secret
    WEBHOOK_SECRET = 'abc123456'
    
    # Function that compares the computed signature to the one in the request
    def verify_woocommerce_signature(body, signature, secret):
        digest = hmac.new(bytes(secret, 'utf-8'), body, hashlib.sha256).digest()
        encoded = base64.b64encode(digest).decode()
    
        return encoded == signature
    
    # WooCommerce Order Creation Event
    @app.route('/webhooks/woocommerce/order_created', methods=['POST'])
    def webhooks_woocommerce_order_created():
        # Get raw request body
        body = request.get_data()
        
        # Get request signature
        signature = request.headers['X-WC-WEBHOOK-SIGNATURE']
        
        # Verify webhook signature and handle mismatch
        if verify_woocommerce_signature(body, signature, WEBHOOK_SECRET) is False:
            msg = {"success": False}
            return Response(json.dumps(msg), status=400, mimetype='application/json')
    
        # Signatures match, process the payload
    

提交回复
热议问题