今天就跟大家聊聊有關(guān)怎么在asp.net項目中開發(fā)一個微信公眾賬號接口,可能很多人都不太了解,為了讓大家更加了解,小編給大家總結(jié)了以下內(nèi)容,希望大家根據(jù)這篇文章可以有所收獲。
成都創(chuàng)新互聯(lián)公司專注于企業(yè)全網(wǎng)整合營銷推廣、網(wǎng)站重做改版、延平網(wǎng)站定制設(shè)計、自適應(yīng)品牌網(wǎng)站建設(shè)、H5開發(fā)、商城開發(fā)、集團公司官網(wǎng)建設(shè)、外貿(mào)營銷網(wǎng)站建設(shè)、高端網(wǎng)站制作、響應(yīng)式網(wǎng)頁設(shè)計等建站業(yè)務(wù),價格優(yōu)惠性價比高,為延平等各大城市提供網(wǎng)站開發(fā)制作服務(wù)。使用.net實現(xiàn)的方法:
//微信接口地址 頁面代碼:
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)) //請求處理 { _wx.Handle(postStr); } } else { _wx.Auth(); }
具體處理類
////// 微信公眾平臺操作類 /// public class weixin { private string Token = "my_weixin_token"; //換成自己的token public void Auth() { string echoStr = System.Web.HttpContext.Current.Request.QueryString["echoStr"]; if (CheckSignature()) //校驗簽名是否正確 { if (!string.IsNullOrEmpty(echoStr)) { System.Web.HttpContext.Current.Response.Write(echoStr); //返回原值表示校驗成功 System.Web.HttpContext.Current.Response.End(); } } } public void Handle(string postStr) { //封裝請求類 XmlDocument doc = new XmlDocument(); doc.LoadXml(postStr); XmlElement rootElement = doc.DocumentElement; //MsgType XmlNode MsgType = rootElement.SelectSingleNode("MsgType"); //接收的值--->接收消息類(也稱為消息推送) 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; //根據(jù)不同的類型進行不同的處理 switch (requestXML.MsgType) { case "text": //文本消息 requestXML.Content = rootElement.SelectSingleNode("Content").InnerText; break; case "image": //圖片 requestXML.PicUrl = rootElement.SelectSingleNode("PicUrl").InnerText; break; case "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": //鏈接 break; case "event": //事件推送 支持V4.5+ break; } //消息回復(fù) ResponseMsg(requestXML); } ////// 驗證微信簽名 /// * 將token、timestamp、nonce三個參數(shù)進行字典序排序 /// * 將三個參數(shù)字符串拼接成一個字符串進行sha1加密 /// * 開發(fā)者獲得加密后的字符串可與signature對比,標(biāo)識該請求來源于微信。 /// ///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"]; //加密/校驗流程: //1. 將token、timestamp、nonce三個參數(shù)進行字典序排序 string[] ArrTmp = { Token, timestamp, nonce }; Array.Sort(ArrTmp);//字典排序 //2.將三個參數(shù)字符串拼接成一個字符串進行sha1加密 string tmpStr = string.Join("", ArrTmp); tmpStr = FormsAuthentication.HashPasswordForStoringInConfigFile(tmpStr, "SHA1"); tmpStr = tmpStr.ToLower(); //3.開發(fā)者獲得加密后的字符串可與signature對比,標(biāo)識該請求來源于微信。 if (tmpStr == signature) { return true; } else { return false; } } /// /// 消息回復(fù)(微信信息返回) /// /// The request XML. private void ResponseMsg(RequestXML requestXML) { try { string resxml = ""; //主要是調(diào)用數(shù)據(jù)庫進行關(guān)鍵詞匹配自動回復(fù)內(nèi)容,可以根據(jù)自己的業(yè)務(wù)情況編寫。 //1.通常有,沒有匹配任何指令時,返回幫助信息 AutoResponse mi = new AutoResponse(requestXML.Content, requestXML.FromUserName); switch (requestXML.MsgType) { case "text": //在這里執(zhí)行一系列操作,從而實現(xiàn)自動回復(fù)內(nèi)容. string _reMsg = mi.GetReMsg(); if (mi.msgType == 1) { resxml = ""; } else { resxml = " " + ConvertDateTimeInt(DateTime.Now) + " 2 "; resxml += mi.GetRePic(requestXML.FromUserName); resxml += " 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": //圖文混合的消息 具體格式請見官方API“回復(fù)圖文消息” break; } System.Web.HttpContext.Current.Response.Write(resxml); WriteToDB(requestXML, resxml, mi.pid); } catch (Exception ex) { //WriteTxt("異常:" + ex.Message + "Struck:" + ex.StackTrace.ToString()); //wx_logs.MyInsert("異常:" + ex.Message + "Struck:" + ex.StackTrace.ToString()); } } /// " + ConvertDateTimeInt(DateTime.Now) + " 1 /// unix時間轉(zhuǎn)換為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); } /// /// datetime轉(zhuǎn)換為unixtime /// /// ///private int ConvertDateTimeInt(System.DateTime time) { System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1)); return (int)(time - startTime).TotalSeconds; } /// /// 調(diào)用百度地圖,返回坐標(biāo)信息 /// /// 經(jīng)度 /// 緯度 ///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";//此key為個人申請 res = webRequestPost(url, parame); XmlDocument doc = new XmlDocument(); doc.LoadXml(res); XmlElement rootElement = doc.DocumentElement; string Status = rootElement.SelectSingleNode("status").InnerText; if (Status == "OK") { //僅獲取城市 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異常:" + ex.Message.ToString() + "Struck:" + ex.StackTrace.ToString()); return "0"; } return "0"; } /// /// Post 提交調(diào)用抓取 /// /// 提交地址 /// 參數(shù) ///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()) { //在這里對接收到的頁面內(nèi)容進行處理 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(); } } ////// 將本次交互信息保存至數(shù)據(jù)庫中 /// /// /// /// 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; } } }
響應(yīng)類MODEL
#region 微信請求類 RequestXML ////// 微信請求類 /// public class RequestXML { private string toUserName = ""; ////// 消息接收方微信號,一般為公眾平臺賬號微信號 /// public string ToUserName { get { return toUserName; } set { toUserName = value; } } private string fromUserName = ""; ////// 消息發(fā)送方微信號 /// public string FromUserName { get { return fromUserName; } set { fromUserName = value; } } private string createTime = ""; ////// 創(chuàng)建時間 /// public string CreateTime { get { return createTime; } set { createTime = value; } } private string msgType = ""; ////// 信息類型 地理位置:location,文本消息:text,消息類型:image /// public string MsgType { get { return msgType; } set { msgType = value; } } private string content = ""; ////// 信息內(nèi)容 /// public string Content { get { return content; } set { content = value; } } private string location_X = ""; ////// 地理位置緯度 /// public string Location_X { get { return location_X; } set { location_X = value; } } private string location_Y = ""; ////// 地理位置經(jīng)度 /// public string Location_Y { get { return location_Y; } set { location_Y = value; } } private string scale = ""; ////// 地圖縮放大小 /// public string Scale { get { return scale; } set { scale = value; } } private string label = ""; ////// 地理位置信息 /// public string Label { get { return label; } set { label = value; } } private string picUrl = ""; ////// 圖片鏈接,開發(fā)者可以用HTTP GET獲取 /// public string PicUrl { get { return picUrl; } set { picUrl = value; } } } #endregion
看完上述內(nèi)容,你們對怎么在asp.net項目中開發(fā)一個微信公眾賬號接口有進一步的了解嗎?如果還想了解更多知識或者相關(guān)內(nèi)容,請關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道,感謝大家的支持。