搜尋
首頁微信小程式微信開發微信開發之處理微信客戶端所發的消息

在上一篇微信開發的博文中微信開發(01)之如何成為開發者,我們開啟了微信開發者模式,本篇博文我們簡單的處理微信關注者發給我們公眾號的消息。

在開啟微信開發者模式時,我們配置了一個URL位址,當我們提交開啟微信開發者模式,騰訊的微信伺服器會向該URL位址發送一個get請求,並且攜帶一些參數,讓我們來驗證。說到get請求,就必須說到post請求,關注我們公眾號的微信粉絲發來的消息,觸發的事件,騰訊的微信伺服器則會像該URL地址發送一個post請求,請求的內容就是以xml文檔形式的字串。

所以該URL位址的get請求的處理方法,專門用於開啟微信開發者模式;而post請求則用於處理微信粉絲發給我們的訊息,或者觸發的事件,所以我們後面的微信開發工作的起點就是該URL位址的post處理方法。

下面我們處理一個最簡單的例子:粉絲發送任何一個文字訊息給我們,我們回覆他一個訊息:「你好,+ 他微信的openId」

下面直接貼程式碼:

URL對應的處理servlet:

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();
		// 请求校验,若校验成功则原样返回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 signature = request.getParameter("signature");
		String timestamp = request.getParameter("timestamp");
		String nonce = request.getParameter("nonce");

		PrintWriter out = response.getWriter();
		// 请求校验
		if (SignUtil.checkSignature(signature, timestamp, nonce)) {
			Message msgObj = XMLUtil.getMessageObject(request);	// 读取微信客户端发来的消息(xml字符串),并将其转换为消息对象
			if(msgObj != null){
				String xml = "<xml>" +
						 "<ToUserName><![CDATA[" + msgObj.getFromUserName() + "]]></ToUserName>" +	// 接收方帐号(收到的OpenID)
						 "<FromUserName><![CDATA[" + msgObj.getToUserName() + "]]></FromUserName>" +	// 开发者微信号
						 "<CreateTime>12345678</CreateTime>" +
						 "<MsgType><![CDATA[text]]></MsgType>" +
						 "<Content><![CDATA[你好,"+ msgObj.getFromUserName() +"]]></Content>" +
						 "</xml>";
				out.write(xml);	// 回复微信客户端的消息(xml字符串)
				out.close();
				return;
			}
		}
		out.write("");
		out.close();
	}
}

# xml字串的處理工具類,實現xml訊息到訊息物件的轉換:

public class XMLUtil 
{
	/**
	 * 从request中读取用户发给公众号的消息内容
	 * @param request
	 * @return 用户发给公众号的消息内容
	 * @throws IOException
	 */
	public static String readRequestContent(HttpServletRequest request) throws IOException
	{
		// 从输入流读取返回内容
		InputStream inputStream = request.getInputStream();
		InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
		BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
		String str = null;
		StringBuilder buffer = new StringBuilder();
		
		while ((str = bufferedReader.readLine()) != null) {
			buffer.append(str);
		}
		
		// 释放资源
		bufferedReader.close();
		inputStreamReader.close();
		inputStream.close();
		
		return buffer.toString();
	}
	
	/**
	 * 将xml文档的内容转换成map
	 * @param xmlDoc
	 * @return map
	 */
	public static Map<String, String> xmlToMap(String xmlDoc)
	{
		//创建一个新的字符串
        StringReader read = new StringReader(xmlDoc);
        //创建新的输入源SAX 解析器将使用 InputSource 对象来确定如何读取 XML 输入
        InputSource source = new InputSource(read);
        //创建一个新的SAXBuilder
        SAXBuilder sb = new SAXBuilder();
        
        Map<String, String> xmlMap = new HashMap<String, String>();
        try {
            Document doc = sb.build(source);	//通过输入源构造一个Document
            Element root = doc.getRootElement();	//取的根元素
            
            List<Element> cNodes = root.getChildren();	//得到根元素所有子元素的集合(根元素的子节点,不包括孙子节点)
            Element et = null;
            for(int i=0;i<cNodes.size();i++){
                et = (Element) cNodes.get(i);	//循环依次得到子元素
                xmlMap.put(et.getName(), et.getText());
            }
        } catch (JDOMException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return xmlMap;
	}
	
	/**
	 * 将保存xml内容的map转换成对象
	 * @param map
	 * @return
	 */
	public static Message getMessageObject(Map<String, String> map)
	{
		if(map != null){
			String MsgType = map.get("MsgType");
			
			// 消息类型(文本消息:text, 图片消息:image, 语音消息:voice, 视频消息:video, 
			// 地理位置消息:location, 链接消息:link)
			if("text".equals(MsgType)){
				TextMessage msg = new TextMessage();
				XMLUtil.initCommonMsg(msg, map);
				
				msg.setContent(map.get("Content"));
				return msg;
			}
			if("ImageMessage".equals(MsgType)){
				ImageMessage msg = new ImageMessage();
				XMLUtil.initCommonMsg(msg, map);
				
				msg.setPicUrl(map.get("PicUrl"));
				msg.setMediaId(map.get("MediaId"));
				return msg;
			}
			if("video".equals(MsgType)){
				VideoMessage msg = new VideoMessage();
				XMLUtil.initCommonMsg(msg, map);
				
				msg.setMediaId(map.get("MediaId"));
				msg.setThumbMediaId(map.get("ThumbMediaId"));
				return msg;
			}
			if("voice".equals(MsgType)){
				VoiceMessage msg = new VoiceMessage();
				XMLUtil.initCommonMsg(msg, map);
				
				msg.setMediaId(map.get("MediaId"));
				msg.setFormat(map.get("Format"));
				return msg;
			}
			if("location".equals(MsgType)){
				LocationMessage msg = new LocationMessage();

				msg.setLocation_X(map.get("Location_X"));
				msg.setLocation_Y(map.get("Location_Y"));
				msg.setScale(map.get("Scale"));
				msg.setLabel(map.get("Label"));
				return msg;
			}
			if("link".equals(MsgType)){
				LinkMessage msg = new LinkMessage();
				XMLUtil.initCommonMsg(msg, map);
				
				msg.setTitle(map.get("Title"));
				msg.setDescription(map.get("Description"));
				msg.setUrl(map.get("Url"));
				return msg;
			}
		}
		return null;
	}
	
	/**
	 * 将保存xml内容的map转换成对象
	 * @param map
	 * @return
	 * @throws IOException 
	 */
	public static Message getMessageObject(HttpServletRequest request) throws IOException
	{
		String xmlDoc = XMLUtil.readRequestContent(request);	// 读取微信客户端发了的消息(xml)
		Map<String, String> map = XMLUtil.xmlToMap(xmlDoc);		// 将客户端发来的xml转换成Map
		if(map != null){
			String MsgType = map.get("MsgType");
			
			// 消息类型(文本消息:text, 图片消息:image, 语音消息:voice, 视频消息:video, 
			// 地理位置消息:location, 链接消息:link)
			if("text".equals(MsgType)){
				TextMessage msg = new TextMessage();
				XMLUtil.initCommonMsg(msg, map);
				
				msg.setContent(map.get("Content"));
				return msg;
			}
			/*if("ImageMessage".equals(MsgType)){
				ImageMessage msg = new ImageMessage();
				XMLUtil.initCommonMsg(msg, map);
				
				msg.setPicUrl(map.get("PicUrl"));
				msg.setMediaId(map.get("MediaId"));
				return msg;
			}
			if("video".equals(MsgType)){
				VideoMessage msg = new VideoMessage();
				XMLUtil.initCommonMsg(msg, map);
				
				msg.setMediaId(map.get("MediaId"));
				msg.setThumbMediaId(map.get("ThumbMediaId"));
				return msg;
			}
			if("voice".equals(MsgType)){
				VoiceMessage msg = new VoiceMessage();
				XMLUtil.initCommonMsg(msg, map);
				
				msg.setMediaId(map.get("MediaId"));
				msg.setFormat(map.get("Format"));
				return msg;
			}
			if("location".equals(MsgType)){
				LocationMessage msg = new LocationMessage();

				msg.setLocation_X(map.get("Location_X"));
				msg.setLocation_Y(map.get("Location_Y"));
				msg.setScale(map.get("Scale"));
				msg.setLabel(map.get("Label"));
				return msg;
			}
			if("link".equals(MsgType)){
				LinkMessage msg = new LinkMessage();
				XMLUtil.initCommonMsg(msg, map);
				
				msg.setTitle(map.get("Title"));
				msg.setDescription(map.get("Description"));
				msg.setUrl(map.get("Url"));
				return msg;
			}*/
		}
		return null;
	}
	
	public static void initCommonMsg(Message msg, Map<String, String> map)
	{
		msg.setMsgId(map.get("MsgId"));
		msg.setMsgType(map.get("MsgType"));
		msg.setToUserName(map.get("ToUserName"));
		msg.setFromUserName(map.get("FromUserName"));
		msg.setCreateTime(map.get("CreateTime"));
	}
}

 粉絲發來的訊息分為了6中類型(文字訊息, 圖片訊息, 語音訊息, 視訊訊息, 地理位置訊息, 連結訊息):

/**
 * 微信消息基类
 * @author yuanfang
 * @date 2015-03-23
 */
public class Message 
{
	private String MsgId;	// 消息id,64位整型
	private String MsgType;	// 消息类型(文本消息:text, 图片消息:image, 语音消息:voice, 视频消息:video, 地理位置消息:location, 链接消息:link)
	private String ToUserName;	//开发者微信号
	private String FromUserName; // 发送方帐号(一个OpenID)
	private String CreateTime;	// 消息创建时间 (整型)
	
	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 getMsgId() {
		return MsgId;
	}
	public void setMsgId(String msgId) {
		MsgId = msgId;
	}
	
}

 文字訊息類別:

package com.sinaapp.wx.msg;

public class TextMessage extends Message 
{
	private String Content;	// 文本消息内容

	public String getContent() {
		return Content;
	}

	public void setContent(String content) {
		Content = content;
	}
	
}

 OK,對粉絲傳送給我們公眾號的任意的文字訊息最簡單的處理就完成,我們簡單的回覆他:你好,然後加上他微信的openId,類似於:你好,orJydljfkg3-r0_dj3rkdfvjl

# 更多微信開發之處理微信客戶端發來的消息相關文章請關注PHP中文網!

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

這個專案正在遷移到osdn.net/projects/mingw的過程中,你可以繼續在那裡關注我們。 MinGW:GNU編譯器集合(GCC)的本機Windows移植版本,可自由分發的導入函式庫和用於建置本機Windows應用程式的頭檔;包括對MSVC執行時間的擴展,以支援C99功能。 MinGW的所有軟體都可以在64位元Windows平台上運作。

Atom編輯器mac版下載

Atom編輯器mac版下載

最受歡迎的的開源編輯器

VSCode Windows 64位元 下載

VSCode Windows 64位元 下載

微軟推出的免費、功能強大的一款IDE編輯器

SublimeText3 Linux新版

SublimeText3 Linux新版

SublimeText3 Linux最新版

DVWA

DVWA

Damn Vulnerable Web App (DVWA) 是一個PHP/MySQL的Web應用程序,非常容易受到攻擊。它的主要目標是成為安全專業人員在合法環境中測試自己的技能和工具的輔助工具,幫助Web開發人員更好地理解保護網路應用程式的過程,並幫助教師/學生在課堂環境中教授/學習Web應用程式安全性。 DVWA的目標是透過簡單直接的介面練習一些最常見的Web漏洞,難度各不相同。請注意,該軟體中