映射地址
域名/wechat/security
接口
@Controller
@RequestMapping("/wechat")
public class WechatSecurity {
private static Logger logger = Logger.getLogger(WechatSecurity.class);
/**
*
* @Description: 用于接收 get 参数,返回验证参数
* @param @param request
* @param @param response
* @param @param signature
* @param @param timestamp
* @param @param nonce
* @param @param echostr
*/
@RequestMapping(value = "security", method = RequestMethod.GET)
public void doGet(
HttpServletRequest request,
HttpServletResponse response,
@RequestParam(value = "signature", required = true) String signature,
@RequestParam(value = "timestamp", required = true) String timestamp,
@RequestParam(value = "nonce", required = true) String nonce,
@RequestParam(value = "echostr", required = true) String echostr) {
try {
if (SignUtil.checkSignature(signature, timestamp, nonce)) {
PrintWriter out = response.getWriter();
out.print(echostr);
out.close();
} else {
logger.info("这里存在非法请求!");
}
} catch (Exception e) {
logger.error(e, e);
}
}
@RequestMapping(value = "security", method = RequestMethod.POST)
// post 方法用于接收微信服务端消息
public void DoPost() {
System.out.println("这是 post 方法!");
}
}
util
public class SignUtil {
// 与接口配置信息中的 Token 要一致
private static String token = "wechat";
/**
* 验证签名
* @param signature
* @param timestamp
* @param nonce
* @return
*/
public static boolean checkSignature(String signature, String timestamp, String nonce) {
String[] arr = new String[] { token, timestamp, nonce };
// 将 token、timestamp、nonce 三个参数进行字典序排序
Arrays.sort(arr);
StringBuilder content = new StringBuilder();
for (int i = 0; i < arr.length; i++) {
content.append(arr[i]);
}
MessageDigest md = null;
String tmpStr = null;
try {
md = MessageDigest.getInstance("SHA-1");
// 将三个参数字符串拼接成一个字符串进行 sha1 加密
byte[] digest = md.digest(content.toString().getBytes());
tmpStr = byteToStr(digest);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
content = null;
// 将 sha1 加密后的字符串可与 signature 对比,标识该请求来源于微信
return tmpStr != null ? tmpStr.equals(signature.toUpperCase()) : false;
}
/**
* 将字节数组转换为十六进制字符串
* @param byteArray
* @return
*/
private static String byteToStr(byte[] byteArray) {
String strDigest = "";
for (int i = 0; i < byteArray.length; i++) {
strDigest += byteToHexStr(byteArray[i]);
}
return strDigest;
}
/**
* 将字节转换为十六进制字符串
* @param mByte
* @return
*/
private static String byteToHexStr(byte mByte) {
char[] Digit = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
char[] tempArr = new char[2];
tempArr[0] = Digit[(mByte >>> 4) & 0X0F];
tempArr[1] = Digit[mByte & 0X0F];
String s = new String(tempArr);
return s;
}
}