In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-15 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article will explain in detail how .net realizes the development of Wechat public account interface. The editor thinks it is very practical, so I share it with you as a reference. I hope you can get something after reading this article.
Speaking of Wechat public accounts, you are no stranger. Using this platform can add a new highlight to the website or system, so get to the point and be sure to read the official API documents carefully before using it.
API document address: http://mp.weixin.qq.com/wiki/index.php
Methods implemented using .net:
/ / Wechat API address page code:
The 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 ()
}
Concrete processing class
The code is as follows:
/ / /
/ / Wechat public platform operation class
/ / /
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 whether the signature is correct
{
If (! string.IsNullOrEmpty (echoStr))
{
System.Web.HttpContext.Current.Response.Write (echoStr); / / return the original value to indicate that the verification is successful
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
/ / different processing according to different types
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": / / 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 support V4.5 +
Break
}
/ / reply to the message
ResponseMsg (requestXML)
}
/ / /
/ / verify Wechat signature
/ / * sort the three parameters token, timestamp and nonce in lexicographic order
/ / * concatenate three parameter strings into one string for sha1 encryption
/ * the encrypted string obtained by the developer can be compared with signature to indicate that the request originated from Wechat.
/ / /
/ / /
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. The three parameters token, timestamp and nonce are sorted in dictionary order.
String [] ArrTmp = {Token, timestamp, nonce}
Array.Sort (ArrTmp); / / dictionary sort
/ / 2. Concatenate 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 indicate that the request originated from Wechat.
If (tmpStr = = signature)
{
Return true
}
Else
{
Return false
}
}
/ / /
/ / message reply (Wechat message is returned)
/ / /
/ The request XML.
Private void ResponseMsg (RequestXML requestXML)
{
Try
{
String resxml = ""
/ / it mainly calls the database for keyword matching and automatic reply content, which can be written according to your own business situation.
/ / 1. Usually, help information is returned when no instructions are matched.
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 = "" + ConvertDateTimeInt (DateTime.Now) + "2"
Resxml + = mi.GetRePic (requestXML.FromUserName)
Resxml + = "1"
}
Else
{
Resxml = "" + ConvertDateTimeInt (DateTime.Now) + "1"
}
Break
Case "location":
String city = GetMapInfo (requestXML.Location_X, requestXML.Location_Y)
If (city = = "0")
{
Resxml = "" + ConvertDateTimeInt (DateTime.Now) + "1"
}
Else
{
Resxml = "" + ConvertDateTimeInt (DateTime.Now) + "1"
}
Break
Case "image":
/ / for more information on the format of mixed messages, please see the official API "reply 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 ())
}
}
/ / /
/ convert unix time to datetime
/ / /
/ / /
/ / /
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)
}
/ / /
/ convert datetime to unixtime
/ / /
/ / /
/ / /
Private int ConvertDateTimeInt (System.DateTime time)
{
System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime (new System.DateTime (1970, 1,1))
Return (int) (time-startTime). TotalSeconds
}
/ / /
/ / call Baidu Map and return coordinate information
/ / /
/ / longitude
/ / Latitude
/ / /
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")
{
/ / get the city only
XmlNodeList xmlResults = rootElement.SelectSingleNode ("/ GeocodeResponse") .ChildNodes
For (int I = 0; I < xmlResults.Count; iTunes +)
{
XmlNode childNode = xmlResults [I]
If (childNode.Name = = "status") {
Continue
}
String city = "0"
For (int w = 0; w < childNode.ChildNodes.Count; walled +)
{
For (int Q = 0; Q < childNode.ChildNodes.Count; QNode.ChildNodes.Count)
{
XmlNode childeTwo = childNode.ChildNodes.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"
}
/ / /
/ Post submit call crawl
/ / /
/ / submit address
/ / parameters
/ string
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 ())
{
/ / the received page content is processed 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 ()
}
}
/ / /
/ / Save this interactive information to the database
/ / /
/ / /
/ / /
/ / /
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
The copy code is as follows:
# region Wechat request type RequestXML
/ / /
/ / Wechat request class
/ / /
Public class RequestXML
{
Private string toUserName = ""
/ / /
/ / the WeChat account of the recipient of the message, usually the Wechat account of the public platform.
/ / /
Public string ToUserName
{
Get {return toUserName;}
Set {toUserName = value;}
}
Private string fromUserName = ""
/ / /
/ / message sender's Wechat account
/ / /
Public string FromUserName
{
Get {return fromUserName;}
Set {fromUserName = value;}
}
Private string createTime = ""
/ / /
/ / creation time
/ / /
Public string CreateTime
{
Get {return createTime;}
Set {createTime = value;}
}
Private string msgType = ""
/ / /
/ / Information type Geographic location: location, text message: text, message type: image
/ / /
Public string MsgType
{
Get {return msgType;}
Set {msgType = value;}
}
Private string content = ""
/ / /
/ / Information content
/ / /
Public string Content
{
Get {return content;}
Set {content = value;}
}
Private string location_X = ""
/ / /
/ / Geographic location and latitude
/ / /
Public string Location_X
{
Get {return location_X;}
Set {location_X = value;}
}
Private string location_Y = ""
/ / /
/ / Geographic location longitude
/ / /
Public string Location_Y
{
Get {return location_Y;}
Set {location_Y = value;}
}
Private string scale = ""
/ / /
/ / Map Zoom size
/ / /
Public string Scale
{
Get {return scale;}
Set {scale = value;}
}
Private string label = ""
/ / /
/ / Geographic location information
/ / /
Public string Label
{
Get {return label;}
Set {label = value;}
}
Private string picUrl = ""
/ / /
/ Image link, which can be obtained by developers using HTTP GET
/ / /
Public string PicUrl
{
Get {return picUrl;}
Set {picUrl = value;}
}
}
# endregion
This is the end of the article on "how to achieve Wechat public account interface development". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, please share it for more people to see.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.