title: Encoding request body with HMAC sha256 and base64
body: <p>How to encode a request body using HMAC sha 256 and  base64.</p>
  <p>The request object that i receives from xero webhook.</p>
  <pre><code>HEADER:
     &quot;x-xero-signature&quot; : HASH_VALUE
  PAYLOAD:
    {
       &quot;events&quot;: [],
       &quot;lastEventSequence&quot;: 0,
       &quot;firstEventSequence&quot;: 0,
       &quot;entropy&quot;: &quot;S0m3r4Nd0mt3xt&quot;
    } 
  </code></pre>
  <p>The note from xero documentation says &quot;If the payload is hashed using HMACSHA256 with your webhook signing key and base64 encoded, it should match the signature in the header. This is a correctly signed payload. If the signature does not match the hashed payload it is an incorrectly signed payload.&quot;</p>
  <p>And I followed this example : <a href="https://devblog.xero.com/using-xero-webhooks-with-node-express-hapi-examples-7c607b423379" rel="nofollow noreferrer">https://devblog.xero.com/using-xero-webhooks-with-node-express-hapi-examples-7c607b423379</a></p>
  <pre><code>const express = require(&quot;express&quot;);
  const router = express.Router();
  const base64 = require('base-64');
  const crypto = require('crypto')
  const bodyParser = require('body-parser')
  const xero_webhook_key = '00fRRlJBYiYN4ZGjmTtG+g/pulyb1Eru68YYL3PFoLsa78dadfQtGrOMuISuVBHxpXeEYo0Yy1Gc+hHMhDkSI/EEcgtrA==';
  
  let options = {
      type: 'application/json'
    };
  let itrBodyParser = bodyParser.raw(options);
  
  router.post(&quot;/&quot;, itrBodyParser, async (req, res, next) =&gt;{
  //     console.log('::::WebhookPost:::');
  const reSign = req.headers['x-xero-signature'];
   console.log(req.headers['x-xero-signature']);
   console.log('::::::::');
   console.log(req.body);
      console.log(&quot;Body: &quot;+JSON.stringify(req.body))
      console.log(req.body.toString());
      console.log(&quot;Xero Signature: &quot;+ reSign);
      console.log('Server key::::',xero_webhook_key);
      // Create our HMAC hash of the body, using our webhooks key
      let hmac = crypto.createHmac(&quot;sha256&quot;, xero_webhook_key).update(req.body.toString()).digest('base64');
      console.log(&quot;Resp Signature: &quot;,hmac)
  
      if (req.headers['x-xero-signature'] == hmac) {
          res.statusCode = 200
      } else {
          res.statusCode = 401
      }
      console.log(&quot;Response Code: &quot;+res.statusCode)
      return res.send();
   
  
  });
  </code></pre>