验证代码:
CheckServiceServlet.java
/**
* Servlet implementation class CheckService
* Java微信服务器验证
*/
public class CheckServiceServlet extends HttpServlet {
private static final long serialVersionUID = 7783989149982325969L;
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//获取参数
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)) {
out.print(echostr);
}
}
}
工具类:
CheckUtil.java
public class CheckUtil {
private static final String Token = "weixintoken";
/**
* 1)将token、timestamp、nonce三个参数进行字典序排序
* 2)将三个参数字符串拼接成一个字符串进行sha1加密
* 3)开发者获得加密后的字符串可与signature对比,标识该请求来源于微信
* @param signature 微信加密签名,signature结合了开发者填写的token参数和请求中的timestamp参数、nonce参数。
* @param timestamp 时间戳
* @param nonce 随机数
* @return
*/
public static boolean checkSignature(String signature, String timestamp, String nonce) {
String[] arr = new String[] { Token, timestamp, nonce };
// 1、排序
Arrays.sort(arr);
// 2、生成字符串
StringBuffer sb = new StringBuffer();
for (int i = 0; i
sb.append(arr[i]);
}
// sha1加密
String temp = SHA1.sha1(sb.toString());
return temp.equals(signature);
}
}
web配置:
web.xml
CheckService
CheckService
com.mg.weixin.servlet.CheckServiceServlet
CheckService
/check.do
项目结构:
请求URL:
http://api.xxx.com/weixin/check.do