Verify Payment Signature using Java
To verify the signature in Java, use the following format:
Create a signature on your server
Section titled “Create a signature on your server”orderId: Retrieve the orderId from your serverpaymentId: This field will be available in the success/failure responseclientSecret: You will receive this information during the onboarding process
Use the SHA256 algorithm, as given below
Section titled “Use the SHA256 algorithm, as given below”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(); }}If the signature you generate on your server matches the signature returned to you, the payment received is from an authentic source.