asp.net realization of micro-credit public account Interface development Tutorial-practical skills

Source: Internet
Author: User
Tags auth cdata datetime httpcontext sha1 sha1 encryption

Speaking of micro-credit public accounts, we will not be unfamiliar with the use of this platform can give the website or system to add a new bright spot, directly to the point, before use must carefully read the official API documentation.
methods to use. NET implementations:
//micro-letter 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 = new 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 class

<summary>///Micro-trust platform Operation Class///</summary> public class Weixin {private String Token = "My_weixin_token "; 
Replace it with your 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 indicates the validation succeeded 
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"); 
The value received---> 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; Different processing switch (requestxml.msgtype) {case "text" according to different types://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>///Authentication Micro-Letter Signature///* token, timestamp, nonce three parameters are sorted in dictionary///* concatenation of three parameter strings into a string for SHA1 encryption///* Developer 
The encrypted string can be compared with signature to identify the request from the micro-letter. </summary>///<returns></returns> private bool Checksignature () {String signature = system.web . Httpcontext.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. 
Sort Token, timestamp, nonce three parameters in dictionary order string[] arrtmp = {Token, timestamp, nonce}; Array.Sort (arrtmp);//dictionary sort//2. Concatenation of three parameter strings into a string SHA1 encrypt string tmpstr = string. 
Join ("", arrtmp); 
Tmpstr = FormsAuthentication.HashPasswordForStoringInConfigFile (tmpstr, "SHA1"); 
Tmpstr = Tmpstr.tolower (); 
3. The developer obtains the encrypted string to compare with the signature, which identifies the request from the micro-letter. 
if (tmpstr = = signature) {return true; 
else {return false; }///<summary>///message reply (micro-information return)///</summary>///<param name= "RequestXML" >the request XML.&L 
t;/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 matching any instructions when returning help information autoresponse mi = new Autoresponse (requestxml.content, requestxml.fromusername);
 
Switch (requestxml.msgtype) {case "text"://Perform a series of actions here to implement the 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[Well, 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[Well, we know where you are. You can: "+ mi." 
Getdefault () + "]]></content><funcflag>1</funcflag></xml>"; 
} break; 
Case "image"://Text mixed message specific format see the official API "reply message" break; 
} System.Web.HttpContext.Current.Response.Write (Resxml); 
Writetodb (RequestXML, Resxml, mi.pid); The catch (Exception ex) {//writetxt ("exception:" + ex.) Message + "struck:" + ex. 
Stacktrace.tostring ()); Wx_logs. Myinsert ("Exception:" + ex.) Message + "struck:" + ex. 
Stacktrace.tostring ()); }///<summary>///Unix time conversion to datetime///</summary>///<param name= "TimeStamp" &GT;&LT;/PARAM&G 
T <returns></returns> private datetime unixtimetotime (String timeStamp) {datetime Dtstart = Timezone.cur 
Renttimezone.tolocaltime (New DateTime (1970, 1, 1)); Long ltime = long. 
Parse (TimeStamp + "0000000"); 
TimeSpan Tonow = new TimeSpan (ltime); 
Return Dtstart.add (Tonow); }///<summary>/DateTime conversion to Unixtime///</summary>///<param name= "Time" ></param>///<returns></return s> private int Convertdatetimeint (System.DateTime time) {System.DateTime starttime = TimeZone.CurrentTimeZone.ToLoc 
Altime (New System.DateTime (1970, 1, 1)); return (int) (time-starttime). 
TotalSeconds; ///<summary>///call Baidu Map, return coordinates information///</summary>///<param name= "y" > Longitude </param>///<p Aram name= "x" > Latitude </param>///<returns></returns> public string Getmapinfo (string x, string y) {T ry {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 applies for the individual 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 gets the 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 city; 
}} return to City; {//writetxt (Exception Ex)}} catch ("Map exception:" + ex.) Message.tostring () + "struck:" + ex. 
Stacktrace.tostring ()); 
return "0"; 
return "0"; ///<summary>///Post commit call crawl///</summary>///<param name= "url" > Submit address </param>/// ;p Aram 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 (); The using (WebResponse WR = req. GetResponse ()) {//Here the content of the received page is processed 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>///saves this interactive information to the database///</summary>///<param name= "RequestXML" ></param> <param 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 (); The catch (Exception ex) {//wx_logs. Myinsert (ex. 
message); 
Ex.message; 
 } 
} 
}

Response class model

 
#region Micro-Letter Request Class RequestXML///<summary>///Micro-letter Request Class///</summary> public class RequestXML {private str 
ing tousername = ""; <summary>///message receiver micro-signal, generally for the public platform account micro-signal///</summary> Common string Tousername {get {return tousername ; 
set {tousername = value;} 
private string fromusername = ""; 
<summary>///message Sender micro-signal///</summary> public string Fromusername {got {return fromusername;} 
set {fromusername = value;} 
private string createtime = ""; 
<summary>///creation Time///</summary> public string Createtime {get {return createtime;} 
set {createtime = value;} 
private string msgtype = ""; <summary>///Information Type Geography: location, Text message: text, message type: Image///</summary> public string Msgtype {get {RE Turn Msgtype; 
set {Msgtype = value;} 
private String content = ""; <summary>///Information Content///</summary> public string content {get {return content; 
The 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>///Geographical 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 {scale = value;} 
private String label = ""; 
<summary>///Geographic Information///</summary> public string Label {get {return Label;} 
set {label = value;} 
private string picurl = ""; 
<summary>///Picture links, developers can get///</summary> public string Picurl {getting {return Picurl} with HTTP gets 
set {Picurl = value;}  }} #endregion

This article has been sorted out to the ASP. NET micro-Credit Development tutorial Summary, you are welcome to learn to read.

By reading this article, you will probably know how to achieve the micro-trust of the public account interface development, I hope this article is helpful to everyone's study.

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.