纯JSP实现简单微信开发后台
2016-01-29 16:28
495 查看
http://my.oschina.net/u/1387995/blog/172202?fromerr=zcnZ0erv
%@ page import="java.net.*" % %@ page import="java.math.*" % %@ page import="java.io.*" % %@ page import="java.text.*"% %@page import="java.util.Date"% %@page import="org.dom4j.Element"% %@page import="org.dom4j.DocumentHelper"% %@page import="org.dom4j.Document"% %@page import="java.io.IOException"% %@page import="java.io.InputStreamReader"% %@page import="java.io.BufferedReader"% %@page import="java.io.Reader"% %@page import="java.security.MessageDigest"% %@page import="java.util.Arrays"% %@page import="java.util.ArrayList"% %@page import="java.util.Collections"% %@page import="java.util.List"% %@page import="java.util.regex.Matcher"% %@page import="java.util.regex.Pattern"% %@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"% <% //WeiXinHandler为内部类不能使用非final类型的对象 final String TOKEN=“daniuco”;//此处填写自己的TOKEN参数,见开发模式 final HttpServletRequest final_request=request; final HttpServletResponse final_response=response; %> <% class WeiXinHandler{ public void valid(){ String echostr=final_request.getParameter(“echostr”); if(null==echostr||echostr.isEmpty()) { responseMsg(); }else{ if(this.checkSignature()) { this.print(echostr); }else{ this.print("error"); } } } //自动回复内容 public void responseMsg() { String postStr=null; try{ postStr=this.readStreamParameter(final_request.getInputStream()); //System.out.print(postStr); }catch(Exception e) { e.printStackTrace(); } //System.out.println(postStr); if (null!=postStr&&!postStr.isEmpty()) { Document document=null; try{ document = DocumentHelper.parseText(postStr); }catch(Exception e){ e.printStackTrace(); } if(null==document) { this.print(““); return; } Element root=document.getRootElement(); String fromUsername = root.elementText(“FromUserName”); String toUsername = root.elementText(“ToUserName”); String keyword = root.elementTextTrim(“Content”); long longTime = new Date().getTime(); String time = longTime/1000 +““; String msgType = root.elementText(“MsgType”); String event = root.elementText(“Event”); String textTpl = “ “+ “ %1$s “+ “ %2$s “+ “ %3$s “+ “ %4$s “+ “ %5$s “+ “ 0 “+ “ “; String htmlTpl = “ “+ “ %1$s “+ “ %2$s “+ “ %3$s “+ “ %4$s ” + "[%5$s]" + "</Articles></xml>"; //公用帮助文档 String helpHtml = “\n任何时候,回复"help"或者"帮助"或者"?"三者之一获取最新使用手册。\n\n分类信息([c:新闻],[c:公告],[c:研报]等)\n历史信息([2013-10-05]:某天信息,[d:9]:过去9天之内的信息,[d:-9]:过去9天之前的信息,默认查询范围10天之内)“; if(null!=msgType && !msgType.equals(““)) { /** *事件类型 */ if(msgType.equals(“event”) && event.equals(“subscribe”)) { //订阅 String subscribeHtml = ""; msgType = "news"; //String helpHtml = "\n任何时候,回复\"help\"或者\"帮助\"二者之一获取最新使用手册。\n分类信息(c:新闻,c:公告,c:研报)\n历史信息([2013-10-05]:某天信息,[d:9]:过去9天之内的信息,[d:-9]:过去9天之前的信息,默认查询范围10天之内)"; String helpPicUrl = "http://www.daniu.co/images/weixin/finance_travel_640_320.jpg"; String helpContentUrl = ""; String helpResults = "<item><Title><![CDATA[欢迎开启财富新旅程]]></Title><Description><![CDATA[" + helpHtml + "]]></Description><PicUrl><![CDATA[" + helpPicUrl +"]]></PicUrl><Url><![CDATA[" + helpContentUrl + "]]></Url></item>"; helpResults = "<ArticleCount>1</ArticleCount><Articles>"+ helpResults; subscribeHtml = helpResults; //System.out.println(subscribeHtml); String resultStr = htmlTpl.format(htmlTpl, fromUsername, toUsername, time, msgType, subscribeHtml); this.print(resultStr); } if(msgType.equals(“event”) && event.equals(“unsubscribe”)) { //退订 String subscribeHtml = ""; msgType = "news"; helpHtml = "\n感谢关注daniuco\n\n你订或不订,我都在这里,勤勤恳恳... ..."; String helpPicUrl = "http://www.daniu.co/images/weixin/finance_640_320.png"; String helpContentUrl = ""; String helpResults = "<item><Title><![CDATA[感谢关注金融互联网]]></Title><Description><![CDATA[" + helpHtml + "]]></Description><PicUrl><![CDATA[" + helpPicUrl +"]]></PicUrl><Url><![CDATA[" + helpContentUrl + "]]></Url></item>"; helpResults = "<ArticleCount>1</ArticleCount><Articles>"+ helpResults; subscribeHtml = helpResults; //System.out.println(subscribeHtml); String resultStr = htmlTpl.format(htmlTpl, fromUsername, toUsername, time, msgType, subscribeHtml); this.print(resultStr); } } if(null!=keyword&&!keyword.equals(““)) { /* *回复文本信息 String msgType = “text”; String contentStr = “系统在开发过程中,敬请期待!“; if(keyword.equals(“help”) || keyword.equals(“帮助”)) {//使用手册 contentStr = contentStr + "\n使用手册正在设计中,您可以在以后使用过程中,回复\"help\"或者\"帮助\"二者之一获取最新使用手册。"; } //Autonomy Search contentStr = contentStr + “\n===自动推送测试内容===\n”+ AutonomySearch(keyword); String resultStr = textTpl.format(textTpl, fromUsername, toUsername, time, msgType, contentStr); /* 回复文本信息结束 */ /* 回复图文信息,最多6条(微信支持10条) */ msgType = “news”; String contentHtml = ““;//用户请求关键字 if(keyword.equals(“help”) || keyword.equals(“帮助”) || keyword.equals(“?“) || keyword.equals(“?“)) {//使用手册 //String helpHtml = "\n任何时候,回复\"help\"或者\"帮助\"二者之一获取最新使用手册。\n分类信息(c:新闻,c:公告,c:研报)\n历史信息([2013-10-05]:某天信息,[d:9]:过去9天之内的信息,[d:-9]:过去9天之前的信息,默认查询范围10天之内)"; String helpPicUrl = "http://www.daniu.co/images/weixin/help_640_320.png"; String helpContentUrl = ""; String helpResults = "<item><Title><![CDATA[由大牛网提供的财富新体验]]></Title><Description><![CDATA[" + helpHtml + "]]></Description><PicUrl><![CDATA[" + helpPicUrl +"]]></PicUrl><Url><![CDATA["+ helpContentUrl +"]]></Url></item>"; helpResults = "<ArticleCount>1</ArticleCount><Articles>"+ helpResults; String resultStr = htmlTpl.format(htmlTpl, fromUsername, toUsername, time, msgType, helpResults); this.print(resultStr); }else {//智能回复 String reqTpl = "<xml><ToUserName><![CDATA[%1$s]]></ToUserName><FromUserName><![CDATA[%2$s]]></FromUserName><CreateTime>%3$s</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[" + keyword + "]]></Content><MsgId>5937584354468300645</MsgId><OpenId>daniuco</OpenId></xml>"; String reqStr = reqTpl.format(reqTpl,toUsername, fromUsername, time);//将原始请求信息发送到智能引擎,注意toUsername,fromUsername位置 contentHtml = getRemoteXML(reqStr); // System.out.print(contentHtml); //返回信息到微信服务器 this.print(contentHtml); } //返回信息到微信服务器 //this.print(resultStr); }else{ this.print(“Input something…“); } }else { this.print(““); } } //微信接口验证 public boolean checkSignature(){ String signature = final_request.getParameter(“signature”); String timestamp = final_request.getParameter(“timestamp”); String nonce = final_request.getParameter(“nonce”); String token=TOKEN; String[] tmpArr={token,timestamp,nonce}; Arrays.sort(tmpArr); String tmpStr=this.ArrayToString(tmpArr); tmpStr=this.SHA1Encode(tmpStr); if(tmpStr.equalsIgnoreCase(signature)){ return true; }else{ return false; } } //向请求端发送返回数据 public void print(String content){ try{ final_response.getWriter().print(content); final_response.getWriter().flush(); final_response.getWriter().close(); }catch(Exception e){ } } //数组转字符串 public String ArrayToString(String [] arr){ StringBuffer bf = new StringBuffer(); for(int i = 0; i < arr.length; i++){ bf.append(arr[i]); } return bf.toString(); } //sha1加密 public String SHA1Encode(String sourceString) { String resultString = null; try { resultString = new String(sourceString); MessageDigest md = MessageDigest.getInstance(“SHA-1”); resultString = byte2hexString(md.digest(resultString.getBytes())); } catch (Exception ex) { } return resultString; } public final String byte2hexString(byte[] bytes) { StringBuffer buf = new StringBuffer(bytes.length * 2); for (int i = 0; i < bytes.length; i++) { if (((int) bytes[i] & 0xff) < 0x10) { buf.append("0"); } buf.append(Long.toString((int) bytes[i] & 0xff, 16)); } return buf.toString().toUpperCase(); } //从输入流读取post参数 public String readStreamParameter(ServletInputStream in){ StringBuilder buffer = new StringBuilder(); BufferedReader reader=null; try{ reader = new BufferedReader(new InputStreamReader(in)); String line=null; while((line = reader.readLine())!=null){ buffer.append(line); } }catch(Exception e){ e.printStackTrace(); }finally{ if(null!=reader){ try { reader.close(); } catch (IOException e) { e.printStackTrace(); } } } return buffer.toString(); } }%> <%! public String getRemoteXML(String reqStr) { HttpURLConnection url_con = null; String responseContent = null; String daniucoUrl = "http://www.daniu.co/openapi"; try { URL url = new URL(daniucoUrl); url_con = (HttpURLConnection) url.openConnection(); url_con.setRequestMethod("POST"); url_con.setDoOutput(true); byte[] b = reqStr.getBytes(); url_con.getOutputStream().write(b, 0, b.length); url_con.getOutputStream().flush(); url_con.getOutputStream().close(); InputStream in = url_con.getInputStream(); BufferedReader rd = new BufferedReader(new InputStreamReader(in, "utf-8")); String tempLine = rd.readLine(); StringBuffer tempStr = new StringBuffer(); String crlf=System.getProperty("line.separator"); while (tempLine != null) { tempStr.append(tempLine); tempStr.append(crlf); tempLine = rd.readLine(); } responseContent = tempStr.toString(); rd.close(); in.close(); } catch (IOException e) { //System.out.print("网络故障", e); } finally { if (url_con != null) { url_con.disconnect(); } } //System.out.println(responseContent); return responseContent; } %> <% WeiXinHandler t=new WeiXinHandler(); t.valid(); %>