Home  >  Article  >  WeChat Applet  >  WeChat public platform development: Understanding MessageHandler

WeChat public platform development: Understanding MessageHandler

高洛峰
高洛峰Original
2017-02-27 12:00:561968browse

Continuing the code from the previous article, we continue to add a CustomMessageHandle.cs class to the project:

WeChat public platform development: Understanding MessageHandler

CustomMessageHandle.cs needs to inherit Senparc.Weixin.MP.MessageHandlers may be as follows:

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using Senparc.Weixin.MP.Entities;
using Senparc.Weixin.MP.MessageHandlers;
 
namespace Senparc.Weixin.MP.Sample.Weixin
{
    public class CustomMessageHandler : MessageHandler<CustomMessageContext>
    {
        public CustomMessageHandler(Stream inputStream, PostModel postModel)
            : base(inputStream, postModel)
        {
 
        }
 
        public override IResponseMessageBase DefaultResponseMessage(IRequestMessageBase requestMessage)
        {
            var responseMessage = base.CreateResponseMessage<ResponseMessageText>(); //ResponseMessageText也可以是News等其他类型
            responseMessage.Content = "这条消息来自DefaultResponseMessage。";
            return responseMessage;
        }
    }
}

We can see that the abstract method that must be rewritten and implemented is called DefaultResponseMessage(). This piece of information is used to return a message. If the corresponding WeChat messages of type (such as voice) are not processed by the code, so the results here will be returned by default.

In the DefaultResponseMessage() method, we see this sentence:

var responseMessage = base.CreateResponseMessage<ResponseMessageText>(); //ResponseMessageText也可以是News等其他类型

The CreateResponseMessage method here creates a return object. T can be any of the following types, corresponding to Different return types:

ResponseMessageText - corresponding to text messages

ResponseMessageNews - corresponding to graphic messages

ResponseMessageMusic - corresponding to music messages

ResponseMessageXXX - other types And so on

Regarding the setting methods of all the above types of parameters, you can see the Demo of the open source project, which will not be repeated here: https://github.com/JeffreySu/WeiXinMPSDK.

So how do we process the text messages sent by users?

It's very simple - just rewrite an OnTextRequest method:

public override IResponseMessageBase OnTextRequest(RequestMessageText requestMessage)
{
    var responseMessage = base.CreateResponseMessage<ResponseMessageText>();
    responseMessage.Content = "您的OpenID是:" + requestMessage.FromUserName      //这里的requestMessage.FromUserName也可以直接写成base.WeixinOpenId
                            + "。\r\n您发送了文字信息:" + requestMessage.Content;  //\r\n用于换行,requestMessage.Content即用户发过来的文字内容
    return responseMessage;
}

You can play freely in this method, such as reading the database, judging keywords, and even returning different ResponseMessageXX types (as long as the final The types are all under the IResponseMessageBase interface).

Corresponds to OnTextRequest. If we want to process messages of voice, geographical location, menu and other types, we only need to rewrite the corresponding method. The methods that can be rewritten are as follows:

public virtual IResponseMessageBase OnImageRequest(RequestMessageImage requestMessage);
        public virtual IResponseMessageBase OnLinkRequest(RequestMessageLink requestMessage);
        public virtual IResponseMessageBase OnLocationRequest(RequestMessageLocation requestMessage);
        public virtual IResponseMessageBase OnTextRequest(RequestMessageText requestMessage);
        public virtual IResponseMessageBase OnVoiceRequest(RequestMessageVoice requestMessage);
        public virtual IResponseMessageBase OnVideoRequest(RequestMessageVideo requestMessage);


        public virtual IResponseMessageBase OnEvent_ClickRequest(RequestMessageEvent_Click requestMessage);
        public virtual IResponseMessageBase OnEvent_ViewRequest(RequestMessageEvent_View requestMessage);
        public virtual IResponseMessageBase OnEvent_EnterRequest(RequestMessageEvent_Enter requestMessage);
        public virtual IResponseMessageBase OnEvent_LocationRequest(RequestMessageEvent_Location requestMessage);
        public virtual IResponseMessageBase OnEvent_SubscribeRequest(RequestMessageEvent_Subscribe requestMessage);
        public virtual IResponseMessageBase OnEvent_UnsubscribeRequest(RequestMessageEvent_Unsubscribe requestMessage);
        public virtual IResponseMessageBase OnEvent_ScanRequest(RequestMessageEvent_Scan requestMessage)
        public virtual IResponseMessageBase OneEvent_MassSendJobFinisRequest(RequestMessageEvent_MassSendJobFinish requestMessage)

Among them, OnEvent_XX corresponds are all subtypes of Event requests.

When setting the base class of CustomMessageHandler, we saw that a generic type called MessageContext is used (MessageHandler). This MessageContext is a default message context processing class provided by the SDK. This class has It can handle the most basic situations. If your application is not very complex, just use this class directly. If the project is more complex, you can also write your own class (inheriting the IMessageContext interface) according to your own needs, or inherit this class to extend some more attributes (such as workflow and distributed cache, etc.).

So far we have used MassageHandler to handle all requests sent by WeChat users.

Here are some of the "secret weapons" of MassageHandler.

OnExecuting() and OnExecuted()

We can override these two methods directly. OnExecuting will be executed before all message processing methods (such as OnTextRequest, OnVoiceRequest, etc.) are executed. During this process, we can set CancelExecute to true to interrupt the execution of all subsequent methods (including OnExecuted), for example:

public override void OnExecuting()
{
    if (RequestMessage.FromUserName == "olPjZjsXuQPJoV0HlruZkNzKc91E")
    {
        CancelExcute = true; //终止此用户的对话
     
        //如果没有下面的代码,用户不会收到任何回复,因为此时ResponseMessage为null
 
        //添加一条固定回复
        var responseMessage = CreateResponseMessage<ResponseMessageText>();
        responseMessage.Content = "Hey!你已经被拉黑啦!";
 
        ResponseMessage = responseMessage;//设置返回对象
    }
}

If there is no interruption in OnExecuting, when, for example, the OnTextRequest method is executed (or the default method is executed), the OnExecuted() method will be triggered, and we can also rewrite it accordingly. It should be noted that within the OnExecuted() method, ResponseMessage has been assigned a return value.

More WeChat public platform development: To learn about MessageHandler-related articles, please pay attention to the PHP Chinese website!

Statement:
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