java开发微信公众号(SpringMVC)2-消息管理功能

        微信移动端软件,可以向公众号发送消息,如文字,语音,图片等等,在这个过程中,微信端服务器首先要接受到你发送的消息,然后根据你发送的消息会产生不同的回应。

这个回应要想自己设定内容(微信公众号管理界面可以设置简单的回复),就必须要在微信设置中打开服务器配置。


        此处打开配置后需要自己的服务器地址,如下:


(此处请忽略-->此处可以给大家推荐一个服务器购买点,方便开发,https://www.fjjsp.com,相当便宜,而且有半个月试用期,有兴趣可以去了解下,小编就是在那买的。)

配置好微信的,接下来就是代码的编写了。此处不再赘述springmvc的机制。

1.首先是能接收来自微信服务器的请求,还有接受用户发送的文字,并解析文字。直接上代码(代码有参考柳峰微信)。

package com.zj.controller;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.liufeng.course.service.CoreService;
import org.liufeng.course.util.SignUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 消息自动处理接口
 * @author Administrator
 *
 */
@Controller
@RequestMapping("wechat.do")
public class XxtController {
	private String token = "abc";
	
	@RequestMapping(method = RequestMethod.GET)
	@ResponseBody
	public void xxtInterface(HttpServletRequest request, HttpServletResponse response) throws 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();
				// 请求校验,若校验成功则原样返回echostr,表示接入成功,否则接入失败
				if (SignUtil.checkSignature(signature, timestamp, nonce)) {
					out.print(echostr);
				}
				out.close();
				out = null;
	}
	
	@RequestMapping(method = RequestMethod.POST)
	@ResponseBody
	public void getWeiXinMessage(HttpServletRequest request, HttpServletResponse response) throws Exception
	{
		// 将请求、响应的编码均设置为UTF-8(防止中文乱码)
				request.setCharacterEncoding("UTF-8");
				response.setCharacterEncoding("UTF-8");

				// 接收参数微信加密签名、 时间戳、随机数
				String signature = request.getParameter("signature");
				String timestamp = request.getParameter("timestamp");
				String nonce = request.getParameter("nonce");

				PrintWriter out = response.getWriter();
				// 请求校验
				if (SignUtil.checkSignature(signature, timestamp, nonce)) {
					// 调用核心服务类接收处理请求
					String respXml = CoreService.processRequest(request);
					out.print(respXml);
				}
				out.close();
				out = null;
			
	}
}
此处的do方法必须和服务器配置中的服务器地址最后的一样。
其中post方法中的 String respXml = CoreService.processRequest(request); out.print(respXml)

这两句分别是解析request 数据,业务处理也就是返回什么数据和将数据再自动发送给用户。

因为服务器接收和返回的数据类型都是有固定格式的,一般为了方便开发,都会自己封装好实体类,然后解析好再调用。

2.解析数据

public static Map<String, String> parseXml(HttpServletRequest request) throws Exception {
		// 将解析结果存储在HashMap中
		Map<String, String> map = new HashMap<String, String>();

		// 从request中取得输入流
		InputStream inputStream = request.getInputStream();
		// 读取输入流
		SAXReader reader = new SAXReader();
		Document document = reader.read(inputStream);
		// 得到xml根元素
		Element root = document.getRootElement();
		// 得到根元素的所有子节点
		List<Element> elementList = root.elements();

		// 遍历所有子节点
		for (Element e : elementList)
			map.put(e.getName(), e.getText());

		// 释放资源
		inputStream.close();
		inputStream = null;

		return map;
	}

3.当这个过程了解和实现后,我们需要做的就是在业务处理类中处理接收到的消息。比如根据发送的文本内容回复,事件内容回复,比如菜单点击,这个以后会重点提及。

package com.lianchuang.service;
public class CoreService {

	
	static Logger logger = LoggerFactory.getLogger(CoreService.class);
	
	/**
	 * 处理微信发来的请求
	 * 
	 * @param request
	 * @return
	 */
	public static String processRequest(HttpServletRequest request) {
		String respMessage = null;
		try {
			// 默认返回的文本消息内容
			String respContent = "请求处理异常,请稍候尝试!";

			// xml请求解析
			// 调用消息工具类MessageUtil解析微信发来的xml格式的消息,解析的结果放在HashMap里;
			Map<String, String> requestMap = MessageUtil.parseXml(request);
			// 从HashMap中取出消息中的字段;
			// 发送方帐号(open_id)
			String fromUserName = requestMap.get("FromUserName");
			// 公众帐号
			String toUserName = requestMap.get("ToUserName");
			// 消息类型
			String msgType = requestMap.get("MsgType");
			// 消息内容
			String content = requestMap.get("Content");
			// 从HashMap中取出消息中的字段;
			
			logger.info("fromUserName is:" +fromUserName+" toUserName is:" +toUserName+" msgType is:" +msgType);

			// 文本消息
			if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_TEXT)) {
				//微信聊天机器人测试 2015-3-31
				if(content!=null){
					respContent = TulingApiProcess.getTulingResult(content);
					if(respContent==""||null==respContent){
						MessageResponse.getTextMessage(fromUserName , toUserName , "服务号暂时无法回复,请稍后再试!");
					}
					//return FormatXmlProcess.formatXmlAnswer(toUserName, fromUserName, respContent);
					return MessageResponse.getTextMessage(fromUserName , toUserName , respContent);
				}
			} else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_EVENT)) {// 事件推送
				String eventType = requestMap.get("Event");// 事件类型
				
				if (eventType.equals(MessageUtil.EVENT_TYPE_SUBSCRIBE)) {// 订阅
					respContent = "欢迎关注沪动校讯通!";
					return MessageResponse.getTextMessage(fromUserName , toUserName , respContent);
				} else if (eventType.equals(MessageUtil.EVENT_TYPE_UNSUBSCRIBE)) {// 取消订阅
					// TODO 取消订阅后用户再收不到公众号发送的消息,因此不需要回复消息
				} else if (eventType.equals(MessageUtil.EVENT_TYPE_CLICK)) {// 自定义菜单点击事件
					String eventKey = requestMap.get("EventKey");// 事件KEY值,与创建自定义菜单时指定的KEY值对应
					logger.info("eventKey is:" +eventKey);
					return MenuClickService.getClickResponse(eventKey , fromUserName , toUserName);
				}
			}

			//开启微信声音识别测试 2015-3-30
			else if(msgType.equals("voice"))
			{
				String recvMessage = requestMap.get("Recognition");
				//respContent = "收到的语音解析结果:"+recvMessage;
				if(recvMessage!=null){
					respContent = TulingApiProcess.getTulingResult(recvMessage);
				}else{
					respContent = "您说的太模糊了,能不能重新说下呢?";
				}
				return MessageResponse.getTextMessage(fromUserName , toUserName , respContent); 
			}
			//拍照功能
			else if(msgType.equals("pic_sysphoto"))
			{
				
			}
			else
			{
				return MessageResponse.getTextMessage(fromUserName , toUserName , "返回为空"); 
			}
			
		}
		catch (Exception e) {
			e.printStackTrace();
		}

		return respMessage;
	}

}

此处不再赘述如何解析数据格式,和封装成什么样的实体类,代码项目直接给你们,你们去参考。不用csdn分(http://download.csdn.net/detail/zjcool2012/9676715)。

此处有这些相关的问题,可以发送邮件到我的私人邮箱(2501399916@qq,com),我会一一为大家解答的。











































































































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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值