Instamojo Message Authentication Code in Webhook Comparing Issue

204 Views Asked by At

I am integrating INSTAMOJO payment gateway in my application. I am using MAC verification on webhooks response from INSTAMOJO site. Available tutorial is only for Php and Python. But I'm implementing it using NodeJs (ExpressJs). I have attached my code below. So the problem is expected HashCode and calculated HashCode are not the same, kindly look into my code and INSTAMOJO documentation.

func(req, res){
    body= req.body
    {mac}=body
    delete body.mac
    const instaCredentials= {key:***********, secret:*********, webhooks:********}
    const bodyKeys= Object.keys(body).map(key => key);
    const sortedKeys = bodyKeys.sort()

    const values = sortedKeys.map(key => {
        const value = body[key];
        return value.toLowerCase();
    });

    let message = values.join('|');
    const secret = instaCredentials.webhooks
    let calculatedMac= cryptoJs.HmacSHA1(message, secret)
    calculatedMac = expectedMac.toString();
    console.log(mac,calculatedMac)
}

https://support.instamojo.com/hc/en-us/articles/207816249-What-is-the-Message-Authentication-Code-in-Webhook-

1

There are 1 best solutions below

1
On

Try this

const CryptoJS = require('crypto-js');


function verifyHmac(
    receivedHmac, // received in Kindly-HMAC request header
    dataString, // received in request body (stringified JSON)
    key // shared secret, known by your service
) {
    const generatedHmac = CryptoJS.HmacSHA256(dataString, key);
    const generatedHmacBase64 = CryptoJS.enc.Base64.stringify(generatedHmac);

    return generatedHmacBase64 === receivedHmac;
}

// test the function
const receivedHmac = "uEeD0Q7eW9btdx6LFvvlpwkzQBWdbknsQkg1C27Cx7Q=";
const dataString = '{"foo":1,"bar":2}';
const key = "examplekey";

if (!verifyHmac(receivedHmac, dataString, key)) {
    throw new Error("HMAC did not authenticate");
}