有人可以帮助我如何在Java中验证Shopify Webhook吗?目前,我正在使用以下代码,但是我无法验证
@RequestMapping(value = "/order", method = RequestMethod.POST)
public ResponseEntity<Object> getWebhookOrder(@RequestBody String payload, @RequestHeader Map map) {
try {
String secretKey = "xxxxxxxxxxx";
String HMAC_ALGORITHM = "HmacSHA256";
Mac mac = Mac.getInstance(HMAC_ALGORITHM);
SecretKeySpec secretKeySpec = new SecretKeySpec(secretKey.getBytes(), HMAC_ALGORITHM);
mac.init(secretKeySpec);
String signature = new String(Hex.encodeHex(mac.doFinal(payload.toString().getBytes())));
System.out.println("header hmac "+map.get("x-shopify-hmac-sha256").toString());
System.out.println("generated hmac "+signature);
System.out.println(map.get("x-shopify-hmac-sha256").toString().equals(signature));
return new ResponseEntity<Object>("{}", HttpStatus.OK);
}catch(Exception exception) {
exceptionService.saveExceptions(map.get("x-shopify-shop-domain").toString(), exception);
return new ResponseEntity<Object>("{}", HttpStatus.BAD_REQUEST);
}
}
答案 0 :(得分:0)
您可以创建两种计算HMAC的方法并进行检查
private static String calculateHmac(String message, String secret) throws NoSuchAlgorithmException, InvalidKeyException {
Mac hmac = Mac.getInstance(HMAC_ALGORITHM);
SecretKeySpec key = new SecretKeySpec(secret.getBytes(), HMAC_ALGORITHM);
hmac.init(key);
return Base64.encodeBase64String(hmac.doFinal(message.getBytes()));
}
private static Boolean checkHmac(String message, String hmac, String secret) throws InvalidKeyException, NoSuchAlgorithmException {
return hmac.equals(calculateHmac(message, secret));
}
checkHmac 重新运行是或否
使用此代码
private static Boolean verifyWebhook(HttpServletRequest request, final String secret) {
try {
String jsonString = IOUtils.toString(request.getInputStream(),"UTF-8");
String hmac = request.getHeader("X-Shopify-Hmac-Sha256");
return checkHmac(jsonString, hmac, secret);
} catch (IOException e) {
logger.info(e.getMessage());
} catch (InvalidKeyException e) {
logger.info(e.getMessage());
} catch (NoSuchAlgorithmException e) {
logger.info(e.getMessage());
}
return false;
}
您还可以看到https://community.shopify.com/c/Shopify-APIs-SDKs/Java-HMAC-authentication-verification/td-p/498131