配置URL驗(yàn)證地址
微信服務(wù)器會(huì)將請(qǐng)求發(fā)送到配置的地址, 地址必須是80端口, 可使用花生殼等工具
驗(yàn)證參數(shù)
signature: 微信加密簽名液荸,signature結(jié)合了開發(fā)者填寫的token參數(shù)和請(qǐng)求中的timestamp參數(shù)、nonce參數(shù)脱篙。
timestamp: 時(shí)間戳
nonce: 隨機(jī)數(shù)
echostr: 隨機(jī)字符串
開發(fā)者通過檢驗(yàn)signature對(duì)請(qǐng)求進(jìn)行校驗(yàn)(下面有校驗(yàn)方式)娇钱。若確認(rèn)此次GET請(qǐng)求來(lái)自微信服務(wù)器,請(qǐng)?jiān)瓨臃祷豦chostr參數(shù)內(nèi)容绊困,則接入生效文搂,成為開發(fā)者成功,否則接入失敗秤朗。加密/校驗(yàn)流程如下:
1 將token煤蹭、timestamp、nonce三個(gè)參數(shù)進(jìn)行字典序排序
2 將三個(gè)參數(shù)字符串拼接成一個(gè)字符串進(jìn)行sha1加密
3 開發(fā)者獲得加密后的字符串可與signature對(duì)比取视,標(biāo)識(shí)該請(qǐng)求來(lái)源于微信
接入配置
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
String signature = req.getParameter("signature");
String timestamp = req.getParameter("timestamp");
String nonce = req.getParameter("nonce");
String echostr = req.getParameter("echostr");
PrintWriter out = resp.getWriter();
if(CheckUtil.checkSignature(signature, timestamp, nonce)){
System.out.println("校驗(yàn)成功");
out.print(echostr);
}
}
sha1加密工具類####
private static final String token = "weixintoken";
public static boolean checkSignature(String signature, String timestamp, String nonce){
String[] arr = new String[]{token,timestamp,nonce};
//排序
Arrays.sort(arr);
//生成字符串
StringBuffer content = new StringBuffer();
for(int i=0;i<arr.length;i++){
content.append(arr[i]);
}
//sha1加密
String temp = getSha1(content.toString());
return temp.equals(signature);
}
因?yàn)橛玫氖莝ervlet 在web.xml中添加mapping配置
<servlet>
<servlet-name>weixinServlet</servlet-name>
<servlet-class>com.xxxx.xxxx.controller.WeixinServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>weixinServlet</servlet-name>
<url-pattern>/wechat/portal</url-pattern>
</servlet-mapping>