WeChat public platform development tutorial (3) Basic framework construction

Source: Internet
Author: User
Tags php code examples sha1 encryption
This article mainly introduces the public platform development tutorial (3) Basic framework construction public platform development tutorial (3) Basic framework construction

In the previous chapter, we have explained the basic principles of public account development. today we will explore the design and implementation.

First, we designed the module hierarchy diagram. of course, the diagram only provides an implementation method, not limited to this. For details, see.

The main functions are as follows:

1) request interface layer. Process HTTP requests and responses

2) distribution layer. The request is passed in at the interface layer, and the request types are analyzed and distributed to different processors.

3) business logic layer. Here is our specific business logic. we implement specific business logic based on requests.

4) data layer. When implementing an application, we may need to access data, either a database or a file. This layer may not exist for simple applications.

In fact, specific applications can be expanded in this structure, and the message object layer, business object layer, data access layer, and function management layer can be extended. Here is just a way of thinking, not limited to this.

Based on the flowchart, we can clearly understand the entire process and the specific implementation steps of message processing.

The following code is implemented for each process.

1. receive HTTP requests

We need an HttpHandler or webpage to process the HTTP request from the server.

HttpHandler is used here. Because of its high flexibility and good performance.

The specific implementation is as follows.

Public class WeiXinHttpHandler: IHttpHandler {/////////Public bool IsReusable {get {return true ;}}////// Process the request //////Public void ProcessRequest (HttpContext context) {// The service receives the request. the specific processing request is WeiXinService wxService = new WeiXinService (context. request); string responseMsg = wxService. response (); context. response. clear (); context. response. charset = "UTF-8"; context. response. write (responseMsg); context. response. end ();}}

For HTTPHandler, you must configure the specific application in the configuration file. We will not describe the specific node configuration. An example is provided. configure the HttpHandler node as follows:

    
 

II. request distribution

To encapsulate functions, we also encapsulate this in processing components. In fact, it can be placed in HttpHandler.

1) verify the signature

For the first request, you must verify the signature. It is equivalent to an HTTP handshake. Previously, in the previous chapter, the server URL and token value set are used to check whether the link is successful.

This is a GET request. The following details (official ):

Business logic:

Encryption/verification process:

<1> sort the tokens, timestamp, and nonce in lexicographic order.

<2> splice the three parameter strings into one string for SHA1 encryption

<3> The encrypted string obtained by the developer can be compared with signature to identify that the request comes from

The official website only provides PHP code examples. many things are not literally translated in C. So there are some specific solutions here. First look at the official code:

    private function checkSignature()    {        $signature = $_GET["signature"];        $timestamp = $_GET["timestamp"];        $nonce = $_GET["nonce"];                            $token = TOKEN;        $tmpArr = array($token, $timestamp, $nonce);        sort($tmpArr);        $tmpStr = implode( $tmpArr );        $tmpStr = sha1( $tmpStr );                if( $tmpStr == $signature ){            return true;        }else{            return false;        }    }

We will translate it into C:

////// Check the signature /////////
 Private bool CheckSignature () {string signature = Request. QueryString [SIGNATURE]; string timestamp = Request. QueryString [TIMESTAMP]; string nonce = Request. QueryString [NONCE]; List
 
  
List = new List
  
   
(); List. add (TOKEN); list. add (timestamp); list. add (nonce); // sort list. sort (); // string input = string. empty; foreach (var item in list) {input + = item;} // encrypted string new_signature = SecurityUtility. SHA1Encrypt (input); // verify if (new_signature = signature) {return true;} else {return false ;}}
  
 

SHA1 encryption is required here. the specific algorithm is as follows:

////// SHA1 encryption //////Input string///
 
  
Encrypted string
 Public static string SHA1Encrypt (string intput) {byte [] StrRes = Encoding. default. getBytes (intput); HashAlgorithm mySHA = new SHA1CryptoServiceProvider (); StrRes = mySHA. computeHash (StrRes); StringBuilder EnText = new StringBuilder (); foreach (byte Byte in StrRes) {EnText. appendFormat ("{0: x2}", Byte);} return EnText. toString ();}

2) distribute requests

The next step is the specific message request. here all are POST requests.

Because there are multiple message types, we encapsulate them through the factory class, and then each message has a dedicated processor for processing. Specific implementation logic:

////// Process the request //////
 Private string ResponseMsg () {string requestXml = Common. ReadRequest (this. Request); IHandler handler = HandlerFactory. CreateHandler (requestXml); if (handler! = Null) {return handler. HandleRequest ();} return string. Empty ;}

The external method used to process the request (this is the method called by HttpHandler), that is:

////// Process the request and generate a response //////
 Public string Response () {string method = Request. httpMethod. toUpper (); // verify the signature if (method = "GET") {if (CheckSignature () {return Request. queryString [ECHOSTR];} else {return "error" ;}}// process the message if (method = "POST") {return ResponseMsg ();} else {return "unable to process ";}}

III. message processing by the message processor

1) message type

First, let's take a look at the specific message type. In fact, the message interface has been explicitly provided in the previous section.

Let's take a look at the specific types of request messages and types of reply messages.

Please note that the requested message is of the text type, and the reply message is not necessarily of the text type. it can be any type of reply message, such as text or music. See the following table for details.

4) specific business processing

Each handler can process specific requests. The input messages, access data, and call services are all processed here.

We recommend that you encapsulate specific services separately. In Handler, only called interfaces are provided.

As the business grows, a Handler may have to deal with many businesses. If all the operation logic is written here, reading will inevitably be affected and it is not easy to maintain and expand.

5) generate a reply message

After processing the request, you need to generate a reply message to respond to the terminal. The message format refers to the types of messages that are introduced, but must be used for reply. Currently, the supported types include text, text, and music.

It must be clear: the type of the reply message does not have to be the same as the type of the request message. for example, the request is text and the reply can be text or music.

The process of generating a reply message is actually the process of formatting a specific message object into the corresponding XML, and then responding the XML to the server.

6) instances

Here, the user pays attention to the public account, then the server processes the event request, registers the user, and prompts the welcome information.

Class EventHandler: IHandler {////// Request xml ///Private string RequestXml {get; set ;}////// Constructor //////Public EventHandler (string requestXml) {this. RequestXml = requestXml ;}////// Process the request //////
 Public string HandleRequest () {string response = string. empty; EventMessage em = EventMessage. loadFromXml (RequestXml); if (em. event = EventType. subscribe) {// registered User user User = new user (); User. openID = em. fromUserName; UserManager. regester (user); // reply to the welcome message TextMessage tm = new TextMessage (); tm. toUserName = em. fromUserName; tm. fromUserName = em. toUserName; tm. createTime = Common. getNowTime (); tm. C Ontent = "welcome to follow xxx. I am Xiaowei. Is there anything I can help you? "; Response = tm. GenerateContent () ;}return response ;}}

IV. HTTP response

Finally, return the processing result to the original HttpHandler and send the Response to the server. then, the Response is processed directly. This is also implemented in HttpHandler, which was initially designed.

The following is a code snippet. for details, see 1. Http request.

            context.Response.Clear();            context.Response.Charset = "UTF-8";            context.Response.Write(responseMsg);            context.Response.End();


For more public platform development tutorials (III) Basic framework construction 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.