说起微信公众帐号,大家都不会陌生,使用这个平台能给网站或系统增加一个新亮点,直接进入正题吧,在使用之前一定要仔细阅读官方api文档。
使用.net实现的方法:
//微信接口地址 页面代码:
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,(int)s.Length); poststr = EnCoding.UTF8.GetString(b); if (!string.IsNullOrEmpty(poststr)) //请求处理 { _wx.Handle(poststr); } } else { _wx.Auth(); }
具体处理类
/// <summary> /// 微信公众平台 *** 作类 /// </summary> 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; //根据不同的类型进行不同的处理 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; } //消息回复 ResponseMsg(requestXML); } /// <summary> /// 验证微信签名 /// * 将token、timestamp、nonce三个参数进行字典序排序 /// * 将三个参数字符串拼接成一个字符串进行sha1加密 /// * 开发者获得加密后的字符串可与signature对比,标识该请求来源于微信。 /// </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"]; //加密/校验流程: //1. 将token、timestamp、nonce三个参数进行字典序排序 string[] ArrTmp = { Token,timestamp,nonce }; Array.sort(ArrTmp);//字典排序 //2.将三个参数字符串拼接成一个字符串进行sha1加密 string tmpStr = string.Join("",ArrTmp); tmpStr = FormsAuthentication.HashPasswordForStoringInConfigfile(tmpStr,"SHA1"); tmpStr = tmpStr.Tolower(); //3.开发者获得加密后的字符串可与signature对比,标识该请求来源于微信。 if (tmpStr == signature) { return true; } else { return false; } } /// <summary> /// 消息回复(微信信息返回) /// </summary> /// <param name="requestXML">The request XML.</param> private voID ResponseMsg(RequestXML requestXML) { try { string resxml = ""; //主要是调用数据库进行关键词匹配自动回复内容,可以根据自己的业务情况编写。 //1.通常有,没有匹配任何指令时,返回帮助信息 autoResponse mi = new autoResponse(requestXML.Content,requestXML.FromUsername); switch (requestXML.MsgType) { case "text": //在这里执行一系列 *** 作,从而实现自动回复内容. 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[好啦,我们知道您的位置啦。您可以:" + 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>"; } break; case "image": //图文混合的消息 具体格式请见官方API“回复图文消息” 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()); } } /// <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)); 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">参数</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,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(); } } /// <summary> /// 将本次交互信息保存至数据库中 /// </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; } } }
响应类MODEL
#region 微信请求类 RequestXML /// <summary> /// 微信请求类 /// </summary> public class RequestXML { private string toUsername = ""; /// <summary> /// 消息接收方微信号,一般为公众平台账号微信号 /// </summary> public string ToUsername { get { return toUsername; } set { toUsername = value; } } private string fromUsername = ""; /// <summary> /// 消息发送方微信号 /// </summary> public string FromUsername { get { return fromUsername; } set { fromUsername = value; } } private string createTime = ""; /// <summary> /// 创建时间 /// </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> /// 图片链接,开发者可以用http GET获取 /// </summary> public string PicUrl { get { return picUrl; } set { picUrl = value; } } } #endregion
本文已被整理到了《ASP.NET微信开发教程汇总》,欢迎大家学习阅读。
通过阅读这篇文章,大家就大概知道.net如何实现微信公众账号接口开发的,希望这篇文章对大家的学习有所帮助。
总结以上是内存溢出为你收集整理的asp.net实现微信公众账号接口开发教程全部内容,希望文章能够帮你解决asp.net实现微信公众账号接口开发教程所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)