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萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章