How to Verify Razorpay Payments in ASP.NET Core
A browser can tell my API that a payment succeeded. It can also tell my API that it paid ₹1 for a ₹4,399 order. Both requests arrive in the same shape, so I stopped trying to tell them apart at the edge. My server proves
A browser can tell my API that a payment succeeded. It can also tell my API that it paid ₹1 for a ₹4,399 order. Both requests arrive in the same shape, so I stopped trying to tell them apart at the edge. My server proves the money itself.
GameHub is my .NET 8 store: 46 endpoints across 11 controllers. I built it to work through the whole commerce lifecycle, and payments were the part I couldn't fake. The file I use to decide whether an order is paid is RazorpayPaymentService.cs, 487 lines. Here's what's in it that matters.
I treat the client as a pointer, not proof
My verify endpoint takes RazorpayOrderId, RazorpayPaymentId, RazorpaySignature, and an optional Amount. Four fields a browser can type. I don't trust any of them on their own, so my controller does nothing except pass them to the service.
There's no try/catch in that controller either. ExceptionMiddleware maps BusinessRuleException to 400 and NotFoundException to 404. I pulled the old catch blocks out because they were stuffing ex.Message into responses and leaking internals.
The signature covers two ids and nothing else
Razorpay signs the string orderId|paymentId with my key secret, and I keep that secret in server config where the browser can't reach it. If I don't recompute the hash myself, anyone who can read my frontend can mark an order paid.
private bool VerifySignature(string orderId, string paymentId, string signature)
{
string payload = $"{orderId}|{paymentId}";
using var hmac = new HMACSHA256(Encoding.UTF8.GetBytes(_keySecret));
byte[] hash = hmac.ComputeHash(Encoding.UTF8.GetBytes(payload));
string computedSignature = BitConverter.ToString(hash).Replace("-", "").ToLower();
return computedSignature == signature.ToLower();
}
Notice what's missing from that payload: the amount. A valid signature proves the payment id belongs to that order. It says nothing about how much was paid. That's the second check, and it's the one I see skipped most often.
I keep money in integer paise
Razorpay speaks in paise. My purchase total is a decimal. I convert with (int)Math.Round(purchase.Total * 100, MidpointRounding.AwayFromZero), and AwayFromZero isn't paranoia. 4398.90m * 100 can land on 439889.99999999994 in double, truncate to 439889, and then fail against a payment that was correct. I round once, at the boundary, and compare integers after that.
My comparison is >=, not ==. If someone pays more, I don't want their order stuck in pending over eleven paise. I treat underpayment as a hard fail. Overpayment is a support ticket.
I ask Razorpay and fail closed
The payment-link flow does not give me a signature to check, so I ask Razorpay directly:
using var linkDoc = await TryFetchPaymentLinkAsync(request.RazorpayPaymentLinkId)
?? throw new BusinessRuleException(ExceptionMessages.PaymentNotVerified);
var linkStatus = linkDoc.RootElement.TryGetProperty("status", out var ls)
? (ls.GetString() ?? "") : "";
if (!string.Equals(linkStatus, "paid", StringComparison.OrdinalIgnoreCase))
throw new BusinessRuleException(ExceptionMessages.PaymentNotVerified);
Then I walk the link's payments array and need a matching id with status captured or authorized, and an amount above zero. Anything else isn't verified, and I don't touch the order.
The part I care about most is inside TryFetchPaymentLinkAsync. It returns null on a timeout, a 500, or a DNS failure, and never throws. null becomes "not verified". If Razorpay is down, my order stays unpaid. That's the direction I want to fail in: a customer retries, an attacker gets nothing.
One purchase gets one link
My retries used to mint a new payment link every time. Now I reuse the open one if it's still valid. And I added a guard after thinking about what a duplicate link actually costs:
if (paymentRow.Status == PaymentStatus.Success)
{
// Money already recorded but the order is not confirmed:
// treat as a payment/integrity mismatch and refuse to mint another link.
throw new BusinessRuleException(ExceptionMessages.PaymentAlreadyVerified);
}
A paid row with an unconfirmed order means something broke between those two writes. Minting a second link would take the customer's money twice, so I throw instead. I'd rather return an error than guess.
I make failure leave the cart usable
When the signature check fails, my code doesn't just mark the payment failed. It restores the purchase lines into the cart inside the same transaction, merging with any row that already exists for that game instead of adding a duplicate quantity. Then it commits and throws.
I care about that merge more than it sounds. Before it, a customer who retried three times ended up with three copies of the same game in my cart, and the total no longer matched what they thought they were buying.
What I'd still change
Three things in this file I'd fix before I call it finished:
-
==on signature strings. String comparison can short-circuit on the first differing byte, which is a timing side channel.CryptographicOperations.FixedTimeEqualson the raw bytes is the right call. It's impractical to exploit over a network, but the fix is one line. -
The client amount is only checked when it's above zero. Sending
0skips my local check and falls through to the Razorpay API call, which requires an exact match. Correct today, fragile tomorrow. -
Two amount rules.
verifyrequires an exact match against Razorpay's record.confirm-linkaccepts anything at or above my total. I'd unify them on>=and log the overpayment.
One architectural gap too: my confirmation is pull-based. The browser comes back to /order-confirmation, my frontend calls confirm-link, and my server checks. I don't have a Razorpay webhook endpoint yet, so if a customer pays and closes the tab, that order sits unconfirmed until they come back. A webhook would close that hole.
The short version
The client is a pointer. The signature proves the payment id belongs to the order. The amount check proves the money is enough. Razorpay's API is the only thing that can say "paid". Everything else is me asking those questions in order, and I'd rather my server say no than my browser say yes.
I checked all of this against RazorpayPaymentService.cs in my repo: 487 lines, two flows (verify and confirm-link), HMAC-SHA256 over orderId|paymentId, integer paise, fail-closed fetches.
Source: github.com/naheel0/GameHub-fullstack
Disclosure: I used AI to help draft this post. The code and the decisions in the repo are mine.
When your checkout decides an order is paid, which check runs last: the callback, a webhook, or a server-to-server call?
Originally published by Dev.to Security. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.