/**
* 微信验证
* 收/发送信息
*/
@RequestMapping("serial")
@ResponseBody
public void serial(HttpServletRequest request, HttpServletResponse response) throws IOException {
// 将请求、响应的编码均设置为UTF-8(防止中文乱码)
request.setCharacterEncoding("UTF-8"); //微信服务器POST消息时用的是UTF-8编码,在接收时也要用同样的编码,否则中文会乱码;
response.setCharacterEncoding("UTF-8"); //在响应消息(回复消息给用户)时,也将编码方式设置为UTF-8,原理同上;
boolean isGet = request.getMethod().toLowerCase().equals("get");
PrintWriter out = response.getWriter();
String signature = request.getParameter("signature"); // 随机字符串
String echostr = request.getParameter("echostr"); // 时间戳
String timestamp = request.getParameter("timestamp"); // 随机数
String nonce = request.getParameter("nonce");
String result = "";
// 确认请求来至微信
if (SignUtil.checkSignature(ConstantWeiXin.TOKEN, signature, timestamp, nonce)) {
{
/** 读取接收到的xml消息 */
StringBuffer sb = new StringBuffer();
InputStream is = request.getInputStream();
InputStreamReader isr = new InputStreamReader(is, "UTF-8");
BufferedReader br = new BufferedReader(isr);
String s = "";
while ((s = br.readLine()) != null) {
sb.append(s);
}
String xml = sb.toString(); //次即为接收到微信端发送过来的xml数据
/** 判断是否是微信接入激活验证,只有首次接入验证时才会收到echostr参数,此时需要把它直接返回 */
if (echostr != null && echostr.length() > 1) {
result = echostr;
} else {
//正常的微信处理流程
result = new WechatProcess().processWechatMag(xml);
}
response.setContentType("application/xml;charset=UTF-8");
out.print(result);
System.out.println("说的什么" + result);
}
}
}
验证签名
/**
* 验证签名
*
* @param token 微信服务器token,在env.properties文件中配置的和在开发者中心配置的必须一致
* @param signature 微信服务器传过来sha1加密的证书签名
* @param timestamp 时间戳
* @param nonce 随机数
* @return
*/
public static boolean checkSignature(String token,String signature, String timestamp, String nonce) {
String[] arr = new String[] { token, timestamp, nonce };
// 将token、timestamp、nonce三个参数进行字典序排序
Arrays.sort(arr);
// 将三个参数字符串拼接成一个字符串进行sha1加密
String tmpStr = SHA1.encode(arr[0] + arr[1] + arr[2]);
// 将sha1加密后的字符串可与signature对比,标识该请求来源于微信
return tmpStr != null ? tmpStr.equals(signature.toUpperCase()) : false;
}