. NET WeChat public account development public account message processing,. net public

Source: Internet
Author: User
Tags openid

. NET public account development-public account message processing,. net public account

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, we should carefully read the document officially given to us: Response. First, we start with the most basic text message processing.

<Xml> <ToUserName> <! [CDATA [toUser]> </ToUserName> <FromUserName> <! [CDATA [fromUser]> </FromUserName> <CreateTime> 12345678 </CreateTime> <MsgType> <! [CDATA [text]> </MsgType> <Content> <! [CDATA [Hello]> </Content> </xml>

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 {// <summary> /// TOKEN // </summary> private const string TOKEN = "finder "; /// <summary> /// SIGNATURE /// </summary> private const string signature = "SIGNATURE "; /// <summary> /// TIMESTAMP /// </summary> private const string timestamp = "TIMESTAMP "; /// <summary> /// random number /// </summary> private const string NONCE = "nonce "; /// <summary> /// random string /// </summary> private const s Tring ECHOSTR = "echostr"; // <summary> /// </summary> private HttpRequest Request {get; set ;} /// <summary> /// constructor /// </summary> /// <param name = "request"> </param> public WeiXinService (HttpRequest request) {this. request = request;} // <summary> // process the Request, generate a Response /// </summary> /// <returns> </returns> public string Response () {string method = Request. httpMethod. toUpper (); // verify the signature if (meth Od = "GET") {if (CheckSignature () {return Request. queryString [ECHOSTR];} else {return "error" ;}}// process the message if (method = "POST") {return ResponseMsg ();} else {return "unable to process ";}} /// <summary> /// process the request /// </summary> /// <returns> </returns> private string ResponseMsg () {string requestXml = CommonWeiXin. readRequest (this. request); IHandler handler = HandlerFactory. createHandler (requestXml ); If (handler! = Null) {return handler. handleRequest ();} return string. empty ;} /// <summary> /// check the signature /// </summary> /// <param name = "request"> </param> /// <returns> </returns> private bool CheckSignature () {string signature = Request. queryString [SIGNATURE]; string timestamp = Request. queryString [TIMESTAMP]; string nonce = Request. queryString [NONCE]; List <string> list = new List <string> (); 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.

/// <Summary> /// process the request /// </summary> /// <returns> </returns> 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:

/// <Summary> /// processing interface /// </summary> public interface IHandler {// <summary> /// process the request /// </summary> /// <returns> </returns> string HandleRequest ();}

EventHandler

Class EventHandler: IHandler {// <summary> // request xml // </summary> private string RequestXml {get; set ;} /// <summary> /// constructor /// </summary> /// <param name = "requestXml"> </param> public EventHandler (string requestXml) {this. requestXml = requestXml;} // <summary> // process the request // </summary> /// <returns> </returns> 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

/// <Summary> // text information processing class /// </summary> public class TextHandler: IHandler {string openid {get; set;} string access_token {get; set ;}//< summary> /// request XML /// </summary> private string RequestXml {get; set ;} /// <summary> /// constructor /// </summary> /// <param name = "requestXml"> request xml </param> public TextHandler (string requestXml) {this. requestXml = requestXml;} // <summary> // process the request /// </Summary> // <returns> </returns> 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. generateConte Nt (); return response ;} /// <summary> /// process other messages /// </summary> /// <param name = "tm"> </param> /// <returns> </returns> 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

/// <Summary> /// processor factory class /// </summary> public class HandlerFactory {/// <summary> /// create a processor /// </summary> /// <param name = "requestXml"> request xml </param> // <returns> IHandler object </returns> 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 {// <summary> // static template field /// </summary> private static string m_Template; /// <summary> /// default constructor /// </summary> public PicTextMessage () {this. msgType = "news ";} /// <summary> /// load text messages from xml data /// </summary> /// <param name = "xml"> </param> 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 ;}/// <summary >/// Template //</summary> public override string Template {get {if (string. isNullOrEmpty (m_Template) {LoadTemplate ();} return m_Templ Ate ;}//< summary> /// generated content //</summary> /// <returns> </returns> public override string GenerateContent () {this. createTime = CommonWeiXin. getNowTime (); string str = string. format (this. template, this. toUserName, this. fromUserName, this. createTime); return str ;}/// <summary> // load the template /// </summary> private static void LoadTemplate () {m_Template = @ "<xml> <ToUserName> <! [CDATA [{0}]> </ToUserName> <FromUserName> <! [CDATA [{1}]> </FromUserName> <CreateTime> {2} </CreateTime> <MsgType> <! [CDATA [news]> </MsgType> <ArticleCount> 1 </ArticleCount> <Articles> <item> <Title> <! [CDATA [welcome to a parking space!]> </Title> <Description> <! [CDATA [if you have any questions, please call 400-6238-136 or leave a message directly. We will serve you as soon as possible]> </Description> <PicUrl> <! [CDATA [ http://www.baidu.com /Youwei.jpg]> </PicUrl> <Url> <! [CDATA [ http://www.baidu.com ]> </Url> </item> </Articles> </xml> ";}}

Finally, our results are as follows;

The above is all the content of this article. I hope you will like it.

Related Article

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.