. NET WeChat development code example of public account message processing

Source: Internet
Author: User
Tags openid
This article tells you about the message processing related to the public account in. net public account development. it is very detailed. For more information, see. I. Preface

The message processing on the public platform is still relatively complete. The basic principles of basic text messages, text messages, image messages, voice messages, video messages, and music messages are the same, however, the xml data in the post is different. before processing the message, read the official document mp.weixin.qq.com/wiki/14/89b871b5466b19b3efa4ada8e577d45e.html. First, we start with the most basic text message processing.


 
  toUser
  
  fromUser
  
  
   
12345678
  
  text
  
  你好
  
 

We can see that this is the most basic mode of message processing, including the sender, receiver, creation time, type, content, and so on.

First, we create a class for message processing. this class is used to capture all message requests and process different message replies according to different message request types.


Public class WeiXinService {////// TOKEN ///Private const string TOKEN = "finder ";////// Signature ///Private const string SIGNATURE = "signature ";////// Timestamp ///Private const string TIMESTAMP = "timestamp ";////// Random number ///Private const string NONCE = "nonce ";////// Random string ///Private const string ECHOSTR = "echostr ";/////////Private HttpRequest Request {get; set ;}////// Constructor //////Public WeiXinService (HttpRequest request) {this. Request = request ;}////// 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 ";}}////// Process the request //////
 Private string ResponseMsg () {string requestXml = CommonWeiXin. ReadRequest (this. Request); IHandler handler = HandlerFactory. CreateHandler (requestXml); if (handler! = Null) {return handler. HandleRequest ();} return string. Empty ;}////// 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 ;}}}
  
 

Let's take a look at how we capture messages first. The code for Default. ashx on the homepage is as follows:

Public void ProcessRequest (HttpContext context) {context. response. contentType = "text/html"; string postString = string. empty; if (HttpContext. current. request. httpMethod. toUpper () = "POST") {// 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 () ;}else {string token = "wei2414201"; if (string. isNullOrEmpty (token) {return;} string echoString = HttpContext. current. request. queryString ["echoStr"]; string signature = HttpContext. current. request. queryString ["signature"]; string timestamp = HttpContext. current. request. queryString ["timestamp"]; string nonce = HttpContext. current. request. queryString ["nonce "]; If (! String. IsNullOrEmpty (echoString) {HttpContext. Current. Response. Write (echoString); HttpContext. Current. Response. End ();}}}

From the code above, we can see that messages in the WeiXinService. cs class are crucial.

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

IHandler is a message processing interface, which is implemented by the EventHandler and TextHandler processing class. The code is as follows:

////// Processing interface ///Public interface IHandler {////// Process the request //////
 String HandleRequest ();}

EventHandler

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. equals ("subscribe", StringComparison. ordinalIgnoreCase) // used to determine if it is the first time to pay attention to {PicTextMessage tm = new PicTextMessage (); // A text message processing class tm created by myself. toUserName = em. fromUserName; tm. fromUserName = em. toUserName; tm. createTime = CommonWeiXin. getNowTime (); response = tm. generateContent () ;}return response ;}}

TextHandler

////// Text information processing class ///Public class TextHandler: IHandler {string openid {get; set;} string access_token {get; set ;}////// Request XML ///Private string RequestXml {get; set ;}////// Constructor //////Request xmlPublic TextHandler (string requestXml) {this. RequestXml = requestXml ;}////// Process the request //////
 Public string HandleRequest () {string response = string. empty; TextMessage tm = TextMessage. loadFromXml (RequestXml); string content = tm. content. trim (); if (string. isNullOrEmpty (content) {response = "You have not entered anything. you cannot help you. ";} Else {string username = System. configuration. configurationManager. appSettings ["weixinid"]. toString (); AccessToken token = AccessToken. get (username); access_token = token. access_token; openid = tm. fromUserName; response = HandleOther (content);} tm. content = response; // the sender and receiver are converted to string temp = tm. toUserName; tm. toUserName = tm. fromUserName; tm. fromUserName = temp; response = tm. generateContent (); return response ;}////// Process other messages /////////
 Private string HandleOther (string requestContent) {string response = string. empty; if (requestContent. contains ("Hello") | requestContent. contains ("Hello") {response = "Hello ~ ";} Else if (requestContent. contains ("openid") | requestContent. contains ("id") | requestContent. contains ("ID") // match the keyword {response = "your Openid:" + openid;} else if (requestContent. contains ("token") | requestContent. contains ("access_token") {response = "your access_token:" + access_token;} else {response = "try other keywords. ";}Return response ;}}

HandlerFactory

////// Processor factory class ///Public class HandlerFactory {////// Create a processor //////Request xml///
 
  
IHandler object
 Public static IHandler CreateHandler (string requestXml) {IHandler handler = null; if (! String. isNullOrEmpty (requestXml) {// Parse data XmlDocument doc = new System. xml. xmlDocument (); doc. loadXml (requestXml); XmlNode node = doc. selectSingleNode ("/xml/MsgType"); if (node! = Null) {XmlCDataSection section = node. FirstChild as XmlCDataSection; if (section! = Null) {string msgType = section. value; switch (msgType) {case "text": handler = new TextHandler (requestXml); break; case "event": handler = new EventHandler (requestXml ); break ;}}} return handler ;}}

Here, the basic classes have been completed. now, let's follow our public account, and we will send a text message, enter some of our keywords, and return some messages, for example, input the id to return the user's openid.

II. PicTextMessage

Public class PicTextMessage: Message {////// Static template field ///Private static string m_Template ;////// Default constructor ///Public PicTextMessage () {this. MsgType = "news ";}////// Load text messages from xml data //////Public static PicTextMessage LoadFromXml (string xml) {PicTextMessage tm = null; if (! String. IsNullOrEmpty (xml) {XElement element = XElement. Parse (xml); if (element! = Null) {tm = new PicTextMessage (); tm. fromUserName = element. element (CommonWeiXin. FROM_USERNAME ). value; tm. toUserName = element. element (CommonWeiXin. TO_USERNAME ). value; tm. createTime = element. element (CommonWeiXin. CREATE_TIME ). value ;}} return tm ;}////// Template ///Public override string Template {get {if (string. IsNullOrEmpty (m_Template) {LoadTemplate () ;}return m_Template ;}}////// Generate content //////
 Public override string GenerateContent () {this. createTime = CommonWeiXin. getNowTime (); string str = string. format (this. template, this. toUserName, this. fromUserName, this. createTime); return str ;}////// Load the template ///Private static void LoadTemplate () {m_Template = @"
               
  {0}
                
  {1}
                
  
   
{2}
                
  news
  1                              
                  
   <! [CDATA [Welcome to a parking space!]>                 
   如有问题请致电400-6238-136或直接在留言,我们将第一时间为您服务!
                   
   http://www.baidu.com/youwei.jpg
                   
   http://www.baidu.com
                   
                            
 ";}}

Finally, our results are as follows;

The above is the details of the sample code for public message processing developed by. NET. For more information, see other related articles on 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.