razorpay / razorpay-node

Razorpay node.js bindings
MIT License
164 stars 108 forks source link

cant verify signature #380

Open profabhishekjha opened 9 months ago

profabhishekjha commented 9 months ago

Steps to reproduce the behavior

import crypto from "crypto"; import prisma from "@/utils/connect"; import { NextResponse } from "next/server";

export const POST = async (req) => { try { const body = await req.json(); const { event, payload } = body;

  // Your Razorpay key secret
  const razorpayKeySecret = "**************";

  // Retrieve the Razorpay signature from the x-razorpay-signature header
  const razorpaySignature = req.headers.get("x-razorpay-signature");

  // Verify the Razorpay signature
  const generatedSignature = crypto
    .createHmac("sha256", razorpayKeySecret)
    .update(JSON.stringify(payload))
    .digest("hex");

  if (generatedSignature !== razorpaySignature) {
    console.error("Invalid Razorpay signature");
    return new NextResponse("Invalid Razorpay signature", { status: 401 });
  }

  switch (event) {
    case "payment.authorized":
      break;
    case "payment.captured":
      const donationId = payload.payment.entity.notes.donationId;

      if (donationId) {
        await prisma.donation.update({
          where: { id: donationId },
          data: { status: "Success" },
        });
        console.log("Payment Captured:", donationId);
      } else {
        console.error(
          "Invalid or missing donationId from Razorpay webhook payload"
        );
        return new NextResponse("Invalid or missing donationId", {
          status: 400,
        });
      }
      break;
    default:
      // Handle other events if needed
      console.log("Unhandled Event:", event);
  }

  return new NextResponse("Webhook Received", { status: 200 });
} catch (error) {
  console.error("Error processing webhook:", error);
  return new NextResponse(
    JSON.stringify({ message: "Something went wrong!" }, { status: 500 })
  );
}

};

Expected behavior

it should verify signature but no , its not, please help me if anyone can

Actual behavior

its not matching both the values

Code snippets

import crypto from "crypto";
  import prisma from "@/utils/connect";
  import { NextResponse } from "next/server";

  export const POST = async (req) => {
    try {
      const body = await req.json();
      const { event, payload } = body;

      // Your Razorpay key secret
      const razorpayKeySecret = "**************";

      // Retrieve the Razorpay signature from the x-razorpay-signature header
      const razorpaySignature = req.headers.get("x-razorpay-signature");

      // Verify the Razorpay signature
      const generatedSignature = crypto
        .createHmac("sha256", razorpayKeySecret)
        .update(JSON.stringify(payload))
        .digest("hex");

      if (generatedSignature !== razorpaySignature) {
        console.error("Invalid Razorpay signature");
        return new NextResponse("Invalid Razorpay signature", { status: 401 });
      }

      switch (event) {
        case "payment.authorized":
          break;
        case "payment.captured":
          const donationId = payload.payment.entity.notes.donationId;

          if (donationId) {
            await prisma.donation.update({
              where: { id: donationId },
              data: { status: "Success" },
            });
            console.log("Payment Captured:", donationId);
          } else {
            console.error(
              "Invalid or missing donationId from Razorpay webhook payload"
            );
            return new NextResponse("Invalid or missing donationId", {
              status: 400,
            });
          }
          break;
        default:
          // Handle other events if needed
          console.log("Unhandled Event:", event);
      }

      return new NextResponse("Webhook Received", { status: 200 });
    } catch (error) {
      console.error("Error processing webhook:", error);
      return new NextResponse(
        JSON.stringify({ message: "Something went wrong!" }, { status: 500 })
      );
    }
  };

Node version

latest

Library version

latest

Additional Information

No response

crypticatul commented 6 months ago

We are also facing the same issue. Is anyone working on this? @projectashik

dhwaj1902 commented 6 months ago

I am facing the same issue. Can anyone in Razorpay help us with this? or @profabhishekjha have you figured out any solution for this?

kakdeykaushik commented 6 months ago

You can use validatePaymentVerification function to verify payment signature. Refer to this doc

dhwaj1902 commented 6 months ago

Hi @kakdeykaushik, I have also used validatePaymentVerification, but I could not verify the signature in the webhook response.

Sen-442b commented 1 month ago

In the docs they have mentioned using raw requestbody (req.body) as the message to create the hash signature. In your case, you're using payload of the body

const generatedSignature = crypto
        .createHmac("sha256", razorpayKeySecret)
        .update(JSON.stringify(req.body)) // raw requestBody  
        .digest("hex");

However, even that is not working for me
Could you let me know if you managed to resolve it? @dhwaj1902 @profabhishekjha ?