chaitanya
chaitanya

Reputation: 188

How to verify cashfree gateway's webhook signature in js

I am using cashfree payments gateway. Everything is working fine, but I don't know how to verify webhooks signature.

enter image description here

This is how they are asking to do. How to write javascript code for it ?

Upvotes: 0

Views: 726

Answers (1)

obh
obh

Reputation: 334

Thanks for the heads up. We are working on improving the webhook documentation. In the meantime the steps to verify the webhook are -

  1. Get the payload from the webhook endpoint
  2. Generate the signature
  3. Verify the signature.

The payload here refers to the raw json body and not something parsed by bodyParser. I will share the code for Express.

getting the payload
//Set up your server like this 
var express = require('express')
var bodyParser = require('body-parser');
var crypto = require('crypto');
var app = express()

//This part is to get the rawBody
app.use(
    express.json({
        limit: '5mb',
        verify: (req, res, buf) => {
        req.rawBody = buf.toString();
        },
    })
);
app.use(bodyParser.json());
//This is your endpoint
app.post('/webhook', function(req, res) {
    console.log(req.rawBody);
    const ts = req.headers["x-webhook-timestamp"]
    const signature = req.headers["x-webhook-signature"]
    console.log("ts --> ", ts);
    console.log("expected sign --> ", signature);
    const genSignature = verify(ts, req.rawBody)
    if(signature === genSignature){
        res.send('OK')
    } else {
        res.send("failed")
    } 
})

verifying signature

function verify(ts, rawBody){
    const body = ts + rawBody
    const secretKey = "<your secret key>";
    let genSignature = crypto.createHmac('sha256',secretKey).update(body).digest("base64");
    return genSignature
}

Upvotes: 1

Related Questions