Webhook signature validation

Hi, i have struggled to verify for webhook notification on sandbox… is it can we verify on sandbox ?? if you have article or example github apps please help me

i’m working on nodejs (expressjs)
Thank you

We do have an example in node.js.

import * as http from 'http';
import { WebhooksHelper } from 'square';

// The URL where event notifications are sent.
const NOTIFICATION_URL = 'https://example.com/webhook';

// The signature key defined for the subscription.
const SIGNATURE_KEY = 'asdf1234';

// isFromSquare generates a signature from the url and body and compares it to the Square signature header.
function isFromSquare(signature, body) {
  return WebhooksHelper.isValidWebhookEventSignature(
      body,
      signature,
      SIGNATURE_KEY,
      NOTIFICATION_URL
    );
}

function requestHandler(request, response) {
  let body = '';
  request.setEncoding('utf8');

  request.on('data', function(chunk) {
    body += chunk;
  });

  request.on('end', function() {
    const signature = request.headers['x-square-hmacsha256-signature'];
    if (isFromSquare(signature, body)) {
      // Signature is valid. Return 200 OK.
      response.writeHead(200);
      console.info("Request body: " + body);
    } else {
      // Signature is invalid. Return 403 Forbidden.
      response.writeHead(403);
    }
    response.end();
  });
}

// Start a simple server for local testing.
// Different frameworks may provide the raw request body in other ways.
// INSTRUCTIONS
// 1. Run the server:
//    node server.js
// 2. Send the following request from a separate terminal:
//    curl -vX POST localhost:8000 -d '{"hello":"world"}' -H "X-Square-HmacSha256-Signature: 2kRE5qRU2tR+tBGlDwMEw2avJ7QM4ikPYD/PJ3bd9Og="
const server = http.createServer(requestHandler);
server.listen(8000);

:slightly_smiling_face:

Hi thank you for your suggestion, i have see the code others day… but i dont know its not working…
but i see on the Squareup Blog and its working

here’s my result:

const body = req.body
const signature = req.headers["x-square-hmacsha256-signature"]
const hmac = createHmac("sha256", SIGNATURE_KEY);
hmac.update(NOTIFICATION_URL + JSON.stringify(body));
const hash = hmac.digest("base64");
return hash === signature;

notes:

- req.body is a JSON data
- signature you can get from 'x-square-hmacsha256-signature' with sha256 or you can use 'x-square-signature' with sha1

I also seem to have a problem with the C# sample given on that page. I get back a 403 Forbidden. It looks like the page may be incomplete as there is a section that states…
The following functions generates an HMAC-SHA256 signature from your signature key, the notification URL, and the event notification body. You can then compare the result with the event notification’s x-square-hmacsha256-signature . But then goes into the examples which looks like they should be standalone and change nothing as the curl command signature would have to change if variables where changed.