dom4j微信接口开发

新建一个web项目,我用的是eclipse和tomcat7.0 ,外网环境用的nat123

先建立一个实体bean:TextMessage

/**
 * xml基本对象
 * @author xiaohua
 *
 */
public class TextMessage {
	private String ToUserName="" ;//开发者微信号
	private String FromUserName="";// 	发送方帐号(一个OpenID)
	private String CreateTime="" ;//消息创建时间 (整型)
	private String MsgType="" ;//text
	private String Content="" ;//文本消息内容
	private String MsgId="" ;//消息id,64位整型 
	public String getToUserName() {
		return ToUserName;
	}
	public void setToUserName(String toUserName) {
		ToUserName = toUserName;
	}
	public String getFromUserName() {
		return FromUserName;
	}
	public void setFromUserName(String fromUserName) {
		FromUserName = fromUserName;
	}
	public String getCreateTime() {
		return CreateTime;
	}
	public void setCreateTime(String createTime) {
		CreateTime = createTime;
	}
	public String getMsgType() {
		return MsgType;
	}
	public void setMsgType(String msgType) {
		MsgType = msgType;
	}
	public String getContent() {
		return Content;
	}
	public void setContent(String content) {
		Content = content;
	}
	public String getMsgId() {
		return MsgId;
	}
	public void setMsgId(String msgId) {
		MsgId = msgId;
	}
}

 微信校验工具类:CheckUtil

/**
 * 校验工具类
 * @author xiaohua
 *
 */
public class CheckUtil {
	
	private static final String token="testweixin";
	
	public static boolean checkSignsture(String signature,String timestamp,String nonce){
		String[] arra =new String[]{token,timestamp,nonce};
		//1排序
		Arrays.sort(arra);
		//2生成字符串
		StringBuffer content = new StringBuffer();
		for(int i = 0 ;i<arra.length;i++){
			content.append(arra[i]);
		}
		//3加密
	    String temp =getSha1(content.toString());
	    return temp.equals(signature);
	}

	public static String getSha1(String str){
		String  s[]= new String[100];
		if(str==null || str.length() ==0){
			return null;
		}
		char[] hexDigits={'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'};
		try {
			MessageDigest mdTemp = MessageDigest.getInstance("SHA1");
			mdTemp.update(str.getBytes("UTF-8"));
			byte[] md = mdTemp.digest();
			int j=md.length;
			char buf[]=new char[j*2];
			int  k=0;
			for(int i =0;i<j;i++){
				byte byte0=md[i];
				buf[k++] = hexDigits[byte0>>>4 & 0xf];
				buf[k++] = hexDigits[byte0 & 0xf];
			}
			return new String(buf);
		} catch (Exception e) {
			return null;
		}
	}

 格式转换 回复内容测试类:MessageUtil

/**
 * 格式转换 回复内容测试
 * @author xiaohua
 *
 */
public class MessageUtil {
	public static final String MESSAGE_TEXT="text";//文本类型
	public static final String MESSAGE_IMAGE="image";//图像类型
	public static final String MESSAGE_VOICE="voice";//声音
	public static final String MESSAGE_VIDEO="video";//视频
	public static final String MESSAGE_LINK="link";//链接
	public static final String MESSAGE_LOCATION="location";//位置
	public static final String MESSAGE_EVENT="event";//事件
	public static final String MESSAGE_SUBSCRIBE="subscribe";//关注
	public static final String MESSAGE_UNSUBSCRIBE="unsubscribe";//取消关注
	public static final String MESSAGE_CLICK="click";//取消关注
	public static final String MESSAGE_VIEW="view";//取消关注
	
	
	/**
	 * 接收的微信格式xml转成map集合
	 * @param request
	 * @return
	 * @throws IOException
	 * @throws DocumentException
	 */
	public static Map<String,String> xmlToMap(HttpServletRequest request) throws IOException, DocumentException{
		Map<String, String> map = new HashMap<>();
		SAXReader reader = new SAXReader();
		
		InputStream ins = request.getInputStream();
		Document doc = reader.read(ins);
		
		Element root = doc.getRootElement();
		
		List<Element> list = root.elements();
		for(Element el :list){
			map.put(el.getName(), el.getText());
		}
		
		ins.close();
		return map;
	}
	/**
	 * 将文本消息对象转换为xml
	 * @param textMessage
	 * @return
	 */
	public static String textMessageToXml(TextMessage textMessage){
		XStream xStream = new XStream();
		xStream.alias("xml", textMessage.getClass());//替换
		return xStream.toXML(textMessage);
	}
	
	/**
	 * 拼接菜单
	 * @return
	 */
	public static String menuText(){
		StringBuffer bf = new StringBuffer();
		bf.append("欢迎你的关注,请按照提示操作:\n\n");
		bf.append("1:小安妮的熊的介绍\n");
		bf.append("2:小安妮的熊更多详细介绍\n");
		bf.append("?:调出此主菜单\n");
		return bf.toString();
	}
	
	public static String initText(String toUserName,String fromUserName,String content){
		TextMessage text = new TextMessage();
		text.setToUserName(fromUserName);
		text.setFromUserName(toUserName);
		text.setCreateTime(dateToStr(new Date()));
		text.setMsgType(MessageUtil.MESSAGE_TEXT);
		text.setContent(content);
		return textMessageToXml(text);
	}
	
	/**
	 * 当回复数字1时
	 * @return
	 */
	public static String firstMenu(){
		StringBuffer bf = new StringBuffer();
		bf.append("你好我是小安妮的熊,我的年龄才3天,因为主人研发出我也就那么三天,以后主人会更高级的研发我的,好爱我的小主人么么哒~");
		return bf.toString();
	}
	
	/**
	 * 当回复数字2时
	 * @return
	 */
	public static String secondMenu(){
		StringBuffer bf = new StringBuffer();
		bf.append("哎呀,你怎么一不小心摁了2呢?我才出生三天耶,怎么可能会有那么多的详细资料呀!你很笨的啦~");
		return bf.toString();
	}
	
	/**
	 * 日期转换 日期转成String类型
	 * @param date
	 * @return
	 */
	public static String dateToStr(Date date){
		SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");  
		return sdf.format(date);  
	}

 servlet类:WeiXinServlet

public class WeiXinServlet extends HttpServlet {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private String token="weixintest";

	@Override
	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(true){
			out.print(echostr);
		}
		out.close();
		out=null;
		
	}
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		req.setCharacterEncoding("UTF-8");
		resp.setCharacterEncoding("UTF-8");
		
		PrintWriter out = resp.getWriter();
			try {
				Map<String, String> map = MessageUtil.xmlToMap(req);
				String fromUserName = map.get("FromUserName");
				String toUserName = map.get("ToUserName");
				String createTime = map.get("CreateTime");
				String msgType = map.get("MsgType");
				String content = map.get("Content");
				String msgId = map.get("MsgId");
				//判断,如果是文本类型的
				String message = null;
				System.out.println(msgType+"--");
				if(MessageUtil.MESSAGE_TEXT.equals(msgType)){
					if("1".equals(content)){
						message = MessageUtil.initText(toUserName, fromUserName,  MessageUtil.firstMenu());
					}else if("2".equals(content)){
						message = MessageUtil.initText(toUserName, fromUserName, MessageUtil.secondMenu());
					}else if("?".equals(content) || "?".equals(content)){
						message = MessageUtil.initText(toUserName, fromUserName, MessageUtil.menuText());
					}else{
						message ="<xml>"+
					    "<ToUserName><![CDATA["+fromUserName+"]]></ToUserName>"+
					    "<FromUserName><![CDATA["+toUserName+"]]></FromUserName>"+
					    "<CreateTime>2015-09-06</CreateTime>"+
					    "<MsgType><![CDATA[text]]></MsgType>"+
					    "<Content><![CDATA[好无语~小主人么么哒还没有开发这个呢!你是猪么,总是碰壁一点都不好玩~]]></Content>"+
					    "</xml>";
					}
					/*TextMessage text = new TextMessage();
					text.setToUserName(fromUserName);
					text.setFromUserName(toUserName);
					text.setCreateTime(dateToStr(new Date()));
					text.setMsgType("text");
					text.setContent("你发的消息是:"+content);
					message = MessageUtil.textMessageToXml(text);*/
				}else if(MessageUtil.MESSAGE_EVENT.equals(msgType)){
					String eventType = map.get("Event");//得到事件类型
					if(MessageUtil.MESSAGE_SUBSCRIBE.equals(eventType)){//关注
						message = MessageUtil.initText(toUserName, fromUserName, MessageUtil.menuText());
					}
				}
				System.out.println(message);
				out.print(message);
			} catch (DocumentException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}finally{
				out.close();
			}
	}
	
	/**
	 * 日期转换 日期转成String类型
	 * @param date
	 * @return
	 */
	public String dateToStr(Date date){
		SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");  
		return sdf.format(date);  
	}

}

 web.xml相关配置:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>wx</display-name>
    <servlet>
  	<servlet-name>WeiXinServlet</servlet-name>
  	<servlet-class>**.**.WeiXinServlet</servlet-class><!--设置WeiXinServlet的路径-->
  </servlet>
  <servlet-mapping>
  	<servlet-name>WeiXinServlet</servlet-name>
  	<url-pattern>/do</url-pattern>
  </servlet-mapping>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
</web-app>

 涉及到的jar:

写到这里,差不多就写完了.

 

 

 

 

 

 

 

目测网上的微信例子有很多,现在我是纯属娱乐自己捣鼓出来的一个,感觉还凑合,目前还在继续发展中,有兴趣的可以添加我的微信公众号:小安妮的熊

好了,先说一下我的步奏吧,我首先是百度了:微信公众号,然后注册一个微信公众号信息,由于纯属个人开发,所以我在注册过程中选择的的个人。想尽一切办法注册后,找到开发者中心,

相关源码和jar下载地址:

http://pan.baidu.com/s/1jG5wMsY  密码:7e7j

 

posted @ 2015-09-06 17:51  小安妮的熊  Views(193)  Comments(0Edit  收藏  举报