公众号开发——基本配置
提交信息后,微信服务器将发送GET请求到填写的URL上,GET请求携带四个参数:
signature:微信加密签名,signature结合了开发者填写的token参数和请求中的timestamp参数、nonce参数。
timestamp:时间戳
nonce:随机数
echostr:随机字符串
加密/校验流程如下:
1. 将token、timestamp、nonce三个参数进行字典序排序
2. 将三个参数字符串拼接成一个字符串进行sha1加密
3. 开发者获得加密后的字符串可与signature对比,标识该请求来源于微信
代码:
public void doGet(HttpServletRequest request, HttpServletResponse response) throws Exception{
PrintWriter out = null;
try {
String signature = request.getParameter("signature");
String timestamp = request.getParameter("timestamp");
String nonce = request.getParameter("nonce");
String echostr = request.getParameter("echostr");
if(checkSignature(signature, timestamp, nonce)){
out = response.getWriter();
out.print(echostr);
out.flush();
out.close();
}
} catch (Exception e) {
e.printStackTrace();
} finally{
if(out!=null)
out.close();
}
}
//效验
public boolean checkSignature(String signature, String timestamp, String nonce) throws Exception{
String token = "eOpenCloud";
String [] arrs = new String[]{token, timestamp, nonce};
//排序
Arrays.sort(arrs);
//生成字符串
StringBuffer buf = new StringBuffer();
for(String arr : arrs){
buf.append(arr);
}
//sha1加密
String temp = getSha1(buf.toString());
return signature.equals(temp);
}
//加密
public String getSha1(String str) throws Exception{
try {
if(str == null || "".equals(str))
return null;
char[] hexDigits = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
MessageDigest mdTemp = MessageDigest.getInstance("SHA1");
mdTemp.update(str.getBytes("UTF-8"));
byte[] md = mdTemp.digest();
int j = md.length;
char[] buf = new char[j * 2];
int k = 0;
for (int i = 0; i < j; i++) {
byte byte0 = md[i];
buf[k++] = hexDigits[byte0 >>> 4 & 0xf];
buf[k++] = hexDigits[byte0 & 0xf];
}
return new String(buf);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}