3. WeChat public account development--explain the message processing and receiving process

foreword

        After receiving a message, WeChat will want to send a request in the form of a post to the set url address. The developer only needs to receive the request, parse it and make a response operation, and then respond to the data according to the format of the response. If the response fails, WeChat does not receive the response information from the server, or the format of the response is incorrect, the front end will display a similar prompt such as "The target server service has failed";

text

        The first is the entry of the program, which handles the request in the doPost() method of the servlet. and returns the xml string of the response;

@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// Call the core business class to receive and process messages
        String respXml = MessageControl.getControl().processMessageRequest(request);
        //System.out.println("respxml"+respXml);
        // response message
        PrintWriter out = response.getWriter();
        out.print(respXml);
        out.close();
		return;
	}
        The logic is very simple. Because the amount of code is small, it is divided into two steps. First, the core business processing class MessageControl is called to process the message object, and then the result is written out to the page through the out stream;

        In the MessageControl class, most of the writing is about the judgment of the message type and the judgment of the event type, and then respond.

package com.wx.control;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import com.wx.service.ImageMsgService;
import com.wx.service.LinkMsgService;
import com.wx.service.LocationMsgService;
import com.wx.service.MenuService;
import com.wx.service.TextMsgService;
import com.wx.service.VideoMsgService;
import com.wx.service.VoiceMsgService;
import com.wx.service.impl.ImageMsgServiceImpl;
import com.wx.service.impl.LinkMsgServiceImpl;
import com.wx.service.impl.LocationMsgServiceImpl;
import com.wx.service.impl.MenuServiceImpl;
import com.wx.service.impl.TextMsgServiceImpl;
import com.wx.service.impl.VideoMsgServiceImpl;
import com.wx.service.impl.VoiceMsgServiceImpl;
import com.wx.util.MessageUtil;

import life.book.util.LogPersist;
import life.book.util.LogPersist.Path;
import life.book.util.Utils;

/**
 * User:Jiahengfei --> [email protected]
 *created by April 29, 2018 from Eclipse.
 * describe:Message receiving and responding controller
 */
public class MessageControl implements Path{
	private static MessageControl control;
	private MessageControl(){}
	public static MessageControl getControl(){if(control==null){control=new MessageControl();}return control;}
	
	private TextMsgService text = new TextMsgServiceImpl();
	private VideoMsgService video = new VideoMsgServiceImpl();
	private ImageMsgService image = new ImageMsgServiceImpl();
	private VoiceMsgService link = new VoiceMsgServiceImpl();
	private LocationMsgService location = new LocationMsgServiceImpl();
	private LinkMsgService voice = new LinkMsgServiceImpl();
	
	private MenuService menu = new MenuServiceImpl();
	
	/**
     * Process requests from WeChat
     * @param request
     * @return xml
     */
    public String processMessageRequest(HttpServletRequest request) {
    	// message data in xml format
        String respXml = null;
        try {
            // Call the parseXml method to parse the request message
            Map<String, String> map = MessageUtil.parseXml(request);
            // message type
            String msgType = map.get("MsgType");
            
            //persistent log
            String[] params = {Utils.getTime(),map.get("MsgType"),map.get("FromUserName"),map.get("Content")};
            LogPersist.getOperation().log().csv(this, params);
            System.out.println("AE:"+map.get("MsgType"));

            // text message
            if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_TEXT)) {
            	respXml = text.dispose(map);
            }
            // image message
            else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_IMAGE)) {
            	respXml = image.dispose(map);
            }
            // Voice messages
            else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_VOICE)) {
            	respXml = voice.dispose(map);
            }
            // video message
            else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_VIDEO)) {
            	respXml = video.dispose(map);
            }
            // video message
            else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_SHORTVIDEO)) {
            	respXml = video.dispose(map);
            }
            // geolocation message
            else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_LOCATION)) {
            	respXml = location.dispose(map);
            }
            // link message
            else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_LINK)) {
            	respXml = link.dispose(map);
            }
            // event push
            else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_EVENT)) {
                // event type
                String eventType = map.get("Event");
                // focus on
                if (eventType.equals(MessageUtil.EVENT_TYPE_SUBSCRIBE)) {
                	respXml = MessageUtil.Default.text(map, "Thank you for being so talented and following me
}
                // unsubscribe
                else if (eventType.equals(MessageUtil.EVENT_TYPE_UNSUBSCRIBE)) {
                    // After TODO unsubscribes, the user will no longer receive messages from the public account, so no reply is required
                }
                // Scan the QR code with parameters
                else if (eventType.equals(MessageUtil.EVENT_TYPE_SCAN)) {
                    // TODO handles scanning the QR code event with parameters
                }
                // report location
                else if (eventType.equals(MessageUtil.EVENT_TYPE_LOCATION)) {
                    // TODO handles reporting geolocation events
                }
                // custom menu
                else if (eventType.equals(MessageUtil.EVENT_TYPE_CLICK)) {
                	// TODO handles the menu click event
                	String key = map.get("EventKey");
                	if (key!=null) {
                		respXml = menu.rstOnclickMenu(key, map);
					}
                }
            }
            if (respXml==null) {respXml = MessageUtil.Default.text(map, "The message you are currently sending cannot be identified automatically, it has been handed over to customer service for processing, please wait for the customer service to reply, thank you for your support and understanding!") ;}
        } catch (Exception e) {
            e.printStackTrace ();
        }
        return respXml;
    }
	@Override
	public String gainPath() {
		return LogPersist.getOperation().path("wx/textmsg");
	}
}

        I don't know what to write about this, but it's just that it's not fully displayed, so I have to rewrite it several times! ! !

        To sum up, after a user sends a message, it is first passed to the WeChat server. After the WeChat server wraps the message, it is passed to the corresponding developer server for data processing. After the developer server receives it, it will parse and process the message. Parse into a map set, then judge the type of the message, and then respond to the corresponding service to process the data, package the processing result into a string in xml format, and return it to the WeChat server, which parses the data and then passes it to the Client display;
        in this control class, we have made judgments on almost all WeChat message types and event push types, and have respectively opened the corresponding services to deal with these problems, so after this control class is written, the general process of subsequent development No matter how the Chinese demand changes and the business increases, this category will not change much.
        This is the whole process of processing WeChat public account messages. As for the specific processing, I will explain it with a case of text message processing in the next chapter;

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325732673&siteId=291194637