WeChat development series ---- 02: implement POST request response

Source: Internet
Author: User
Tags openid website server
This article mainly introduces the development series ---- 02: implementing POST request response GitHub address of the project: Https://github.com/Andyahui/xgyxsh_WeiXin

I. XML POST request processing

Yesterday we became a developer, indicating that the get request can be processed in the end. The following is what we browsed through the URL we configured in the browser.

We can find that the returned 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 us and the website server gets what we want through the POST request, we must encrypt the transmission.

////// After the user sends a message, the platform automatically posts a request here and waits for the XML response. /// PS: This method is a simplified method with the same effect as OldPost. /// Versions later than v0.8 can be combined with the Senparc. Weixin. MP. MvcExtension extension package to use WeixinResult. for details, refer to the MiniPost method. ///[HttpPost] [ActionName ("Index")] public ActionResult Post (PostModel postModel) {postModel. token = Token; // postModel. encodingAESKey = ""; // keep consistent with your background settings // postModel. appId = AppId; // keep consistent with your background settings // verify the digital signature if (! CheckSignature. Check (postModel. Signature, postModel. Timestamp, postModel. Nonce, Token )){//??? There is a problem here. if there is no comment, there will be an error here, that is, there is a problem with the digital signature. // Return Content ("Parameter error! ");} // 1: Customize MessageHandler, where the detailed judgment operation on the request is located. Instantiated a class var messageHandler = new CustomMessageHandle (Request. InputStream, postModel); // receives the message // 2: executes the processing process-ResponseMessage will have a value after execution. MessageHandler. Execute (); // 3: return new FixWeixinBugWeixinResult (messageHandler); there is a line feed problem. // Return new FixWeixinBugWeixinResult (messageHandler. toString (); // 3: pay attention to the third ---- to solve the temporary addition of the line feed bug of the official 5.0 software, you can return new WeixinResult (messageHandler) using the following method ); // v0.8 +}

We can clearly see the meaning of each line above. here I have a question, if you do not comment in the verification of digital signatures, the "Parameter error" is directly displayed. the following operations will not be continued, but there is no comment in the official website blog. why ?? (Please answer .)

The preceding steps are as follows:

First, the CustomMessageHandle object is instantiated, and the corresponding parameters are passed, initialized through the corresponding CTOR, and then its Execute () method is called, finally, the corresponding CustomMessageHandle object is returned by instantiating WeixinResult. at this time, the object contains the logic processing method of our website background.

This is the processing of our POST request. every xml message forwarded by the server will be forwarded here again in the form of a POST request for processing.

II. learn about MessageHandler

To complete the development, you need to understand the key classes in the SDK. The following describes MessageHandler;

MessageHandler is the core of the SDK for processing messages. it mainly processes POST requests. We can also make logical judgments. to put it bluntly, all our business logic is under this class. <消息和事件> . This is an abstract class. we need to implement it again through inheritance. The specific implementation is as follows. Here is the official interpretation WiKi.

Namespace XGY_WeiXin.WeiXinHelper {public class CustomMessageHandle: MessageHandler
 
  
{// PostModel: indicates the values, timestamps, and strings obtained from the server. (Used in WeiXinController) // The inputStream of the constructor is used to receive the request stream from the server (XDocument can be input here if it needs to be processed externally ). Public CustomMessageHandle (Stream inputSrream, PostModel postModel): base (inputSrream, postModel ){}///
  /// The abstract class must be implemented ------ function: used to return a message. If no message of the corresponding type is processed by the code, the result is returned by default. //////
  Request message///
  Public override IResponseMessageBase DefaultResponseMessage (IRequestMessageBase requestMessage) {// CreateResponseMessage
  
   
Here is to create a put back object, representing different types, var responseMessage = base. CreateResponseMessage
   
    
(); // ResponseMessageText can be changed to another type: responseMessage. Content = "this message comes from DefaultResponseMessage. "; Return responseMessage ;}///
    /// 1: process text messages sent by the user. Override the OnTextRequest method. /// -------- (Summary: The method can be used to read the database, determine the keyword, or even return different ResponseMessageXX types (as long as the final type is under the ireeclipsemessagebase interface ). //////
    Request message///
    Public override IResponseMessageBase OnTextRequest (RequestMessageText requestMessage) {// CreateResponseMessage
    <类型>
     
Create ResponseMessage of the specified type based on the current RequestMessage; create the corresponding message. var responseMessage = base. CreateResponseMessage
     
      
(); ResponseMessage. Content = "your OpenID is:" + requestMessage. FromUserName + ". \ R \ t you sent the text: "+ requestMessage. Content; return responseMessage ;}}}
     
    
   
  
 

From top to bottom. It is found that it is inherited from MessageHandler, but there is a CustomMessageContext behind it. at this time, we have a new understanding of MessageHandler. this product was originally a generic abstract class and we need to fill in a type in it, check the official description that CustomMessageContext is a custom context class. I have not studied it carefully. please refer to the official introduction (WiKi ). The following is a CTOR, which is mainly used for instantiation. Note that one of the parameters is the request stream. InputSrream, One is the data Class sent by the server PostModel.Next we will implement the method. The first method is the DefaultResponseMessage method, which must be implemented. Because it is data that does not respond to requests, messages are sent to the server by default. Finally, the text processing is completed. here, the OnTextRequest method is override to respond to the user's text information request. If we need to implement other processing methods, such as video, voice, and geographic location, we can rewrite other methods to return the corresponding message type.

3. Custom context CustomMessageContext

The following is the custom context class CustomMessageContext, which inherits from MessageContext. .

////// Custom context class ----> process the dialog state of a single user. ///Public class CustomMessageContext: MessageContext
 
  
{Public CustomMessageContext () {base. MessageContextRemoved + = CustomMessageContext_MessageContextRemoved ;}///
  /// Time triggered when the context expires and is removed ///Private void CustomMessageContext_MessageContextRemoved (object sender, Senparc. Weixin. Context. WeixinContextRemovedEventArgs
  
   
E) {/* Note that this event is not triggered in real time (of course you can also write a thread monitor) * to improve efficiency, according to the WeixinContext algorithm, the expired message will be cleared before the next request is executed */var messageContext = e. messageContext as CustomMessageContext; if (messageContext = null) {// if the call is normal, messageContext will not be null return;} // TODO: the logic for message expiration is executed as needed. the following code is for reference only // Log. infoFormat ("The message context of {0} has expired", e. openId); // api. sendMessage (e. openId, "your customer service status has exited because you have not initiated customer service for a long time! ");}}
  
 

According to the official explanation, the version has been upgraded (WiKi) and I think it will be a big article in the future.

IV. Test No.

At this point, the underlying framework is successfully built. we can see the response of text processing after we release and deploy it on the server.

For more development series ---- 02: POST request response related articles, please follow the PHP Chinese network!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.