理论就不说了,直接上代码。
下面是一个比对微信服务器发送过来的请求的工具类,前提是得导入一个jar包,commons-codec-1.9.jar,我用的是1.9的版本,直接去网上下载即可。
下载链接:http://central.maven.org/maven2/commons-codec/commons-codec/1.9/commons-codec-1.9.jar
package org.weixin.utils;
import java.util.Arrays;
import org.apache.commons.codec.digest.DigestUtils;
public class CheckUtil {
// 一定要和微信公总平台设置的token 值一致
private static final String token = "xxxxx";
public static boolean checkSignature(String signature, String timestamp,
String nonce) {
String[] arr = new String[] { token, timestamp, nonce };
// 排序
Arrays.sort(arr);
// 生成字符串
StringBuilder content = new StringBuilder();
for (int i = 0; i < arr.length; i++) {
content.append(arr[i]);
}
// sha1加密
String temp = getSHA1String(content.toString());
// 与微信传递过来的签名进行比较
return temp.equals(signature);
}
private static String getSHA1String(String data) {
// 使用commons codec生成sha1字符串
return DigestUtils.sha1Hex(data);
}
}
然后就是直接调用该工具类。
public class WeChatServlet extends HttpServlet {
/**
* 接收微信服务器发送的4个参数并返回echostr
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println("进入...");
// 接收微信服务器以Get请求发送的4个参数
String signature = request.getParameter("signature");
String timestamp = request.getParameter("timestamp");
String nonce = request.getParameter("nonce");
String echostr = request.getParameter("echostr");
PrintWriter out = response.getWriter();
// 调用工具了进行比对参数
if (CheckUtil.checkSignature(signature, timestamp, nonce)) {
System.out.println("比对成功!");
out.print(echostr); // 校验通过,原样返回echostr参数内容
}
}
/**
* 接收并处理微信客户端发送的请求
*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// 在这里处理微信公众号发来的各种请求,如关注事件、回复信息、点击事件等
System.out.println("接收到微信服务端发送的请求。");
}
}