Python, Java Webhook Verification examples

112 views
Skip to first unread message

Ed Vinyard

unread,
Apr 28, 2021, 7:00:48 PM4/28/21
to DrChrono API Developers
My two cents...

The webhook verification example code in the API docs could be improved by making it independent of Django (I think?) and making it clear what the type/content of WEBHOOK_SECRET_TOKEN is.  Perhaps I missed it somewhere, but I can't see where that's specified.

Here are working, standalone examples in Python and Java.  (The following code is in the public domain; do whatever you want with it.)

Python
-------------------------------------------------------------
import hashlib
import hmac

def webhook_verification(secret_str, message_str):
    '''
    '''
    return hmac.new(
        bytearray(secret_str, 'utf-8'),
        message_str.encode('utf-8'),
        hashlib.sha256
        ).hexdigest()

if __name__ == '__main__':
    msg = 'hello'
    secret = '11223344-5566-7788-9900-aabbccddeeff'
    print(webhook_verification(secret, msg))
-------------------------------------------------------------

Java
-------------------------------------------------------------
import java.math.BigInteger;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

public class Main {
    public static void main(String[] args) throws Exception {
        System.out.println(webhookVerification(
            "11223344-5566-7788-9900-aabbccddeeff",
            "hello"));
    }

    static String webhookVerification(String secret, String msg) throws Exception {
        byte[] hmacSha256;
        byte[] secretKey = secret.getBytes("UTF-8");
        byte[] message = msg.getBytes("UTF-8");
        Mac mac = Mac.getInstance("HmacSHA256");
        SecretKeySpec secretKeySpec = new SecretKeySpec(secretKey, "HmacSHA256");
        mac.init(secretKeySpec);
        hmacSha256 = mac.doFinal(message);
        return String.format("%032x", new BigInteger(1, hmacSha256));
    }
}
-------------------------------------------------------------

Cheers,
Ed

bri...@drchrono.com

unread,
Apr 28, 2021, 7:05:20 PM4/28/21
to DrChrono API Developers
Appreciate the contribution Ed. 

For anyone else looking for a different webhook setup example, there is also an article listed here: https://developers.drchrono.com/connecting-and-testing-drchrono-webhooks-with-django-and-ngrok-io/, although it is specific to Django as well. The Python code in the article is also updated from the documentation to illustrate Python v3.

Reply all
Reply to author
Forward
0 new messages