亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

Home WeChat Applet WeChat Development WeChat development: processing messages sent by WeChat client

WeChat development: processing messages sent by WeChat client

Feb 28, 2017 am 09:33 AM
WeChat development

In the previous blog post about WeChat development (How to become a developer in WeChat Development (01)), we turned on the WeChat developer mode. In this blog post, we simply process the messages sent to our public account by WeChat followers.

When turning on the WeChat developer mode, we configured a URL address. When we submit to turn on the WeChat developer mode, Tencent's WeChat server will send a get request to the URL address and carry some parameters. Let's verify. When it comes to get requests, we must talk about post requests. When the WeChat fans who follow our official account send messages and trigger events, Tencent's WeChat server will send a post request to the URL address. The content of the request is an xml document. string in the form.

So the processing method of the get request of this URL address is specially used to enable the WeChat developer mode; while the post request is used to process the messages sent to us by WeChat fans, or the events triggered, so what we do later The starting point of WeChat development work is the post processing method of the URL address.

Let’s deal with the simplest example below: fans send us any text message, and we reply to him with a message: "Hello, + his WeChat openId"

Post it directly below Code:

The processing servlet corresponding to the URL:

public class CoreServlet extends HttpServlet 
{
	private static final long serialVersionUID = 4440739483644821986L;

	/**
	 * 請求校驗(yàn)(確認(rèn)請求來自微信服務(wù)器)
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
	{
		// 微信服務(wù)端發(fā)來的加密簽名
		String signature = request.getParameter("signature");
		// 時(shí)間戳
		String timestamp = request.getParameter("timestamp");
		// 隨機(jī)數(shù)
		String nonce = request.getParameter("nonce");
		// 隨機(jī)字符串
		String echostr = request.getParameter("echostr");
		
		PrintWriter out = response.getWriter();
		// 請求校驗(yàn),若校驗(yàn)成功則原樣返回echostr,表示接入成功,否則接入失敗
		if (SignUtil.checkSignature(signature, timestamp, nonce)) {
			out.print(echostr);
		}
		out.close();
		out = null;
	}

	/**
	 * 請求校驗(yàn)與處理
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
	{
		// 將請求、響應(yīng)的編碼均設(shè)置為UTF-8(防止中文亂碼)
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		
		// 接收參數(shù)微信加密簽名、 時(shí)間戳、隨機(jī)數(shù)
		String signature = request.getParameter("signature");
		String timestamp = request.getParameter("timestamp");
		String nonce = request.getParameter("nonce");

		PrintWriter out = response.getWriter();
		// 請求校驗(yàn)
		if (SignUtil.checkSignature(signature, timestamp, nonce)) {
			Message msgObj = XMLUtil.getMessageObject(request);	// 讀取微信客戶端發(fā)來的消息(xml字符串),并將其轉(zhuǎn)換為消息對象
			if(msgObj != null){
				String xml = "<xml>" +
						 "<ToUserName><![CDATA[" + msgObj.getFromUserName() + "]]></ToUserName>" +	// 接收方帳號(收到的OpenID)
						 "<FromUserName><![CDATA[" + msgObj.getToUserName() + "]]></FromUserName>" +	// 開發(fā)者微信號
						 "<CreateTime>12345678</CreateTime>" +
						 "<MsgType><![CDATA[text]]></MsgType>" +
						 "<Content><![CDATA[你好,"+ msgObj.getFromUserName() +"]]></Content>" +
						 "</xml>";
				out.write(xml);	// 回復(fù)微信客戶端的消息(xml字符串)
				out.close();
				return;
			}
		}
		out.write("");
		out.close();
	}
}

xml string processing tool class to realize the conversion of xml message to message object:

public class XMLUtil 
{
	/**
	 * 從request中讀取用戶發(fā)給公眾號的消息內(nèi)容
	 * @param request
	 * @return 用戶發(fā)給公眾號的消息內(nèi)容
	 * @throws IOException
	 */
	public static String readRequestContent(HttpServletRequest request) throws IOException
	{
		// 從輸入流讀取返回內(nèi)容
		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文檔的內(nèi)容轉(zhuǎn)換成map
	 * @param xmlDoc
	 * @return map
	 */
	public static Map<String, String> xmlToMap(String xmlDoc)
	{
		//創(chuàng)建一個新的字符串
        StringReader read = new StringReader(xmlDoc);
        //創(chuàng)建新的輸入源SAX 解析器將使用 InputSource 對象來確定如何讀取 XML 輸入
        InputSource source = new InputSource(read);
        //創(chuàng)建一個新的SAXBuilder
        SAXBuilder sb = new SAXBuilder();
        
        Map<String, String> xmlMap = new HashMap<String, String>();
        try {
            Document doc = sb.build(source);	//通過輸入源構(gòu)造一個Document
            Element root = doc.getRootElement();	//取的根元素
            
            List<Element> cNodes = root.getChildren();	//得到根元素所有子元素的集合(根元素的子節(jié)點(diǎn),不包括孫子節(jié)點(diǎn))
            Element et = null;
            for(int i=0;i<cNodes.size();i++){
                et = (Element) cNodes.get(i);	//循環(huán)依次得到子元素
                xmlMap.put(et.getName(), et.getText());
            }
        } catch (JDOMException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return xmlMap;
	}
	
	/**
	 * 將保存xml內(nèi)容的map轉(zhuǎn)換成對象
	 * @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內(nèi)容的map轉(zhuǎn)換成對象
	 * @param map
	 * @return
	 * @throws IOException 
	 */
	public static Message getMessageObject(HttpServletRequest request) throws IOException
	{
		String xmlDoc = XMLUtil.readRequestContent(request);	// 讀取微信客戶端發(fā)了的消息(xml)
		Map<String, String> map = XMLUtil.xmlToMap(xmlDoc);		// 將客戶端發(fā)來的xml轉(zhuǎn)換成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"));
	}
}

Messages sent by fans are divided into 6 types (text messages, picture messages, voice messages, video messages, geographical location messages, link messages):

/**
 * 微信消息基類
 * @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;	//開發(fā)者微信號
	private String FromUserName; // 發(fā)送方帳號(一個OpenID)
	private String CreateTime;	// 消息創(chuàng)建時(shí)間 (整型)
	
	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;
	}
	
}

Text message type:

package com.sinaapp.wx.msg;

public class TextMessage extends Message 
{
	private String Content;	// 文本消息內(nèi)容

	public String getContent() {
		return Content;
	}

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

OK, for fans, send it to our public The simplest processing of any text message of the account is completed. We simply reply to him: Hello, and then add his WeChat openId, similar to: Hello, orJydljfkg3-r0_dj3rkdfvjl

More WeChat development For articles related to processing messages sent from WeChat clients, please pay attention to the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

PHP Tutorial
1488
72
PHP WeChat development: How to implement message encryption and decryption PHP WeChat development: How to implement message encryption and decryption May 13, 2023 am 11:40 AM

PHP is an open source scripting language that is widely used in web development and server-side programming, especially in WeChat development. Today, more and more companies and developers are starting to use PHP for WeChat development because it has become a truly easy-to-learn and easy-to-use development language. In WeChat development, message encryption and decryption are a very important issue because they involve data security. For messages without encryption and decryption methods, hackers can easily obtain the data, posing a threat to users.

PHP WeChat development: How to implement voting function PHP WeChat development: How to implement voting function May 14, 2023 am 11:21 AM

In the development of WeChat public accounts, the voting function is often used. The voting function is a great way for users to quickly participate in interactions, and it is also an important tool for holding events and surveying opinions. This article will introduce you how to use PHP to implement WeChat voting function. Obtain the authorization of the WeChat official account. First, you need to obtain the authorization of the WeChat official account. On the WeChat public platform, you need to configure the API address of the WeChat public account, the official account, and the token corresponding to the public account. In the process of our development using PHP language, we need to use the PH officially provided by WeChat

Using PHP to develop WeChat mass messaging tools Using PHP to develop WeChat mass messaging tools May 13, 2023 pm 05:00 PM

With the popularity of WeChat, more and more companies are beginning to use it as a marketing tool. The WeChat group messaging function is one of the important means for enterprises to conduct WeChat marketing. However, if you only rely on manual sending, it is an extremely time-consuming and laborious task for marketers. Therefore, it is particularly important to develop a WeChat mass messaging tool. This article will introduce how to use PHP to develop WeChat mass messaging tools. 1. Preparation work To develop WeChat mass messaging tools, we need to master the following technical points: Basic knowledge of PHP WeChat public platform development Development tools: Sub

PHP WeChat development: How to implement customer service chat window management PHP WeChat development: How to implement customer service chat window management May 13, 2023 pm 05:51 PM

WeChat is currently one of the social platforms with the largest user base in the world. With the popularity of mobile Internet, more and more companies are beginning to realize the importance of WeChat marketing. When conducting WeChat marketing, customer service is a crucial part. In order to better manage the customer service chat window, we can use PHP language for WeChat development. 1. Introduction to PHP WeChat development PHP is an open source server-side scripting language that is widely used in the field of Web development. Combined with the development interface provided by WeChat public platform, we can use PHP language to conduct WeChat

PHP WeChat development: How to implement user tag management PHP WeChat development: How to implement user tag management May 13, 2023 pm 04:31 PM

In the development of WeChat public accounts, user tag management is a very important function, which allows developers to better understand and manage their users. This article will introduce how to use PHP to implement the WeChat user tag management function. 1. Obtain the openid of the WeChat user. Before using the WeChat user tag management function, we first need to obtain the user's openid. In the development of WeChat public accounts, it is a common practice to obtain openid through user authorization. After the user authorization is completed, we can obtain the user through the following code

PHP WeChat development: How to implement group message sending records PHP WeChat development: How to implement group message sending records May 13, 2023 pm 04:31 PM

As WeChat becomes an increasingly important communication tool in people's lives, its agile messaging function is quickly favored by a large number of enterprises and individuals. For enterprises, developing WeChat into a marketing platform has become a trend, and the importance of WeChat development has gradually become more prominent. Among them, the group sending function is even more widely used. So, as a PHP programmer, how to implement group message sending records? The following will give you a brief introduction. 1. Understand the development knowledge related to WeChat public accounts. Before understanding how to implement group message sending records, I

Steps to implement WeChat public account development using PHP Steps to implement WeChat public account development using PHP Jun 27, 2023 pm 12:26 PM

How to use PHP to develop WeChat public accounts WeChat public accounts have become an important channel for promotion and interaction for many companies, and PHP, as a commonly used Web language, can also be used to develop WeChat public accounts. This article will introduce the specific steps to use PHP to develop WeChat public accounts. Step 1: Obtain the developer account of the WeChat official account. Before starting the development of the WeChat official account, you need to apply for a developer account of the WeChat official account. For the specific registration process, please refer to the official website of WeChat public platform

How to use PHP for WeChat development? How to use PHP for WeChat development? May 21, 2023 am 08:37 AM

With the development of the Internet and mobile smart devices, WeChat has become an indispensable part of the social and marketing fields. In this increasingly digital era, how to use PHP for WeChat development has become the focus of many developers. This article mainly introduces the relevant knowledge points on how to use PHP for WeChat development, as well as some of the tips and precautions. 1. Development environment preparation Before developing WeChat, you first need to prepare the corresponding development environment. Specifically, you need to install the PHP operating environment and the WeChat public platform

See all articles