My Generated Signature is not matching the razorpay signature in nodejs

24 Views Asked by At

I am creating a Hmac with the req.body the webhook secret and the digest method and then matching the generatedSignature with the X-razorpay signature received in the headers but both the signatures do not match. I have cross check the webhookSecret and it is matching properly.

My routers file:

const router1 = require("express").Router();
require("dotenv").config();
const razorPay = require("razorpay");

const razorpay = new razorPay({
    key_id: `${process.env.key_id}`,`
    key_secret: `${process.env.key_secret}`,
});

router1.post("/checkout/create-session", async (req, res) =\> {
    try {
        const { id, total, email name, discountAmount, discount } = req.body;
        const amount = Math.floor(total \* 100);
        const order = await razorpay.orders.create({
            amount: amount, // Amount in paisa
            currency: 'INR',
            receipt: id, // Use 'id' instead of 'userId'
            payment_capture: 1,
            notes: {
                cartId: id,
            },
        });
       return res.json({ orderId: order.id, currency: order.currency, amount: order.amount });
    }catch(error) {
        console.log(error);
        return res.json({success: false, message: "Server Error."});
    }
});

router1.post("/webhook", async (req, res) =\> {
    try {
        const webhookSecret = process.env.webhook_secret;
        const generatedSignature = crypto.createHmac('sha256', webhookSecret)
        .update(JSON.stringify(req.body))
        .digest('hex');  
        if(generatedSignature  === req.headers\['x-razorpay-signature'\]){
            console.log("Signature verification successful");
        }else {
            console.log("Not Working");
        }
    } catch (error) {
        console.error('Error processing webhook:', error.message);
        console.log(error);
        res.status(400).send('Error processing webhook');
    }
});
module.exports = router1; 

Help me with problem is there something which I am doing wrong. Because most of the time am getting NOT Working in the console.
I am using ngrok to test my webhook locally.

Also this same code runs properly some time and I get both the signature matched what's the problem?

0

There are 0 best solutions below