微信开发源码讲解

微信开发请求Servlet

package com.weixin.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.jeecg.util.SignUtil;

import com.weixin.service.CoreService;

/**
 * 核心请求处理类
 * 
 * @author liufeng
 * @date 2013-05-18
 */
public class CoreServlet extends HttpServlet {
	private static final long serialVersionUID = 4440739483644821986L;

	/**
	 * 确认请求来自微信服务器
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// 微信加密签名
		String signature = request.getParameter("signature");
		// 时间戳
		String timestamp = request.getParameter("timestamp");
		// 随机数
		String nonce = request.getParameter("nonce");
		// 随机字符串
		String echostr = request.getParameter("echostr");

		PrintWriter out = response.getWriter();
		// 通过检验signature对请求进行校验,若校验成功则原样返回echostr,表示接入成功,否则接入失败
		if (SignUtil.checkSignature(signature, timestamp, nonce)) {
			out.print(echostr);
		}
		out.close();
		out = null;
	}

	/**
	 * 处理微信服务器发来的消息
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// 将请求、响应的编码均设置为UTF-8(防止中文乱码)
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");

		// 调用核心业务类接收消息、处理消息
		//String respMessage = MingXingService.processRequest(request);
		String respMessage =CoreService.processRequest(request);
		// 响应消息
		PrintWriter out = response.getWriter();
		out.print(respMessage);
		out.close();
	}

}

针对用户事件具体逻辑处理代码:

package com.weixin.service;


import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;


import javax.servlet.http.HttpServletRequest;


import org.apache.log4j.Logger;
import org.jeecg.message.resp.Article;
import org.jeecg.message.resp.NewsMessage;
import org.jeecg.message.resp.TextMessage;
import org.jeecg.util.FreemarkerHelper;
import org.jeecg.util.MessageUtil;
import org.jeecg.util.weather.Weather;




/**
 * 核心服务类
 * 
 * @author liufeng
 * @date 2013-05-20
 */
public class CoreService {
private static Logger log = Logger.getLogger(CoreService.class);


/**
* 处理微信发来的请求

* @param request
* @return
*/
public static String processRequest(HttpServletRequest request) {
String respMessage = null;
try {
// 默认返回的文本消息内容
String respContent = "请求处理异常,请稍候尝试!";
// xml请求解析
Map<String, String> requestMap = MessageUtil.parseXml(request);
// Map<String, String> requestMap = new HashMap<String, String>();
// // 发送方帐号(open_id)
String fromUserName = requestMap.get("FromUserName");
// 公众帐号
String toUserName = requestMap.get("ToUserName");
// 消息类型
String msgType = requestMap.get("MsgType");
// 默认回复此文本消息
TextMessage textMessage = new TextMessage();
textMessage.setToUserName(fromUserName);
textMessage.setFromUserName(toUserName);
textMessage.setCreateTime(new Date().getTime());
textMessage.setMsgType(MessageUtil.RESP_MESSAGE_TYPE_TEXT);
textMessage.setFuncFlag(0);
// 由于href属性值必须用双引号引起,这与字符串本身的双引号冲突,所以要转义
textMessage.setContent(getMainMenu());
// 将文本消息对象转换成xml字符串
respMessage = MessageUtil.textMessageToXml(textMessage);
// 文本消息
if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_TEXT)) {
String content = requestMap.get("Content");
if ("?".equals(content)) {
respContent = getMainMenu();
textMessage.setContent(respContent);
respMessage = MessageUtil.textMessageToXml(textMessage);
} else if ("1".equals(content)) {
respContent = "作者:张代浩 (scott) \n邮箱:scott@jeecg.org \n QQ群:129190229";
textMessage.setContent(respContent);
respMessage = MessageUtil.textMessageToXml(textMessage);
} else if ("2".equals(content)) {
respContent = "<a href=\"www.jeecg.org\">www.jeecg.org</a>";
textMessage.setContent(respContent);
respMessage = MessageUtil.textMessageToXml(textMessage);
} else if ("3".equals(content)) {
// 创建图文消息
NewsMessage newsMessage = new NewsMessage();
newsMessage.setToUserName(fromUserName);
newsMessage.setFromUserName(toUserName);
newsMessage.setCreateTime(new Date().getTime());
newsMessage.setMsgType(MessageUtil.RESP_MESSAGE_TYPE_NEWS);
newsMessage.setFuncFlag(0);


List<Article> articleList = new ArrayList<Article>();
Article article1 = new Article();
article1.setTitle("JEECG专题介绍");
article1.setDescription("JEECG 微云快速开发平台");
article1.setPicUrl("http://avatar.csdn.net/3/D/E/1_zhangdaiscott.jpg");
article1.setUrl("http://zhangdaiscott.github.io/jeecg/");


Article article4 = new Article();
article4.setTitle("第2篇\n MiniDao专题介绍");
article4.setDescription("");
article4.setPicUrl("http://www.jeecg.org/data/attachment/forum/201308/18/224051ey14ehqe000iegja.jpg");
article4.setUrl("http://zhangdaiscott.github.io/MiniDao/");


Article article2 = new Article();
article2.setTitle("第3篇\n JEECG CSDN专家访谈");
article2.setDescription("");
article2.setPicUrl("http://img.my.csdn.net/uploads/201301/23/1358930662_6750.jpg");
article2.setUrl("http://blog.csdn.net/blogdevteam/article/details/8534797");


Article article3 = new Article();
article3.setTitle("第4篇\n 参与开源");
article3.setDescription("");
article3.setPicUrl("http://avatar.csdn.net/3/D/E/1_zhangdaiscott.jpg");
article3.setUrl("http://blog.csdn.net/zhangdaiscott/article/details/14160383");




articleList.add(article1);
articleList.add(article4);
articleList.add(article2);
articleList.add(article3);
newsMessage.setArticleCount(articleList.size());
newsMessage.setArticles(articleList);
respMessage = MessageUtil.newsMessageToXml(newsMessage);
}else if ("4".equals(content)) {
respContent = "<a href=\"http://jeecgdemo.duapp.com/html5Servlet\">微应用演示   -- 用力点我</a>";
textMessage.setContent(respContent);
respMessage = MessageUtil.textMessageToXml(textMessage);
}else if ("5".equals(content)||"翻译".equals(content)) {
respContent = getTranslateUsage();
textMessage.setContent(respContent);
respMessage = MessageUtil.textMessageToXml(textMessage);
}else if ("6".equals(content)||"大转盘".equals(content)) {
NewsMessage newsMessage = new NewsMessage();
newsMessage.setToUserName(fromUserName);
newsMessage.setFromUserName(toUserName);
newsMessage.setCreateTime(new Date().getTime());
newsMessage.setMsgType(MessageUtil.RESP_MESSAGE_TYPE_NEWS);
newsMessage.setFuncFlag(0);

Article article3 = new Article();
List<Article> articleList = new ArrayList<Article>();
article3.setTitle("大转盘");
article3.setDescription("");
article3.setPicUrl("http://www.jeecg.org/data/attachment/forum/201312/17/165432nuqktzqq305hkr06.jpg");
article3.setUrl("http://jeecgdemo.duapp.com/zhuanpan.htm");
articleList.add(article3);
newsMessage.setArticleCount(articleList.size());
newsMessage.setArticles(articleList);
respMessage = MessageUtil.newsMessageToXml(newsMessage);
}else if (content.startsWith("翻译")) {
String keyWord = content.replaceAll("^翻译", "").trim();  
       if ("".equals(keyWord)) {  
           textMessage.setContent(getTranslateUsage());  
       } else {  
           textMessage.setContent(BaiduTranslateService.translate(keyWord));  
       }  
respMessage = MessageUtil.textMessageToXml(textMessage);
}else if (content.startsWith("天气")||content.startsWith("7")) {
String keyWord = content.replaceAll("天气", "").trim();  
if ("".equals(keyWord)||"7".equals(keyWord)) {  
StringBuffer buffer = new StringBuffer();
    // 接收用户发送的文本消息内容   
buffer.append("发送天气+城市,例如‘天气广州‘").append("\n");
           textMessage.setContent(buffer.toString()); 
           respMessage = MessageUtil.textMessageToXml(textMessage);
       } else {  
        Map<String, Object> map = new HashMap<String, Object>();
            Map<String, Object> map2 = new HashMap<String, Object>();
            try{
            String filepach = request.getRealPath("/");
            Weather util = new Weather();
        map = util.report(keyWord,filepach);
        map2 = util.report2(keyWord,filepach);
            }catch (Exception e) {
            e.printStackTrace();
            StringBuffer buffer = new StringBuffer();
            // 接收用户发送的文本消息内容   
        buffer.append("发送天气+城市,例如‘天气广州‘").append("\n");
        textMessage.setContent(buffer.toString());
        respMessage = MessageUtil.textMessageToXml(textMessage);
        return respMessage;
    }
           
            List<Article> articleList = new ArrayList<Article>();
            // 创建图文消息   
               NewsMessage newsMessage = new NewsMessage();  
               newsMessage.setToUserName(fromUserName);  
               newsMessage.setFromUserName(toUserName);  
               newsMessage.setCreateTime(new Date().getTime());  
               newsMessage.setMsgType(MessageUtil.RESP_MESSAGE_TYPE_NEWS);  
               newsMessage.setFuncFlag(0); 
               
//                Properties prop = new Properties();
//     InputStream inStream = CoreService.class
//     .getResourceAsStream("/messages.properties");
//     try {
//     prop.load(inStream);
//     inStream.close();
//     } catch (IOException e) {
//     e.printStackTrace();
//     }
//     String picurl = prop.getProperty("picurl");
           
            Article article1 = new Article();  
               article1.setTitle("【"+content.substring(2)+"】天气实况 气温:"+map2.get("temp")+"度  风速:"+map2.get("WD")+" "+map2.get("WS")+" 湿度:"+map2.get("SD") );  
               article1.setDescription("");  
//                article1.setPicUrl(picurl+"/image/khdxz2.jpg");  
               article1.setPicUrl("");
               article1.setUrl("");  


               Article article2 = new Article();  
               article2.setTitle("建议:"+map.get("index_d"));  
               article2.setDescription("");  
               article2.setPicUrl("");  
               article2.setUrl("");  
               
               Article article3 = new Article();  
               article3.setTitle(map.get("mydate1")+"  "+map.get("myweek1")+"  "+map.get("temp1")+"  "+map.get("weather1")+"  "+map.get("wind1")+" "+map.get("fl1"));  
               article3.setDescription("");  
               article3.setPicUrl("http://m.weather.com.cn/img/b"+map.get("img1")+".gif");  
               article3.setUrl("");  


               Article article4 = new Article();  
               article4.setTitle(map.get("mydate2")+"  "+map.get("myweek2")+"  "+map.get("temp2")+"  "+map.get("weather2")+"  "+map.get("wind2")+" "+map.get("fl2"));  
               article4.setDescription("");  
               article4.setPicUrl("http://m.weather.com.cn/img/b"+map.get("img2")+".gif");  
               article4.setUrl("");  
               
               Article article5 = new Article();  
               article5.setTitle(map.get("mydate3")+"  "+map.get("myweek3")+"  "+map.get("temp3")+"  "+map.get("weather3")+"  "+map.get("wind3")+" "+map.get("fl3"));  
               article5.setDescription("");  
               article5.setPicUrl("http://m.weather.com.cn/img/b"+map.get("img3")+".gif");  
               article5.setUrl("");


               articleList.add(article1);  
               articleList.add(article2);  
               articleList.add(article3);  
               articleList.add(article4);
               articleList.add(article5);
               newsMessage.setArticleCount(articleList.size());  
               newsMessage.setArticles(articleList);  
               respMessage = MessageUtil.newsMessageToXml(newsMessage);
       }  

}
}
// 图片消息
else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_IMAGE)) {
respContent = "您发送的是图片消息!";
}
// 地理位置消息
else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_LOCATION)) {
respContent = "您发送的是地理位置消息!";
}
// 链接消息
else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_LINK)) {
respContent = "您发送的是链接消息!";
}
// 音频消息
else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_VOICE)) {
respContent = "您发送的是音频消息!";
}
// 事件推送
else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_EVENT)) {
// 事件类型
String eventType = requestMap.get("Event");
// 订阅
if (eventType.equals(MessageUtil.EVENT_TYPE_SUBSCRIBE)) {
respContent = "谢谢您的关注!回复\"?\"进入主菜单。";
textMessage.setContent(respContent);
respMessage = MessageUtil.textMessageToXml(textMessage);
}
// 取消订阅
else if (eventType.equals(MessageUtil.EVENT_TYPE_UNSUBSCRIBE)) {
// TODO 取消订阅后用户再收不到公众号发送的消息,因此不需要回复消息
}
// 自定义菜单点击事件
else if (eventType.equals(MessageUtil.EVENT_TYPE_CLICK)) {
// TODO 自定义菜单权没有开放,暂不处理该类消息
String EventKey = requestMap.get("EventKey");
if("jeecg.name".equals(EventKey)){
respContent = "作者:张代浩 (scott)\n 邮箱:scott@jeecg.org \n QQ群:129190229";
textMessage.setContent(respContent);
respMessage = MessageUtil.textMessageToXml(textMessage);
}
if("翻译".equals(EventKey)){
respContent = getTranslateUsage();
textMessage.setContent(respContent);
respMessage = MessageUtil.textMessageToXml(textMessage);
}

}
}


} catch (Exception e) {
e.printStackTrace();
}


return respMessage;
}


/**
* 欢迎语
* @return
*/
public static String getMainMenu() {

// 复杂字符串文本读取,采用文件方式存储
String html = new FreemarkerHelper().parseTemplate("/text/welcome.ftl", null);
return html;
}



/**
* Q译通使用指南

* @return
*/
public static String getTranslateUsage() {
StringBuffer buffer = new StringBuffer();
buffer.append("微译使用指南").append("\n\n");
buffer.append("微译为用户提供专业的多语言翻译服务,目前支持以下翻译方向:").append("\n");
buffer.append("    中 -> 英").append("\n");
buffer.append("    英 -> 中").append("\n");
buffer.append("    日 -> 中").append("\n\n");
buffer.append("使用示例:").append("\n");
buffer.append("    翻译我是中国人").append("\n");
buffer.append("    翻译dream").append("\n");
buffer.append("    翻译さようなら").append("\n\n");
buffer.append("回复“?”显示主菜单");
return buffer.toString();
}

}

去123123

微信开发源码讲解,布布扣,bubuko.com

微信开发源码讲解

上一篇:less语言特性(二) —— 混合


下一篇:Android第三方应用分享图文到微信朋友圈 & 微信回调通知分享状态