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

Home WeChat Applet WeChat Development WeChat Development Series----02: Implementing POST request response

WeChat Development Series----02: Implementing POST request response

Feb 14, 2017 am 11:17 AM

Project GitHub address: https://github.com/Andyahui/xgyxsh_WeiXin

One: WeChat XML POST request processing

Yesterday we became a developer, which shows that the get request can be processed to the end and is processed accordingly. The following is what we do through the browser The URL we configured is browsed to.

微信開(kāi)發(fā)系列----02:實(shí)現(xiàn)POST請(qǐng)求響應(yīng)

We can find that the return value set in the get request appears here, indicating that our test is successful. Next we need to set the Action corresponding to the POST request.

Note: Since every interaction between our WeChat and the website server is through a POST request to get what we want, we must encrypt the transmission.

        /// <summary>
        /// 用戶發(fā)送消息后,微信平臺(tái)自動(dòng)Post一個(gè)請(qǐng)求到這里,并等待響應(yīng)XML。
        /// PS:此方法為簡(jiǎn)化方法,效果與OldPost一致。
        /// v0.8之后的版本可以結(jié)合Senparc.Weixin.MP.MvcExtension擴(kuò)展包,使用WeixinResult,見(jiàn)MiniPost方法。
        /// </summary>
        [HttpPost]
        [ActionName("Index")]
        public ActionResult Post(PostModel postModel)
        {
            postModel.Token = Token;
            // postModel.EncodingAESKey = "";          //根據(jù)自己后臺(tái)的設(shè)置保持一致
            // postModel.AppId = AppId;                       //根據(jù)自己后臺(tái)的設(shè)置保持一致  
            //驗(yàn)證數(shù)字簽名
            if (!CheckSignature.Check(postModel.Signature, postModel.Timestamp, postModel.Nonce, Token))
            {
                //??? 這里有問(wèn)題,要是不注釋的話,就會(huì)在這里出錯(cuò),也就是數(shù)字簽名有問(wèn)題。
                //return Content("參數(shù)錯(cuò)誤!");
            }

            //  1:自定義MessageHandler,對(duì)微信請(qǐng)求的詳細(xì)判斷操作都在這里面。  實(shí)例化了一個(gè)類
            var messageHandler = new CustomMessageHandle(Request.InputStream, postModel);   //接收消息

            //  2:執(zhí)行微信處理過(guò)程----執(zhí)行完這里之后ResponseMessage才會(huì)有值。
            messageHandler.Execute();            

            //  3:return new FixWeixinBugWeixinResult(messageHandler); 這個(gè)有換行的問(wèn)題。           
            //return new FixWeixinBugWeixinResult(messageHandler.ToString());

            //  3:注意第三個(gè)----為了解決官方微信5.0軟件換行bug暫時(shí)添加的方法,平時(shí)用下面一個(gè)方法即可
            return new WeixinResult(messageHandler);                 //v0.8+
        }

We can clearly see the meaning of each line above. I have a question here. If the digital signature is verified without annotating the if judgment, it will directly display "Parameter error" "The following operations will not continue, but there is no comment in the official blog. I don't know why? ? (Ask God for answers.)

There are three main steps above:

First, the CustomMessageHandle object is instantiated and the corresponding parameters are passed. The corresponding CTOR is initialized, then its Execute() method is called, and finally the corresponding CustomMessageHandle object is returned by instantiating WeixinResult. At this time, the object contains the logical processing method of our website's backend.

This is how our POST request is processed , every time the xml information forwarded by the WeChat server will be forwarded here again using the POST request form, we will process it.

2: Understand MessageHandler

To complete WeChat development, you need to understand the key classes in the SDK. The following is simple Let’s talk about MessageHandler;

MessageHandler is the core of SDK processing messages. It mainly handles POST requests accordingly. Logical judgments can also be made. To put it bluntly, all our business logic is performed under this class. . This is an abstract class, we need to reimplement it through inheritance. The following is the specific implementation. "Here is the corresponding official explanationWiKi".

namespace XGY_WeiXin.WeiXinHelper
{
    public class CustomMessageHandle : MessageHandler<CustomMessageContext>
    {
        //PostModel:表示的都是從微信服務(wù)器里面得到的值,時(shí)間戳,字符串等。(WeiXinController中使用過(guò))
        //構(gòu)造函數(shù)的inputStream用于接收來(lái)自微信服務(wù)器的請(qǐng)求流(如果需要在外部處理,這里也可以傳入XDocument)。
        public CustomMessageHandle(Stream inputSrream,PostModel postModel):base(inputSrream,postModel)
        {            
        }
        /// <summary>
        /// 必須實(shí)現(xiàn)抽象的類------作用:用于放回一條信息,當(dāng)沒(méi)有對(duì)應(yīng)類型的微信消息沒(méi)有被代碼處理,那么默認(rèn)會(huì)執(zhí)行返回這里的結(jié)果。
        /// </summary>
        /// <param name="requestMessage">請(qǐng)求消息</param>
        /// <returns></returns>
    public override IResponseMessageBase DefaultResponseMessage(IRequestMessageBase requestMessage)
    {
        //CreateResponseMessage<T>  這里是創(chuàng)建一個(gè)放回的對(duì)象,代表不同的類型,
        var responseMessage = base.CreateResponseMessage<ResponseMessageText>();//ResponseMessageText可以更換為別的類型
        responseMessage.Content = "這條消息來(lái)自DefaultResponseMessage。";
        return responseMessage;
    }
         /// <summary>
        ///1: 處理用戶發(fā)送過(guò)來(lái)的文字消息。重寫OnTextRequest方法。
       /// --------(總結(jié):)方法里面可以自由發(fā)揮,讀取DB,判斷關(guān)鍵字,甚至返回不同的ResponseMessageXX類型(只要最終的類型都是在IResponseMessageBase接口下的即可)。
        /// </summary>
        /// <param name="requestMessage">請(qǐng)求消息</param>
        /// <returns></returns>
        public override IResponseMessageBase OnTextRequest(RequestMessageText requestMessage)
        {
            //CreateResponseMessage<類型>根據(jù)當(dāng)前的RequestMessage創(chuàng)建指定類型的ResponseMessage;創(chuàng)建相應(yīng)消息.
            var responseMessage = base.CreateResponseMessage<ResponseMessageText>();
            responseMessage.Content = "您的OpenID是:" + requestMessage.FromUserName + "。\r\t您發(fā)送了文字信息:" +
                                      requestMessage.Content;
            return responseMessage;
        }
    }
}

Analyze from top to bottom. I found that it is inherited from MessageHandler but there is a CustomMessageContext behind it. At this time, I have a new understanding of MessageHandler. This thing turns out to be a generic abstract class. We need to fill in a type in it. Check the official description and say that this CustomMessageContext is a custom I haven’t studied carefully what the defined context class is. Let’s look at the official introduction (WiKi). Then below is a CTOR, which is mainly used when instantiating . Pay attention to the parameters inside. One is the request stream inputSrream, and the other is the WeChat server. Sent data classPostModel. The next step is the method we implement. The first one is the DefaultResponseMessage method, which must be implemented. Because it handles data without response from WeChat requests, it sends messages to the WeChat server by default. Finally, it comes to text processing. The OnTextRequest method is overridden here so that it can respond to the user's text information request. If we need to implement other processing, such as pictures, voice, geographical location, etc., we can implement it by rewriting other methods separately and returning the corresponding message type.

Three: Custom context CustomMessageContext

下面是自定義上下文類CustomMessageContext,主要是繼承自MessageContext來(lái)實(shí)現(xiàn)對(duì)于的功能。

    /// <summary>
    /// 自定義的上下文類---->處理單個(gè)用戶的對(duì)話狀態(tài)。
    /// </summary>
    public class CustomMessageContext : MessageContext<IRequestMessageBase,IResponseMessageBase>
    {
        public CustomMessageContext()
        {
            base.MessageContextRemoved+=CustomMessageContext_MessageContextRemoved;
        }
        /// <summary>
        /// 當(dāng)上下文過(guò)期,被移除的時(shí)候觸發(fā)的時(shí)間
        /// </summary>
        private void CustomMessageContext_MessageContextRemoved(object sender, Senparc.Weixin.Context.WeixinContextRemovedEventArgs<IRequestMessageBase, IResponseMessageBase> e)
        {
            /* 注意,這個(gè)事件不是實(shí)時(shí)觸發(fā)的(當(dāng)然你也可以專門寫一個(gè)線程監(jiān)控)
            * 為了提高效率,根據(jù)WeixinContext中的算法,這里的過(guò)期消息會(huì)在過(guò)期后下一條請(qǐng)求執(zhí)行之前被清除
            */
            var messageContext = e.MessageContext as CustomMessageContext;
            if (messageContext==null)
            {
                //如果是正常的調(diào)用,messageContext不會(huì)為null
                return ;                 
            }
            //TODO:這里根據(jù)需要執(zhí)行消息過(guò)期時(shí)候的邏輯,下面的代碼僅供參考
            //Log.InfoFormat("{0}的消息上下文已過(guò)期",e.OpenId);
            //api.SendMessage(e.OpenId, "由于長(zhǎng)時(shí)間未搭理客服,您的客服狀態(tài)已退出!");
        }
    }

?? 解釋參考官方給的解釋,版本升級(jí)了(WiKi),我覺(jué)得這里以后還是會(huì)做大文章的。

四:微信測(cè)試號(hào)效果展示

?? 此時(shí)我們大體的底層框架就搭建成功了,我們發(fā)布部署到服務(wù)器上面就可以看到文本處理的響應(yīng)了。

微信開(kāi)發(fā)系列----02:實(shí)現(xiàn)POST請(qǐng)求響應(yīng)

這是微信的二維碼可以關(guān)注下,可以實(shí)現(xiàn)簡(jiǎn)單的互動(dòng)。

微信開(kāi)發(fā)系列----02:實(shí)現(xiàn)POST請(qǐng)求響應(yīng)

更多微信開(kāi)發(fā)系列----02:實(shí)現(xiàn)POST請(qǐng)求響應(yīng)?相關(guān)文章請(qǐng)關(guān)注PHP中文網(wǎng)!

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