In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article mainly introduces an example analysis of the construction of the basic framework for the development of Wechat public platform, which has a certain reference value. Interested friends can refer to it. I hope you will learn a lot after reading this article. Now let the editor take you to know about it.
Wechat Public platform Development course-basic Framework Building
First of all, we design the module hierarchy diagram, of course, the diagram only gives a way of implementation, not limited to this. See the picture below for details.
The main functions are as follows:
1) request the interface layer. Handle HTTP requests and responses
2) Distribution layer. The request is passed in from the interface layer, then the request type is analyzed and distributed to different processors
3) Business logic layer. Here is our specific business logic, according to the request, the implementation of specific business logic.
4) data layer. We may need to access data, either a database or a file, when implementing an application. If it is a simple application, it may not have this layer.
In fact, the specific application can be extended on this structure, such as message object layer, business object layer, data access layer, function management layer and so on. This is just a way of thinking, not limited to it.
According to the hierarchical diagram, the design flow chart, specifically describes the implementation of each process. In order to understand the whole process. As shown in the following figure:
According to the flow chart, we can clearly understand the whole process and the specific implementation steps of message processing.
Let's do a code implementation for each process.
First, receive HTTP requests
We need a HttpHandler or a web page to handle Wechat server HTTP requests.
Here we use HttpHandler. Because of its high flexibility and good performance.
The specific implementation is as follows.
Public class WeiXinHttpHandler:IHttpHandler {/ public bool IsReusable {get {return true } / public void ProcessRequest (HttpContext context) {/ / the request is received by Wechat service, 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 ();}}
If it is HTTPHandler, you need to configure the specific application in the configuration file. We will not explain the specific node configuration. To give an example directly, configure the HttpHandler node as follows
II. Distribute the request
In order to encapsulate the function, we also encapsulate this in the processing component. It can actually be placed in HttpHandler.
1) verify the signature
If this is the first request, you need to verify the signature. It's the equivalent of a HTTP handshake. In the previous chapter, you set the server URL and token values, which is to verify that the link is successful.
This request is a GET request. The following is specified (official):
Business logic:
Encryption / verification process:
The three parameters token, timestamp and nonce are sorted in dictionary order.
Concatenate three parameter strings into one string for SHA1 encryption
The encrypted string obtained by the developer can be compared with signature, indicating that the request originated from Wechat
The official only provides PHP code examples, many things are not available in C # literal translation. So there is also some specific treatment here. Let's 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 translated it into the C# version:
/ check 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 } / / encryption string new_signature = SecurityUtility.SHA1Encrypt (input); / / verify if (new_signature = = signature) {return true;} else {return false;}}
SHA1 encryption is required here, and 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 the request
Then there are the specific message requests, which are all POST requests.
Because there are many message types, we encapsulate them through the factory class, and then each message has a special processor for processing. Specific implementation logic:
/ 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 that handles 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" }} / / processing message if (method = = "POST") {return ResponseMsg ();} else {return "cannot be processed";}} III. Message processor specifically handles messages
1) message type
First of all, let's take a look at the specific type of message. in fact, the interface of the message has been clearly given in the previous one.
Here, let's take a look at the specific types of messages requested and replied.
It is important to note that the requested message is a text type, and the reply message is not necessarily text, but can be any kind of recoverable message, such as picture and text, music and so on. See the table below for details.
2) the message class is designed according to the specific message interface.
The class diagram is given here for reference.
3) for different messages, there will be different processors. Let's take a look at the specific class diagram.
4) specific business processing
Each handler can handle specific requests. What messages are entered, access to that data, invocation of services, and so on, are handled here.
It is also recommended that you encapsulate the specific business separately. In Handler, only the calling API is provided.
Because with the increase of business, a Handler may have to deal with a lot of business, if all the operation logic is written here, it is bound to affect reading, and it is not easy to maintain and expand.
5) generate a reply message
After the request is processed, a reply message needs to be generated and responded to the terminal. Message format, that is, we introduce those message types, but must be available for reply, currently supported are: text, graphics, music, and so on.
Be clear: the message type of reply does not have to be the same as the message type of the request, for example, the request is text, the reply can be picture and text, music.
The process of generating a reply message is, in fact, the process of formatting a specific message object into a corresponding XML, and then responding the XML to the Wechat server.
6) instance
Here, Wechat users follow the public account, and then the server handles the event request, registers the user, and prompts the welcome message.
Class EventHandler: IHandler {/ requested 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 welcome message TextMessage tm = new TextMessage (); tm.ToUserName = em.FromUserName Tm.FromUserName = em.ToUserName; tm.CreateTime = Common.GetNowTime (); tm.Content = "Welcome to follow xxx. I'm Xiao Wei. Is there anything I can do for you? " ; response = tm.GenerateContent ();} return response;}} IV. HTTP response
Finally, the processing result is returned to the original HttpHandler, and the response is sent to the Wechat server for direct Response processing. This is also implemented in HttpHandler, which was originally designed.
The following is a code snippet. For more information, please see Http request.
Context.Response.Clear (); context.Response.Charset = "UTF-8"; context.Response.Write (responseMsg); context.Response.End () Thank you for reading this article carefully. I hope the article "sample Analysis of the basic Framework for the Development of Wechat Public platform" shared by the editor will be helpful to you. At the same time, I also hope that you will support and pay attention to the industry information channel. More related knowledge is waiting for you to learn!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.