. Net Implementation of WeChat public account interface development instance code

Source: Internet
Author: User

Speaking of public accounts, there are no strangers. Using this platform can add a new highlight to the website or system and directly go to the topic. before using this platform, you must carefully read the official API documentation.
API documentation address: http://mp.weixin.qq.com/wiki/index.php

Methods implemented using. net:
// Interface address Page code:

Copy codeThe Code is as follows:
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

Copy codeThe Code is as follows:
/// <Summary>
/// Public platform operations
/// </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 () // check whether the signature is correct
{
If (! String. IsNullOrEmpty (echoStr ))
{
System. Web. HttpContext. Current. Response. Write (echoStr); // The original value indicates that the verification is successful.
System. Web. HttpContext. Current. Response. End ();
}
}
}

 
Public void Handle (string postStr)
{
// Encapsulate the 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 called 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;

// Perform different Processing Based on Different Types
Switch (requestXML. MsgType)
{
Case "text": // text message
RequestXML. Content = rootElement. SelectSingleNode ("Content"). InnerText;
Break;
Case "image": // image
RequestXML. PicUrl = rootElement. SelectSingleNode ("PicUrl"). InnerText;
Break;
Case "location": // location
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": // link
Break;
Case "event": // event push supports V4.5 +
Break;
}

// Message reply
ResponseMsg (requestXML );
}

 
/// <Summary>
/// Verify the signature
/// * Sort tokens, timestamp, and nonce in Lexicographic Order.
/// * Splice the three parameter strings into one string for sha1 Encryption
/// * The encrypted string obtained by the developer can be compared with signature to identify the request source.
/// </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 the tokens, timestamp, and nonce in Lexicographic Order.
String [] ArrTmp = {Token, timestamp, nonce };
Array. Sort (ArrTmp); // dictionary sorting
// 2. splice the three parameter strings into one string for sha1 Encryption
String tmpStr = string. Join ("", ArrTmp );
TmpStr = FormsAuthentication. HashPasswordForStoringInConfigFile (tmpStr, "SHA1 ");
TmpStr = tmpStr. ToLower ();
// 3. The encrypted string obtained by the developer can be compared with signature to identify the request source.
If (tmpStr = signature)
{
Return true;
}
Else
{
Return false;
}
}

/// <Summary>
/// Message reply (message return)
/// </Summary>
/// <Param name = "requestXML"> The request XML. </param>
Private void ResponseMsg (RequestXML requestXML)
{
Try
{
String resxml = "";
// It is mainly used to call the database to perform keyword matching and automatically reply to the content. You can write the content based on your own business conditions.
// 1. Usually, no matching command is returned.
AutoResponse mi = new AutoResponse (requestXML. Content, requestXML. FromUserName );

Switch (requestXML. MsgType)
{
Case "text ":
// Perform a series of operations here to automatically reply to the 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 [Okay, 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 [Okay, we know where you are. You can: "+ mi. GetDefault () +"]> </Content> <FuncFlag> 1 </FuncFlag> </xml> ";
}
Break;
Case "image ":
// For details about the format of text-and-text message, see the official API "Reply 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>
/// Convert unix time 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>
/// Convert datetime to unixtime
/// </Summary>
/// <Param name = "time"> </param>
/// <Returns> </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 and return coordinates
/// </Summary>
/// <Param name = "y"> longitude </param>
/// <Param name = "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 an individual 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 ")
{
// Obtain only 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 city;
}
}
}
Catch (Exception ex)
{
// WriteTxt ("map exception:" + ex. Message. ToString () + "Struck:" + ex. StackTrace. ToString ());
Return "0 ";
}
Return "0 ";
}

 
/// <Summary>
/// Post submit call capture
/// </Summary>
/// <Param name = "url"> submission address </param>
/// <Param name = "param"> parameter </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 ())
{
// Process the received page content here
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>
/// Save the interaction 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 ();
}
Catch (Exception ex)
{
// Wx_logs.MyInsert (ex. Message );
// Ex. message;
}
}
}

Response class MODEL

Copy codeThe Code is as follows:
# Region request class RequestXML
/// <Summary>
/// Request class
/// </Summary>
Public class RequestXML
{
Private string toUserName = "";
/// <Summary>
/// Message recipient number, which is generally the public platform account number
/// </Summary>
Public string ToUserName
{
Get {return toUserName ;}
Set {toUserName = value ;}
}

Private string fromUserName = "";
/// <Summary>
/// Message sender ID
/// </Summary>
Public string FromUserName
{
Get {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 geographic location: 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>
/// Geographic location and latitude
/// </Summary>
Public string Location_X
{
Get {return location_X ;}
Set {location_X = value ;}
}

Private string location_Y = "";
/// <Summary>
/// Geographic longitude
/// </Summary>
Public string Location_Y
{
Get {return location_Y ;}
Set {location_Y = value ;}
}

Private string scale = "";
/// <Summary>
/// Map zoom
/// </Summary>
Public string Scale
{
Get {return scale ;}
Set {scale = value ;}
}

Private string label = "";
/// <Summary>
/// Geographic location information
/// </Summary>
Public string Label
{
Get {return label ;}
Set {label = value ;}
}

Private string picUrl = "";
/// <Summary>
/// Image link, which can be obtained by developers through HTTP GET
/// </Summary>
Public string PicUrl
{
Get {return picUrl ;}
Set {picUrl = value ;}
}
}
# Endregion

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.