微信回调信息

微信回调信息

/**
 * 微信回调信息处理函数
 * @author hrcui 2017-3-14
 *
 */
public class WxInfoDeal {
	public static String processRequest(HttpServletRequest request,HttpServletResponse response){
		//微信加密签名
		String sReqMsgSig=request.getParameter("msg_signature");
		//时间戳
		String sReqTimeStamp=request.getParameter("timestamp");
		//随机数
		String sReqNonce=request.getParameter("nonce");
		//企业号配置参数
		String sToken=WxHelper.RESP_MSG_TOKEN;
		String sCorpID=WxHelper.CORPID;
		String sEncodingAESKey=WxHelper.RESP_MSG_EncodingAESKey;
		try {
			//接受信息,通过输入流获取密文数据
			ServletInputStream in=request.getInputStream();
			BufferedReader reader=new BufferedReader(new InputStreamReader(in));
			String sReqData="";
			String itemStr="";
			while(null!=(itemStr=reader.readLine())){
				sReqData+=itemStr;
			}
			//解密获取明文
			WXBizMsgCrypt wxcpt=new WXBizMsgCrypt(sToken,sEncodingAESKey,sCorpID);
			String sMsg=wxcpt.DecryptMsg(sReqMsgSig, sReqTimeStamp, sReqNonce, sReqData);
			
			System.out.println(sMsg);
			
			//处理xml
			DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance();
			DocumentBuilder db=dbf.newDocumentBuilder();
			StringReader sr=new StringReader(sMsg);
			InputSource is=new InputSource(sr);
			//生成doc
			Document doc=db.parse(is);
			//生成root节点
			Element root=doc.getDocumentElement();
			//获取MsgType
			NodeList nodelist_msgType=root.getElementsByTagName("MsgType");
			String recieveMsgType=nodelist_msgType.item(0).getTextContent();
			String content="";
			if("text".equals(recieveMsgType)){
				NodeList nodelist_msgcontent=root.getElementsByTagName("Content");
				String reqcontent=nodelist_msgcontent.item(0).getTextContent();
				JSONObject tulingsay=JSONObject.fromObject(TulingAPI.tuLingJiqiren(reqcontent));
				content=tulingsay.getString("text");
			}else if("location".equals(recieveMsgType)){
				//aaa
			}else if("event".equals(recieveMsgType)){
				NodeList nodelist_eventType=root.getElementsByTagName("Event");
				String eventType=nodelist_eventType.item(0).getTextContent();
				NodeList nodelist_eventKey=root.getElementsByTagName("EventKey");
				String eventKey=nodelist_eventKey.item(0).getTextContent();
				System.out.println("你"+eventType+"了"+eventKey);
			}
			//获取信息发送用户
			NodeList nodelist_fromUser=root.getElementsByTagName("FromUserName");
			String createuser=nodelist_fromUser.item(0).getTextContent();
			//生成时间戳
			String time=new Date().getTime()+"";
			String msg_type="text";
			//生成返回消息xml明文
			RespTextMsg tmsg=new RespTextMsg(createuser, sCorpID, Long.valueOf(time), msg_type, content);
			String sRespData=tmsg.toXMLStr();
			//生成返回消息
			String sEncryptMsg=wxcpt.EncryptMsg(sRespData, time, sReqNonce);
			PrintWriter out =response.getWriter();
			out.write(sEncryptMsg);
			out.flush();
			out.close();
		} catch (Exception e) {
			// TODO: handle exception
		}
		return "";
	}
}





public class DealPageServlet extends HttpServlet {

	/**
	 * The doGet method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to get.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		String jsapi_ticket=JSAPITicketCache.getJsapiTicketFromWx(WxHelper.CORPID, WxHelper.RESP_MSG_SECRET);
		String url=request.getRequestURL().toString();
		if(request.getQueryString()!=null){
			url+="?"+request.getQueryString();
		}
//		"http://" + request.getServerName() //服务器地址  
//        + ":"   
//        + request.getServerPort()           //端口号  
//        + request.getContextPath()      //项目名称  
//        + request.getServletPath()      //请求页面或其他地址  
//    + "?" + (request.getQueryString());
		System.out.println(url);
		Map<String, String> ret=WxHelper.sign(jsapi_ticket, url);
		request.setAttribute("corpId", WxHelper.CORPID);
		request.setAttribute("time", ret.get("timestamp"));
		request.setAttribute("nonceStr", ret.get("nonceStr"));
		request.setAttribute("str1", ret.get("signature"));
		
		System.out.println("url:"+url);
		System.out.println("jsapi_ticket:"+jsapi_ticket);
		System.out.println("time:"+ret.get("timestamp"));
		System.out.println("nonceStr:"+ret.get("nonceStr"));
		System.out.println("\nsignature:"+ret.get("signature"));
		request.getRequestDispatcher("JSP/index.jsp").forward(request, response);
	}

	/**
	 * The doPost method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to post.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}

}








public class ConnWechatServlet extends HttpServlet {
	private String token = "0L05Kz3mMhgJQWzEmmMvnH";  //需应用与后台一致  
    private String encodingAESKey = "avM7pACaJ4XJsoWdNcxGyPTNTIcHnANObwuNzxSDO5R";  //自动生成密钥  
    private String corpId = "wx9e6b5f7e6b9f86a2"; //企业号ID    
    private static final long serialVersionUID = 4440739483644821986L;
	/**
	 * The doGet method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to get.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		
		
	    // 微信加密签名(微信传递过来的参数,我们只需要获取)  
        String msg_signature = request.getParameter("msg_signature");    
        // 时间戳(微信传递过来的参数,我们只需要获取)  
        String timestamp = request.getParameter("timestamp");    
        // 随机数(微信传递过来的参数,我们只需要获取)  
        String nonce = request.getParameter("nonce");    
        // 随机字符串(微信传递过来的参数,我们只需要获取)  
        String echostr = request.getParameter("echostr");    
            //打印看看我们自己获取到的地址是怎么样的。  
        System.out.println("request=" + request.getRequestURL());    
        
        PrintWriter out = response.getWriter();    
        // 通过检验signature对请求进行校验,若校验成功则原样返回echostr,表示接入成功,否则接入失败    
        String result = null;    
        try {    
             WXBizMsgCrypt wxcpt = new WXBizMsgCrypt(token,encodingAESKey,corpId);    
             result = wxcpt.VerifyURL(msg_signature, timestamp, nonce, echostr);    
        } catch (AesException e) {    
             e.printStackTrace();    
        }    
        if (result == null) {    
             result = token;  
        }  
  
        String str = msg_signature+" "+timestamp+" "+nonce+" "+echostr;  
        System.out.println("Exception:"+result+" "+ request.getRequestURL()+" "+"FourParames:"+str);  
   
        out.print(result);  
        out.close();    
        out = null;
	}

	/**
	 * The doPost method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to post.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		WxInfoDeal.processRequest(request, response);
	}

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值