Signature Verification for Payment Response
To ensure that a payment response originates from a trusted source, verify the HMAC signature returned in both the payment status API response and your webhook payloads.
Process
Section titled “Process”Gather Inputs
Section titled “Gather Inputs”- orderId: The unique order identifier from your records.
- paymentId: Returned in the payment success/failure response.
- clientSecret: Provided during merchant onboarding.
Generate HMAC Signature
Section titled “Generate HMAC Signature”Use the SHA-256 algorithm, concatenating orderId and paymentId with a pipe (|):
const crypto = require('crypto');function generateHMAC(key, data) { const hmac = crypto.createHmac('sha256', key); hmac.update(data); return hmac.digest('hex');}const secretKey = '<clientSecret>';const message = 'orderId|paymentId'; // Ensure this is properly formatted with actual valuesconst generatedSignature = generateHMAC(secretKey, message);// Compare the generated signature with the one received in the responseif (generatedSignature === signature) { // Payment signature is validated. You can now update the transaction status.}import javax.crypto.Mac;import javax.crypto.spec.SecretKeySpec;import java.security.InvalidKeyException;import java.security.NoSuchAlgorithmException;
public class HMACGenerator { public static void main(String[] args) { String secretKey = "<clientSecret>"; String message = "<orderId>" + "|" + "<paymentId>"; String generatedSignature = generateHMAC(secretKey, message); System.out.println(generatedSignature); // If generatedSignature == signature // payment signature is validated. }
public static String generateHMAC(String key, String data) { try { Mac hmac = Mac.getInstance("HmacSHA256"); SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes(), "HmacSHA256"); hmac.init(secretKeySpec); byte[] hmacBytes = hmac.doFinal(data.getBytes()); return bytesToHex(hmacBytes); // Convert bytes to hexadecimal string } catch (NoSuchAlgorithmException | InvalidKeyException e) { e.printStackTrace(); return null; } }
// Utility method to convert byte array to hexadecimal string public static String bytesToHex(byte[] bytes) { StringBuilder hexString = new StringBuilder(); for (byte b : bytes) { String hex = Integer.toHexString(0xff & b); if (hex.length() == 1) hexString.append('0'); hexString.append(hex); } return hexString.toString(); }}Verify
Section titled “Verify”If your generated signature matches the gateway’s signature, the payload is authentic.