这里写自定义目录标题
微信公众号Token校验
记住这个要对应
代码编写
/**
* 微信通知接口
* @param
* @return
*/
@GetMapping("/notify")
public String getNotifyResult(@RequestParam("signature") String signature,
@RequestParam("timestamp") String timestamp,
@RequestParam("nonce") String nonce,
@RequestParam("echostr") String echostr){
log.info("------------开始校验----------");
log.info("signature:{}",signature);
log.info("timestamp:{}",timestamp);
log.info("nonce:{}",nonce);
log.info("echostr:{}",echostr);
// 将token、timestamp、nonce三个参数进行字典序排序 并拼接为一个字符串
String sortStr = sort(TOKEN,timestamp,nonce);
String mySignature = getSha1(sortStr);
// 字符串加密
log.info("密文:{}",mySignature);
if(signature.equals(mySignature)){
log.info("----nonce---verifyPass--------------------------------:{}", nonce);
}else {
log.info("---------------verifyDown--------------------------------");
}
log.info("加密的echostr:{}",echostr);
return echostr;
}
排序 :
/**
* 参数排序
*
* @param token
* @param timestamp
* @param nonce
* @return
*/
private String sort(String token, String timestamp, String nonce) {
String[] strArray = {token, timestamp, nonce};
Arrays.sort(strArray);
StringBuilder sb = new StringBuilder();
for (String str : strArray) {
sb.append(str);
}
return sb.toString();
}
解密:
/**
* 字符串进行shal加密
* @param str
* @return
*/
//sha1加密
public static String getSha1(String str) {
if (null == str || 0 == str.length()) {
return null;
}
char[] hexDigits = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'a', 'b', 'c', 'd', 'e', 'f'};
try {
MessageDigest mdTemp = MessageDigest.getInstance("SHA1");
mdTemp.update(str.getBytes("UTF-8"));
byte[] md = mdTemp.digest();
int j = md.length;
char[] buf = new char[j * 2];
int k = 0;
for (int i = 0; i < j; i++) {
byte byte0 = md[i];
buf[k++] = hexDigits[byte0 >>> 4 & 0xf];
buf[k++] = hexDigits[byte0 & 0xf];
}
return new String(buf);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return "";
}
private String notifyAfter(@RequestBody NotifyDto notifyDto){
return weChatNotifyService.getNotifyResult(notifyDto);
}
最近在搞公众号这块,一直token校验不过,遇到的问题主要是url,要注意自己的地址是Https还是http,被这个搞了半天,记录一下