Java搭建微信公眾號(hào)的服務(wù)器配置
- 代碼文件:
package com.dhrtec.utils;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
/**
* Created by l on 2018/10/17.
*/
public class SignUtil {
private static String token = Global.getConfig("WeChatToken");// 與微信公眾號(hào)上的token一致
/**
* 校驗(yàn)簽名
* @param signature 簽名
* @param timestamp 時(shí)間戳
* @param nonce 隨機(jī)數(shù)
* @return 布爾值
*/
public static boolean checkSignature(String signature,String timestamp,String nonce){
String checktext = null;
if (null != signature) {
//對(duì)ToKen,timestamp,nonce 按字典排序
String[] paramArr = new String[]{token,timestamp,nonce};
Arrays.sort(paramArr);
//將排序后的結(jié)果拼成一個(gè)字符串
String content = paramArr[0].concat(paramArr[1]).concat(paramArr[2]);
try {
MessageDigest md = MessageDigest.getInstance("SHA-1");
//對(duì)接后的字符串進(jìn)行sha1加密
byte[] digest = md.digest(content.toString().getBytes());
checktext = byteToStr(digest);
} catch (NoSuchAlgorithmException e){
e.printStackTrace();
}
}
//將加密后的字符串與signature進(jìn)行對(duì)比
return checktext !=null ? checktext.equals(signature.toUpperCase()) : false;
}
/**
* 將字節(jié)數(shù)組轉(zhuǎn)化我16進(jìn)制字符串
* @param byteArrays 字符數(shù)組
* @return 字符串
*/
private static String byteToStr(byte[] byteArrays){
String str = "";
for (int i = 0; i < byteArrays.length; i++) {
str += byteToHexStr(byteArrays[i]);
}
return str;
}
/**
* 將字節(jié)轉(zhuǎn)化為十六進(jìn)制字符串
* @param myByte 字節(jié)
* @return 字符串
*/
private static String byteToHexStr(byte myByte) {
char[] Digit = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
char[] tampArr = new char[2];
tampArr[0] = Digit[(myByte >>> 4) & 0X0F];
tampArr[1] = Digit[myByte & 0X0F];
String str = new String(tampArr);
return str;
}
}
調(diào)用方法:
@RequestMapping(value = "/serial", method = RequestMethod.GET)
public String checkSign(HttpServletRequest request,HttpServletResponse response){
String signature=request.getParameter("signature");
String timestamp=request.getParameter("timestamp");
String nonce=request.getParameter("nonce");
String echostr=request.getParameter("echostr");
System.out.println("本身"+signature);
if(SignUtil.checkSignature(signature,timestamp,nonce)) {
return echostr;
}
return null;
}