文档首页/
云商店/
接入指南/
商品接入相关接口/
SaaS类商品接入指南 V1.0(已下线)/
通用和自服务SaaS类商品接入指南 V1.0/
代码示例(Java)/
ISV Server验证所有的post body通知请求
更新时间:2022-10-21 GMT+08:00
ISV Server验证所有的post body通知请求
代码调用如下图所示。
/** * 校验通知消息的合法性 * @param RequestBody requestBody请求体 * @param request http请求通知消息 * @param accessKey 接入码 * @return 验证结果 */ public static boolean verificateRequestParams(@RequestBody RequestBody requestBody, javax.servlet.http.HttpServletRequest request, String accessKey) { // BeanUtils来自包commons-beanutils,其版本必须要>=1.9.4, // 否则需要执行paramsMap.remove("class"),移除参数中不存在的内容 Map<String, String> paramsMap = BeanUtils.describe(requestBody); String timeStamp = paramsMap.get("timeStamp"); String authToken = request.getHeader("authToken"); //对剩下的参数进行排序,拼接成加密内容 Map<String, String> sortedMap = new TreeMap<String, String>(); sortedMap.putAll(paramsMap); StringBuffer strBuffer = new StringBuffer(); Set<String> keySet = sortedMap.keySet(); Iterator<String> iter = keySet.iterator(); while (iter.hasNext()) { String key = iter.next(); String value = sortedMap.get(key); if (StringUtils.isBlank(value)) { continue; } strBuffer.append("&").append(key).append("=").append(value); } //修正消息体,去除第一个参数前面的& String reqParams = strBuffer.toString().substring(1); String key = accessKey + timeStamp; String signature = null; try { signature = generateResponseBodySignature(key, reqParams); } catch (InvalidKeyException | NoSuchAlgorithmException | IllegalStateException | UnsupportedEncodingException e) { // TODO Auto-generated catch block } return authToken.equals(signature); }
/** * 生成http响应消息体签名示例Demo * @param key 用户在isv console分配的accessKey,请登录后查看 * @param body http响应的报文 * @return 加密结果 * @throws InvalidKeyException * @throws NoSuchAlgorithmException * @throws IllegalStateException * @throws UnsupportedEncodingException */ public static String generateResponseBodySignature(String key, String body) throws InvalidKeyException, NoSuchAlgorithmException, IllegalStateException, UnsupportedEncodingException { return base_64(hmacSHA256(key, body)); }
/** * * hamcSHA256加密算法 * @param macKey 秘钥key * @param macData 加密内容-响应消息体 * @return 加密密文 * @throws NoSuchAlgorithmException * @throws InvalidKeyException * @throws IllegalStateException * @throws UnsupportedEncodingException */ public static byte[] hmacSHA256(String macKey, String macData) throws NoSuchAlgorithmException, InvalidKeyException, IllegalStateException, UnsupportedEncodingException { SecretKeySpec secret = new SecretKeySpec(macKey.getBytes(), "HmacSHA256"); Mac mac = Mac.getInstance("HmacSHA256"); mac.init(secret); byte[] doFinal = mac.doFinal(macData.getBytes("UTF-8")); return doFinal; }
/** * * 字节数组转字符串 * @param bytes 字节数组 * @return 字符串 */ public static String base_64(byte[] bytes) { return new String(Base64.encodeBase64(bytes)); }
父主题: 代码示例(Java)