java servlet接收微信公众号消息

公众号消息接收与企业号略有区别,主要在token验证上。

token验证算法不再由sdk提供,需要自己实现

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
    	String sEchoStr=null; //需要返回的明文
		try {
			AppInfo app = WeiXinConfiger.getAppConfig(request);
			String sVerifyEchoStr = request.getParameter("echostr");	
			sEchoStr=sVerifyEchoStr;
			if(app.getSafeMode()){
				String sVerifyMsgSig = request.getParameter("signature");
				String sVerifyTimeStamp = request.getParameter("timestamp");
				String sVerifyNonce = request.getParameter("nonce");
				String[] str = { app.getToken(), sVerifyTimeStamp, sVerifyNonce };
			    Arrays.sort(str); // 字典序排序
			    String bigStr = str[0] + str[1] + str[2];
			    String digest = sha1(bigStr).toLowerCase();// SHA1加密
			    assert(sVerifyMsgSig.equals(digest));
			    if(!sVerifyMsgSig.equals(digest)){
			    	sEchoStr=null;
			    }
			}
		} catch (AesException e1) {
			sEchoStr="ERR: "+e1.getCode()+ "\n\n";
			e1.printStackTrace();		
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		
		PrintWriter pw=response.getWriter();
		pw.print(sEchoStr);
		pw.close();
	}
public static final String sha1(String data) throws NoSuchAlgorithmException {
		MessageDigest md = MessageDigest.getInstance("SHA1");
		 md.update(data.getBytes());
		StringBuffer buf = new StringBuffer();
		 byte[] bits = md.digest();
		for(int i=0;i<bits.length;i++){
		int a = bits[i];
		if(a<0) a+=256;
		if(a<16) buf.append("0");
		buf.append(Integer.toHexString(a));
		}
		return buf.toString();
	}

接收消息时需要根据配置选择安全模式或普通模式


protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		//获得请求参数
		String msgSig =  request.getParameter("msg_signature");
		String timeStamp = request.getParameter("timestamp");
		String nonce = request.getParameter("nonce");
		//获得post提交的数据
		BufferedReader br=new BufferedReader(new InputStreamReader(request.getInputStream()));
	
		StringBuffer sb=new StringBuffer();
		String str=null;
		while((str=br.readLine())!=null){
			sb.append(str);
		}	
		String sReqData = sb.toString();
		String sEchoStr=null;
		try {
			AppInfo app = WeiXinConfiger.getAppConfig(request);
			if(app.getSafeMode()){//如果配置了需要安全模式,则需要解码
				WXBizMsgCrypt wxcpt = new WXBizMsgCrypt(app.getToken(), app.getEncodingAesKey(), app.getAppId());
				String sMsg = wxcpt.decryptMsg(msgSig, timeStamp, nonce, sReqData);		
				//调用处理函数
				sEchoStr=RequestHandler.doHandle(sMsg,app,request,response);
				sEchoStr = wxcpt.encryptMsg(sEchoStr, timeStamp, nonce);
			}else{//如果配置了不使用安全模式,则直接处理后扔回去
				//调用处理函数
				sEchoStr=RequestHandler.doHandle(sReqData,app,request,response);
			}
		} catch (AesException e1) {
			sEchoStr="ERR: "+e1.getCode()+ "\n\n";
			e1.printStackTrace();
		} catch (ParserConfigurationException e) {
			sEchoStr="ERR: "+AesException.ParseXmlError+ "\n\n";
			e.printStackTrace();
		} catch (SAXException e) {
			sEchoStr="ERR: "+AesException.ParseXmlError+ "\n\n";
			e.printStackTrace();
		}
		response.getWriter().print(sEchoStr);
	}


发布了37 篇原创文章 · 获赞 57 · 访问量 12万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章