1// The crypto module provides cryptographic functionality
2const crypto = require('crypto');
3
4// const body = JSON.stringify(req.body);
5// const signature = req.header('x-square-signature');
6
7function isValidSignature(body, url, signature) {
8 // Concatenate your notification URL and
9 // the JSON body of the webhook notification
10 const combined = url + body;
11
12 // Webhook subscription signature key defined in dev portal for app
13 // webhook listener endpoint: https://webhook.site/my-listener-endpoint
14 // Note: Signature key is truncated for illustration
15 const signatureKey = 'uTYf8X...0HGvYg';
16
17 // Generate the HMAC-SHA1 signature of the string
18 // signed with your webhook signature key
19 const hmac = crypto.createHmac('sha1', signatureKey);
20 hmac.write(combined)
21 hmac.end()
22 const checkHash = hmac.read().toString('base64');
23
24 // Compare HMAC-SHA1 signatures.
25 if (checkHash === signature) {
26 console.log('Validation success!');
27 } else {
28 console.log('Validation error.');
29 }
30}