A detailed description of ASP. NET Realization WeChat public account interface Development method

Source: Internet
Author: User
Tags cdata sha1 sha1 encryption
This article is a detailed explanation of ASP. NET implementation of the public account interface development method, interested in small partners can refer to

Speaking of public accounts, we are not unfamiliar, using this platform can add a new bright spot to the website or system, go directly to the point bar, before use must carefully read the official API documentation.
Ways to use the. NET implementation:
Interface Address page code:


Weixin _wx = new Weixin (); String poststr = ""; if (Request.HttpMethod.ToLower () = = "Post") {Stream s = System.Web.HttpContext.Current.Request.InputStream; byte[] B = NE W Byte[s.length]; S.read (b, 0, (int) s.length); Poststr = Encoding.UTF8.GetString (b); if (!string. IsNullOrEmpty (POSTSTR))//Request processing {_wx. Handle (POSTSTR); }} else {_wx. Auth (); }

Specific processing classes


<summary>///Public Platform operation class///</summary> Common class Weixin {private String Token = "My_weixin_token";//change from own token public void Auth () {String echostr = system.web.httpcontext.current.request.querystring["Echostr"]; if ( Checksignature ())//Verify that the signature is correct {if (!string). IsNullOrEmpty (ECHOSTR)) {System.Web.HttpContext.Current.Response.Write (ECHOSTR);//Return the original value to indicate a validation success System.Web.HttpContext.Current.Response.End (); }}} public void Handle (string poststr) {//Encapsulation request class XmlDocument doc = new XmlDocument (); Doc. LOADXML (POSTSTR); XmlElement rootelement = doc. DocumentElement; Msgtype XmlNode msgtype = Rootelement.selectsinglenode ("Msgtype"); Received value---> Receive Message Class (also known as message push) RequestXML RequestXML = new RequestXML (); Requestxml.tousername = Rootelement.selectsinglenode ("Tousername"). InnerText; Requestxml.fromusername = Rootelement.selectsinglenode ("Fromusername"). InnerText; Requestxml.createtime = Rootelement.selectsinglenode ("Createtime"). InnerText;  Requestxml.msgtype = Msgtype.innertext; UnderDifferent types are handled differently by switch (Requestxml.msgtype) {case "text"://text message requestxml.content = Rootelement.selectsinglenode (" Content "). InnerText; Break Case "image"://Picture Requestxml.picurl = Rootelement.selectsinglenode ("Picurl"). InnerText; Break Case ' location '://position requestxml.location_x = Rootelement.selectsinglenode ("location_x"). InnerText; requestxml.location_y = Rootelement.selectsinglenode ("location_y"). InnerText; Requestxml.scale = Rootelement.selectsinglenode ("scale"). InnerText; Requestxml.label = Rootelement.selectsinglenode ("Label"). InnerText; Break Case "link"://Links break; Case "Event"://Event push support v4.5+ break; }//Message reply responsemsg (requestxml); }///<summary>////* token, timestamp, nonce three parameters are ordered in dictionary order//* Three parameter strings are stitched into a string for SHA1 encryption//* Developers get encrypted strings can be compared with signature, which identifies the request from. </summary>//<returns></returns> private bool Checksignature () {String signature = System.Web.Ht tpcontext.current.request.querystring["signature"]; string timestamp = System.web.httpcontext.current.request.querystring["Timestamp"]; String nonce = system.web.httpcontext.current.request.querystring["nonce"]; Encryption/verification process://1. The token, timestamp, nonce three parameters of the dictionary order string[] arrtmp = {token, timestamp, nonce}; Array.Sort (arrtmp);//dictionary sort//2. Concatenation of three parameter strings into a string for SHA1 encryption of string tmpstr = string. Join ("", arrtmp); Tmpstr = FormsAuthentication.HashPasswordForStoringInConfigFile (tmpstr, "SHA1"); Tmpstr = Tmpstr.tolower (); 3. The developer obtains the encrypted string that can be compared to signature, which identifies the request from.  if (tmpstr = = signature) {return true;} else {return false;}} <summary>///message reply (Information return)///</summary>//<param name= "RequestXML" >the request Xml.</param > private void Responsemsg (RequestXML requestxml) {try {string resxml = ""; The main is to call the database for keyword matching automatic reply content, can be written according to their own business situation.  1. Usually, there is no match for any instruction when returning help information autoresponse mi = new Autoresponse (requestxml.content, requestxml.fromusername); Switch (requestxml.msgtype) {case "text"://Perform a series of actions here to enable automatic reply content. String _remsg = mi. Getremsg (); if (mi.msgtype = = 1) {resxml = "<xml><tousername><![ cdata["+ requestxml.fromusername +"]]></tousername><fromusername><! [cdata["+ Requestxml.tousername +"]]></fromusername><createtime> "+ convertdatetimeint (DateTime.Now ) + "</createtime><msgtype><! [cdata[news]]></msgtype><content><! [cdata[]]></content><articlecount>2</articlecount><articles> "; Resxml + = mi. Getrepic (Requestxml.fromusername); Resxml + = "</Articles><FuncFlag>1</FuncFlag></xml>"; } else {resxml = "<xml><tousername><![ cdata["+ requestxml.fromusername +"]]></tousername><fromusername><! [cdata["+ Requestxml.tousername +"]]></fromusername><createtime> "+ convertdatetimeint (DateTime.Now ) + "</createtime><msgtype><! [cdata[text]]></msgtype><content><! [cdata["+ _remsg +"]]></content><funcflag>1</funcflag></xml> "; } break; Case ' location ': string city = Getmapinfo (requestxml.location_x, requestxml.location_y); if (city = = "0") {resxml = "<xml><tousername><![ cdata["+ requestxml.fromusername +"]]></tousername><fromusername><! [cdata["+ Requestxml.tousername +"]]></fromusername><createtime> "+ convertdatetimeint (DateTime.Now ) + "</createtime><msgtype><! [cdata[text]]></msgtype><content><! [cdata[OK, we know where you are. You can: "+ mi. Getdefault () + "]]></content><funcflag>1</funcflag></xml>"; } else {resxml = "<xml><tousername><![ cdata["+ requestxml.fromusername +"]]></tousername><fromusername><! [cdata["+ Requestxml.tousername +"]]></fromusername><createtime> "+ convertdatetimeint (DateTime.Now ) + "</createtime><msgtype><! [cdata[text]]></msgtype><content><! [cdata[OK, we know where you are. You can: "+ mi. Getdefault () + "]]&GT;</content><funcflag>1</funcflag></xml> "; } break; Case "image"://Text mixed message format Please see the official API "reply to text message" break; } System.Web.HttpContext.Current.Response.Write (Resxml); Writetodb (RequestXML, Resxml, mi.pid); } catch (Exception ex) {//writetxt ("exception:" + ex. Message + "struck:" + ex. Stacktrace.tostring ()); Wx_logs. Myinsert ("Exception:" + ex.) Message + "struck:" + ex. Stacktrace.tostring ()); }}///<summary>//Unix time converted to datetime//</summary>//<param name= "TimeStamp" ></param>// <returns></returns> private datetime unixtimetotime (String timeStamp) {datetime Dtstart = TimeZone.CurrentTimeZone.ToLocalTime (New DateTime (1970, 1, 1)); Long ltime = long. Parse (TimeStamp + "0000000"); TimeSpan Tonow = new TimeSpan (Ltime); Return Dtstart.add (Tonow); }//<summary>//datetime converted to Unixtime///</summary>/<param name= "Time" ></param>//<r eturns></returns> private int Convertdatetimeint (System.DateTime Time) {System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime (New System.DateTime (1970, 1, 1)); return (int) ( Time-starttime). TotalSeconds; }///<summary>///Call Baidu Map, return coordinate information///</summary>//<param name= "y" > Longitude </param>//<param NA  Me= "x" > Latitude </param>//<returns></returns> public string Getmapinfo (string x, string y) {try {string res = string. Empty; String parame = String. Empty;  String url = "Http://maps.googleapis.com/maps/api/geocode/xml";  Parame = "latlng=" + x + "," + y + "&language=zh-cn&sensor=false";//This key is for personal application res = webrequestpost (URL, parame); XmlDocument doc = new XmlDocument (); Doc.  LOADXML (RES); XmlElement rootelement = doc. DocumentElement; String status = Rootelement.selectsinglenode ("status").  InnerText; if (Status = = "OK") {//Only get city XmlNodeList xmlresults = Rootelement.selectsinglenode ("/geocoderesponse"). ChildNodes; for (int i = 0; i < Xmlresults.count; i++) {XmlNode childnode = xmlresults[i]; IF (childnode.name = = "status") {continue;} string city = "0"; for (int w = 0, W < childNode.ChildNodes.Count; w++) {for (int q = 0; q < childnode.childnodes[w]. Childnodes.count; q++) {XmlNode childetwo = childnode.childnodes[w]. CHILDNODES[Q]; if (Childetwo.name = = "Long_name") {city = Childetwo.innertext;} else if (Childetwo.innertext = = "locality") {return CI Ty }}} return city; }}} catch (Exception ex) {//writetxt ("Map exception:" + ex. Message.tostring () + "struck:" + ex. Stacktrace.tostring ()); return "0"; } return "0"; }///<summary>///Post Submit call Crawl///</summary>//<param name= "url" > Submit address </param>//<param Name= "param" > Parameters </param>//<returns>string</returns> public string webrequestpost (string URL, string param) {byte[] bs = System.Text.Encoding.UTF8.GetBytes (param); HttpWebRequest req = (HttpWebRequest) httpwebrequest.create (url + "?" + param); Req. Method = "Post"; Req. Timeout = 120 * 1000; Req. ContentType = "Application/x-www-form-urlencoded; "; Req. ContentLength = BS.  Length; using (Stream Reqstream = req. GetRequestStream ()) {reqstream.write (BS, 0, BS). Length); Reqstream.flush (); } using (WebResponse WR = req. GetResponse ()) {//In this connection the received page content is processed by Stream STRM = wr. GetResponseStream ();  StreamReader sr = new StreamReader (STRM, System.Text.Encoding.UTF8); String line; System.Text.StringBuilder sb = new System.Text.StringBuilder (); while (line = Sr. ReadLine ()) = null) {sb. Append (line + System.Environment.NewLine); } Sr. Close (); Strm. Close (); Return SB. ToString (); }}///<summary>//To save this interactive information to the database///</summary>//<param name= "RequestXML" ></param>//&lt ;p Aram Name= "_xml" ></param>///<param name= "_pid" ></param> private void Writetodb (RequestXML RequestXML, string _xml, int _pid) {weixinmsg wx = new Weixinmsg (); wx. Fromusername = Requestxml.fromusername; Wx. Tousername = Requestxml.tousername; Wx. Msgtype = Requestxml.msgtype; Wx. MSG = Requestxml.conTent Wx. Creatime = Requestxml.createtime; Wx. location_x = requestxml.location_x; Wx. location_y = requestxml.location_y; Wx. Label = Requestxml.label; Wx. scale = Requestxml.scale; Wx. Picurl = Requestxml.picurl; wx.reply = _xml; Wx.pid = _pid; try {wx. ADD (); } catch (Exception ex) {//wx_logs. Myinsert (ex. Message); Ex.message; } } }

Response Class Model


 #region Request Class RequestXML//<summary>///Request class///</summary> public class RequestXML {private String Touserna me = "";  <summary>///Message receiver number, general public platform account number///</summary> publicly string Tousername {get {return tousername;} set { Tousername = value; }} private String fromusername = ""; <summary>////Message Sender///</summary> public string Fromusername {get {return fromusername;} set {Fromus Ername = value; }} private String createtime = "";  <summary>//Create Time///</summary> public string Createtime {get {return createtime;} set {createtime = Value }} private String msgtype = ""; <summary>///Information Type: location, text message: text, message type: image///</summary> public string Msgtype {get {return Msgtype;  } set {Msgtype = value;}} private String content = "";  <summary>///information content///</summary> public string content {get {return content;} set {content = value;} } private String location_x = "";<summary>///geographical latitude///</summary> public string Location_x {get {return location_x;} set {location_x = value; }} private String location_y = "";  <summary>//location longitude///</summary> public string Location_y {get {return location_y;} set {location_y = value; }} private String scale = "";  <summary>///MAP zoom Small///</summary> public string Scale {get {return scale;} set {scaled = value;}} private String label = "";  <summary>///location information///</summary> public string Label {get {return label;} set {label = value;}} private string picurl = ""; <summary>///Image link, developers can get the///</summary> public string Picurl {get {return picurl;} set {pic) with HTTP GET URL = value; }}} #endregion

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.