. NET micro-credit public number development of public number message processing _ Practical skills

Source: Internet
Author: User
Tags cdata httpcontext openid

I. Preface

The message processing of the micro-credit public platform is still quite perfect, have the most basic text message, to the message, to the picture message, voice message, video message, music message its basic principles are the same, but the post of the XML data is different, before processing the message, we have to read carefully, Official documents to us: http://mp.weixin.qq.com/wiki/14/89b871b5466b19b3efa4ada8e577d45e.html. First we start with the most basic text message processing.

<tousername><![ Cdata[touser]]></tousername>
<fromusername><![ cdata[fromuser]]></fromusername>
<msgtype ><! [cdata[text]]></msgtype>
<content><![ cdata[Hello]]></content>

We can see that this is one of the most basic patterns of message processing, with senders, recipients, creation times, types, content, and so on.

First we create a class of message processing, which is used to capture all message requests and handle different message responses based on different message request types.

public class Weixinservice {///<summary>///TOKEN///</summary> Private Const string to
    KEN = "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 string ECHOSTR = "Echostr";
    <summary>//////</summary> private HttpRequest Request {get; set;} <summary>///Constructor///</summary>///<param name= "request" ></param> public We Ixinservice (HttpRequest request) {this.
    request = Request; ///<summary>///processing requests, generating responses///</summary>///<returns></returns> Public St Ring Response () {string method = Request.HttpMethod.ToUpper (); Verify that the signature if (method = = "Get") {if (Checksignature ()) {return Request.querystring[ech
        else {return "error";
      }//Process message if (method = = "POST") {return responsemsg ();
      else {return ' cannot be processed ';  }///<summary>///processing request///</summary>///<returns></returns> Private String Responsemsg () {String requestxml = Commonweixin.readrequest (this.
      Ihandler handler = Handlerfactory.createhandler (RequestXML); if (handler!= null) {return handler.
      HandleRequest (); return string.
    Empty;  ///<summary>///Check 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 (); Puzzle string input = string.
      foreach (var item in list) {input = = Item;
      }//Encrypt string new_signature = Securityutility.sha1encrypt (input);
      Verify if (new_signature = = signature) {return true;
      else {return false;



is here to see how we first capture the message. Home DEFAULT.ASHX code is as follows

    public void ProcessRequest (HttpContext context) {context.

      Response.ContentType = "text/html"; String poststring = String.
      Empty; if (HttpContext.Current.Request.HttpMethod.ToUpper () = = "POST") {//By the micro-service to receive the request, the specific processing request Weixinservice W Xservice = new Weixinservice (context.
        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 above code we can see that the messages in the WeiXinService.cs class are critical.

    ///processing request
    Private String responsemsg ()
      string requestxml = Commonweixin.readrequest (this. Request);
      Ihandler handler = Handlerfactory.createhandler (requestxml);
      if (handler!= null)
        handler. HandleRequest ();

      return string. Empty;

Ihandler is a message processing interface that has the following Eventhandler,texthandler processing classes to implement this interface. The code is as follows

  ///Processing interface
  ///</summary> public
  interface Ihandler
    ///< summary>
    ///processing request
    string HandleRequest ();


Class Eventhandler:ihandler {///<summary>///requested XML///</summary> private string requ
    estxml {get; set;}  <summary>///Constructor///</summary>///<param name= "RequestXML" ></param> public EventHandler (String requestxml) {this.
    RequestXML = RequestXML; ///<summary>///processing request///</summary>///<returns></returns> public string HandleRequest () {string response = string.
      Eventmessage em = eventmessage.loadfromxml (RequestXML); if (em. Event.equals ("subscribe", stringcomparison.ordinalignorecase))//used to determine whether the first concern is {Pictextmessage TM = new PicT Extmessage ()///I created a message processing Class TM. Tousername = em.
        Fromusername; Tm. Fromusername = em.
        Tousername; Tm.
        Createtime = Commonweixin.getnowtime (); Response = TM.

      Generatecontent ();
    return response;



  <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>///processing request///</summary>///<returns></returns> public string HandleRequest () {string response = string.
      TextMessage TM = Textmessage.loadfromxml (RequestXML); String content = tm.
      Content.trim (); if (string. IsNullOrEmpty (content)) {response = "You have not entered anything, can not help you ah."
      "; else {string username = system.configuration.configurationmanager.appsettings["Weixinid"].
      ToString ();    Accesstoken token = accesstoken.get (username);
          Access_token = Token.access_token; OpenID = TM.
      Response = handleother (content); } TM.
      Content = response; For sender, receiver conversion String temp = TM.
      Tousername; Tm. Tousername = TM.
      Fromusername; Tm.
      Fromusername = temp; Response = TM.
      Generatecontent ();
    return response; ///<summary>///processing Other messages///</summary>///<param name= "TM" ></param>///&L T;returns></returns> private String Handleother (String requestcontent) {string response = STRING.E
      if (Requestcontent.contains ("Hello") | | | requestcontent.contains ("hello")) {response = "you are OK"; }else if (requestcontent.contains ("OpenID") | | | requestcontent.contains ("id") | | requestcontent.contains ("ID"))//
      Keywords used to match user input {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;



  <summary>///Processor Factory class///</summary> public class Handlerfactory {///<summary>/ Create processor///</summary>///<param name= "RequestXML" > Requested xml</param>///
      Ler object </returns> public static Ihandler Createhandler (String requestxml) {Ihandler = 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.

                Switch (msgtype) {case "text": handler = new Texthandler (requestxml);
              Break Case "Event": Handler = new EventHandler (requEstxml);
    }}} return handler;


Some of the basic classes here have been completed, now we have to complete, pay attention to our micro-letter public number, we will send a message, and input some of our keywords, return some messages, such as input ID to return the user's OpenID and so on.

Two. Pictextmessage

public class Pictextmessage:message {///<summary>///template static field///</summary> private STA

    Tic string m_template; <summary>///Default constructor///</summary> public Pictextmessage () {this.
    Msgtype = "News";
    ///<summary>///Loads this message 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).
    } return TM; }///<summary>///templates///</summary> PublIC override string Template {get {if (string).
        IsNullOrEmpty (m_template)) {loadtemplate ();
      return m_template; }///<summary>///generate content///</summary>///<returns></returns> public o Verride string Generatecontent () {this.
      Createtime = Commonweixin.getnowtime (); String str= string. Format (this. Template, this. Tousername, this. Fromusername, this.
    return str; ///<summary>///Load template///</summary> private static void LoadTemplate () {M_tem plate= @ "<xml> <tousername><! [cdata[{0}]]></tousername> <fromusername><! [cdata[{1}]]></fromusername> <CreateTime>{2}</CreateTime> <MsgType> <!
              [cdata[news]]></msgtype> <ArticleCount>1</ArticleCount><Articles> <item> <title><! [cdata[has a stop to welcome you! ]]></title> <description><! [cdata[If you have any questions, please call 400-6238-136 or directly in the micro-mail message, we will be the first time to serve you!] ></Description> <picurl><! [cdata[http://www.baidu.com/youwei.jpg]]></picurl> <url><! [cdata[http://www.baidu.com]]></url> </item> </Articles> &L
    T;/xml> ";


Finally, our results are shown below;

The above mentioned is the entire content of this article, I hope you can enjoy

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.