公眾號開發——基本配置
提交資訊後,微信伺服器將傳送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;
}