最新文章專題視頻專題問答1問答10問答100問答1000問答2000關鍵字專題1關鍵字專題50關鍵字專題500關鍵字專題1500TAG最新視頻文章推薦1 推薦3 推薦5 推薦7 推薦9 推薦11 推薦13 推薦15 推薦17 推薦19 推薦21 推薦23 推薦25 推薦27 推薦29 推薦31 推薦33 推薦35 推薦37視頻文章20視頻文章30視頻文章40視頻文章50視頻文章60 視頻文章70視頻文章80視頻文章90視頻文章100視頻文章120視頻文章140 視頻2關鍵字專題關鍵字專題tag2tag3文章專題文章專題2文章索引1文章索引2文章索引3文章索引4文章索引5123456789101112131415文章專題3
問答文章1 問答文章501 問答文章1001 問答文章1501 問答文章2001 問答文章2501 問答文章3001 問答文章3501 問答文章4001 問答文章4501 問答文章5001 問答文章5501 問答文章6001 問答文章6501 問答文章7001 問答文章7501 問答文章8001 問答文章8501 問答文章9001 問答文章9501
當前位置: 首頁 - 科技 - 知識百科 - 正文

C#.net 微信公眾賬號接口開發(fā)

來源:懂視網 責編:小采 時間:2020-11-27 22:37:39
文檔

C#.net 微信公眾賬號接口開發(fā)

C#.net 微信公眾賬號接口開發(fā):微信越來越火,微信公眾平臺成為開發(fā)成新寵,本文用C#.net開發(fā)微信公眾信號接口。 微信接口地址代碼: weixin _wx = new weixin(); string postStr = ; if (Request.HttpMethod.ToLower() == post) { Stream s =
推薦度:
導讀C#.net 微信公眾賬號接口開發(fā):微信越來越火,微信公眾平臺成為開發(fā)成新寵,本文用C#.net開發(fā)微信公眾信號接口。 微信接口地址代碼: weixin _wx = new weixin(); string postStr = ; if (Request.HttpMethod.ToLower() == post) { Stream s =

微信越來越火,微信公眾平臺成為開發(fā)成新寵,本文用C#.net開發(fā)微信公眾信號接口。

微信接口地址代碼:

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 = "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;


 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;


 if (requestXML.MsgType == "text")

 {

 requestXML.Content = rootElement.SelectSingleNode("Content").InnerText;

 }

 else if (requestXML.MsgType == "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;

 }

 else if (requestXML.MsgType == "image")

 {

 requestXML.PicUrl = rootElement.SelectSingleNode("PicUrl").InnerText;

 }


 //回復消息

 ResponseMsg(requestXML);

 }


 /// <summary>

 /// 驗證微信簽名

 /// </summary>

 /// * 將token、timestamp、nonce三個參數(shù)進行字典序排序

 /// * 將三個參數(shù)字符串拼接成一個字符串進行sha1加密

 /// * 開發(fā)者獲得加密后的字符串可與signature對比,標識該請求來源于微信。

 /// <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"];

 string[] ArrTmp = { Token, timestamp, nonce };

 Array.Sort(ArrTmp); //字典排序

 string tmpStr = string.Join("", ArrTmp);

 tmpStr = FormsAuthentication.HashPasswordForStoringInConfigFile(tmpStr, "SHA1");

 tmpStr = tmpStr.ToLower();

 if (tmpStr == signature)

 {

 return true;

 }

 else

 {

 return false;

 }

 }

 

 /// <summary>

 /// 回復消息(微信信息返回)

 /// </summary>

 /// <param name="weixinXML"></param>

 private void ResponseMsg(RequestXML requestXML)

 {

 try

 {

 string resxml = "";

 mijiya mi = new mijiya(requestXML.Content,requestXML.FromUserName);


 if (requestXML.MsgType == "text")

 {

 //在這里執(zhí)行一系列操作,從而實現(xiàn)自動回復內容. 

 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>";

 }

 }

 else if (requestXML.MsgType == "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[好啦,我們知道您的位置啦。您可以:" + 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[好啦,我們知道您的位置啦。您可以:" + mi.GetDefault() + "]]></Content><FuncFlag>1</FuncFlag></xml>";

 }

 }

 else if (requestXML.MsgType == "image")

 {

 resxml = "<xml><ToUserName><![CDATA[" + requestXML.FromUserName + "]]></ToUserName><FromUserName><![CDATA[" + requestXML.ToUserName + "]]></FromUserName><CreateTime>" + ConvertDateTimeInt(DateTime.Now) + "</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[親,我沒有看懂你的意思。您可以:" + mi.GetDefault() + "]]></Content><FuncFlag>1</FuncFlag></xml>";

 //返回10以內條

 //int size = 10;

 //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>" + size + "</ArticleCount><Articles>";

 //List<string> list = new List<string>();

 ////假如有20條查詢的返回結果

 //for (int i = 0; i < 20; i++)

 //{

 // list.Add("1");

 //}

 //string[] piclist = new string[] { "/Abstract_Pencil_Scribble_Background_Vector_main.jpg", "/balloon_tree.jpg", "/bloom.jpg", "/colorful_flowers.jpg", "/colorful_summer_flower.jpg", "/fall.jpg", "/fall_tree.jpg", "/growing_flowers.jpg", "/shoes_illustration.jpg", "/splashed_tree.jpg" };


 //for (int i = 0; i < size && i < list.Count; i++)

 //{

 // resxml += "<item><Title><![CDATA[沈陽-黑龍江]]></Title><Description><![CDATA[元旦特價:¥300 市場價:¥400]]></Description><PicUrl><![CDATA[" + "http://www.hougelou.com" + piclist[i] + "]]></PicUrl><Url><![CDATA[http://www.hougelou.com]]></Url></item>";

 //}

 //resxml += "</Articles><FuncFlag>1</FuncFlag></xml>";

 }

 else if (wx_tmsg.GetMsgCount(requestXML.FromUserName) == 0)

 {

 resxml = "<xml><ToUserName><![CDATA[" + requestXML.FromUserName + "]]></ToUserName><FromUserName><![CDATA[" + requestXML.ToUserName + "]]></FromUserName><CreateTime>" + ConvertDateTimeInt(DateTime.Now) + "</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[" + mi.GetFirst() + "]]></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[親,我沒有看懂你的意思。您可以:" + mi.GetDefault() + "]]></Content><FuncFlag>1</FuncFlag></xml>";

 

 }

 //WriteTxt(resxml);

 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());

 }

 }

 

 /// <summary>

 /// unix時間轉換為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轉換為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>

 /// 調用百度地圖,返回坐標信息

 /// </summary>

 /// <param name="y">經度</param>

 /// <param name="x">緯度</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";//此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";

 }


 /// <summary>

 /// Post 提交調用抓取

 /// </summary>

 /// <param name="url">提交地址</param>

 /// <param name="param">參數(shù)</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())

 {

 //在這里對接收到的頁面內容進行處理 


 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();

 }

 }


 private void WriteToDB(RequestXML requestXML,string _xml,int _pid)

 {

 wx_tmsg wx = new wx_tmsg();

 wx.AddNew();

 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.Update();

 }

 catch (Exception ex)

 {

 wx_logs.MyInsert(ex.Message);

 //ex.message;

 }


 }

 }


 //微信請求類

 public class RequestXML

 {

 private string toUserName="";

 /// <summary>

 /// 消息接收方微信號,一般為公眾平臺賬號微信號

 /// </summary>

 public string ToUserName

 {

 get { return toUserName; }

 set { toUserName = value; }

 }


 private string fromUserName = "";

 /// <summary>

 /// 消息發(fā)送方微信號

 /// </summary>

 public string FromUserName

 {

 get { return fromUserName; }

 set { fromUserName = value; }

 }


 private string createTime = "";

 /// <summary>

 /// 創(chuàng)建時間

 /// </summary>

 public string CreateTime

 {

 get { return createTime; }

 set { createTime = value; }

 }


 private string msgType = "";

 /// <summary>

 /// 信息類型 地理位置:location,文本消息:text,消息類型:image

 /// </summary>

 public string MsgType

 {

 get { return msgType; }

 set { msgType = value; }

 }


 private string content = "";

 /// <summary>

 /// 信息內容

 /// </summary>

 public string Content

 {

 get { return content; }

 set { content = value; }

 }


 private string location_X = "";

 /// <summary>

 /// 地理位置緯度

 /// </summary>

 public string Location_X

 {

 get { return location_X; }

 set { location_X = value; }

 }


 private string location_Y = "";

 /// <summary>

 /// 地理位置經度

 /// </summary>

 public string Location_Y

 {

 get { return location_Y; }

 set { location_Y = value; }

 }


 private string scale = "";

 /// <summary>

 /// 地圖縮放大小

 /// </summary>

 public string Scale

 {

 get { return scale; }

 set { scale = value; }

 }


 private string label = "";

 /// <summary>

 /// 地理位置信息

 /// </summary>

 public string Label

 {

 get { return label; }

 set { label = value; }

 }


 private string picUrl = "";

 /// <summary>

 /// 圖片鏈接,開發(fā)者可以用HTTP GET獲取

 /// </summary>

 public string PicUrl

 {

 get { return picUrl; }

 set { picUrl = value; }

 }

}

說明: 其中用到的mijiya類,主要是調用數(shù)據庫進行關鍵詞匹配自動回復內容,可以根據自己的業(yè)務情況編寫。

聲明:本網頁內容旨在傳播知識,若有侵權等問題請及時與本網聯(lián)系,我們將在第一時間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com

文檔

C#.net 微信公眾賬號接口開發(fā)

C#.net 微信公眾賬號接口開發(fā):微信越來越火,微信公眾平臺成為開發(fā)成新寵,本文用C#.net開發(fā)微信公眾信號接口。 微信接口地址代碼: weixin _wx = new weixin(); string postStr = ; if (Request.HttpMethod.ToLower() == post) { Stream s =
推薦度:
  • 熱門焦點

最新推薦

猜你喜歡

熱門推薦

專題
Top