问题描述
有人可以帮助我如何在 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);
    }
}
 
 1楼
您可以创建两种计算 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 返回true 或 false
使用此代码
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;  
}
 
  你也可以看到