public partial class Index : System.Web.UI.Page { public string token = "AAA";//自己的 token protected void Page_Load(object sender, EventArgs e) { #region ////------签名验证 //string echostr = Request["echostr"].ToString(); //WriteLog(echostr); //保存到txt //Response.Write(echostr); //Response.End(); ////--------接收返回的xml,解析,回复信息 //string postStr = ""; //if (Request.HttpMethod.ToLower() == "post") //{ // postStr = PostInput(); // if (!string.IsNullOrEmpty(postStr)) // { // WriteLog(postStr); // ResponseMsg(postStr); // } //} #endregion //创建自定义菜单 MyMenu(); wxmessage wx = GetWxMessage(); string res = ""; if (!string.IsNullOrEmpty(wx.EventName) && wx.EventName.Trim() == "subscribe") {//刚关注时的时间,用于欢迎词 string content = "你好!欢迎使用微信"; res = sendTextMessage(wx, content); } else if (!string.IsNullOrEmpty(wx.EventName) && wx.EventName.Trim() == "CLICK") {//点击菜单时 switch (wx.EventKey) { case "tj": res = sendPicTextMessage(wx, "标题", "描述", "图片url", "要打开的页面地址"); break; case "ck": res = sendPicTextMessage(wx, "", "描述", "http://127.0.0.1/image/xxx.jpg", "http://"); break; case "new": res = sendPicTextMessage(wx, "", "", "", ""); break; case "new3": res = sendPicTextMessage(wx, "", "", "", "" ); break; default: break; } } else {//接收信息自动回复 #region //if (wx.MsgType == "text" && wx.Content == "你好") //{ // res = sendTextMessage(wx, "你好,欢迎使用公共微信平台!"); //} //else if (wx.MsgType == "text" && wx.Content == "图文") //{ // res = sendPicTextMessage(wx, "这里是一个标题", "", ""); //} //else if (wx.MsgType == "image") //{ // res = sendPicTextMessage(wx, "这里是一个标题", "", ""); //} //else //{ // res = sendTextMessage(wx, "你好,未能识别消息!"); //} #endregion res = sendMessage(wx, "transfer_customer_service");//多客服 //res = sendTextMessage(wx, "您好!已收到您发的信息!"); } Response.Write(res); } //创建自定义菜单 public void MyMenu() { string weixin1 = ""; weixin1 = @" { ""button"":[ { ""type"":""click"", ""name"":""菜单1"", ""key"":""new"" } , { ""name"":""菜单2"", ""sub_button"":[ { ""type"":""click"", ""name"":""子类1"", ""key"":""tj"" }, { ""type"":""click"", ""name"":""子类2"", ""key"":""ck"" }] }, { ""type"":""click"", ""name"":""菜单3"", ""key"":""new3"" } ] } "; string access_token = IsExistAccess_Token(); string i = GetPage("https://api.weixin.qq.com/cgi-bin/menu/create?access_token=" + access_token, weixin1); Response.Write(i); } /// <summary> ///Access_token 的摘要说明 /// </summary> public class Access_token { /// <summary> /// 获取到的凭证 /// </summary> public string access_token{get;set;} /// <summary> /// 凭证有效时间,单位:秒 /// </summary> public string expires_in { get; set; } } public static Access_token GetAccess_token() { string appid = "wx9d9af83530a118b6"; string secret = "dc5a5f7ef3aaafdf8c33501d68f0d799"; string strUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appid + "&secret=" + secret; Access_token mode = new Access_token(); HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(strUrl); req.Method = "GET"; using (WebResponse wr = req.GetResponse()) { HttpWebResponse myResponse = (HttpWebResponse)req.GetResponse(); StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8); string content = reader.ReadToEnd(); //Response.Write(content); //在这里对Access_token 赋值 Access_token token = new Access_token(); token = ParseFromJson<Access_token>(content); mode.access_token = token.access_token; mode.expires_in = token.expires_in; } return mode; } /// <summary> /// 获取Json的Model /// </summary> public static T ParseFromJson<T>(string szJson) { T obj = Activator.CreateInstance<T>(); using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(szJson))) { DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType()); return (T)serializer.ReadObject(ms); } } /// <summary> /// 根据当前日期 判断Access_Token 是否超期 如果超期返回新的Access_Token 否则返回之前的Access_Token /// </summary> public string IsExistAccess_Token() { string Token = string.Empty; DateTime YouXRQ; // 读取XML文件中的数据,并显示出来 ,注意文件路径 string filepath = Server.MapPath("XMLFile.xml"); StreamReader str = new StreamReader(filepath, System.Text.Encoding.UTF8); XmlDocument xml = new XmlDocument(); xml.Load(str); str.Close(); str.Dispose(); Token = xml.SelectSingleNode("xml").SelectSingleNode("Access_Token").InnerText; YouXRQ = Convert.ToDateTime(xml.SelectSingleNode("xml").SelectSingleNode("Access_YouXRQ").InnerText); if (DateTime.Now > YouXRQ) { DateTime _youxrq = DateTime.Now; Access_token mode = GetAccess_token(); xml.SelectSingleNode("xml").SelectSingleNode("Access_Token").InnerText = mode.access_token; _youxrq = _youxrq.AddSeconds(int.Parse(mode.expires_in)); xml.SelectSingleNode("xml").SelectSingleNode("Access_YouXRQ").InnerText = _youxrq.ToString(); xml.Save(filepath); Token = mode.access_token; } return Token; } public string GetPage(string posturl, string postData) { Stream outstream = null; Stream instream = null; StreamReader sr = null; HttpWebResponse response = null; HttpWebRequest request = null; Encoding encoding = Encoding.UTF8; byte[] data = encoding.GetBytes(postData); // 准备请求... try { // 设置参数 request = WebRequest.Create(posturl) as HttpWebRequest; CookieContainer cookieContainer = new CookieContainer(); request.CookieContainer = cookieContainer; request.AllowAutoRedirect = true; request.Method = "POST"; request.ContentType = "application/x-www-form-urlencoded"; request.ContentLength = data.Length; outstream = request.GetRequestStream(); outstream.Write(data, 0, data.Length); outstream.Close(); //发送请求并获取相应回应数据 response = request.GetResponse() as HttpWebResponse; //直到request.GetResponse()程序才开始向目标网页发送Post请求 instream = response.GetResponseStream(); sr = new StreamReader(instream, encoding); //返回结果网页(html)代码 string content = sr.ReadToEnd(); string err = string.Empty; return content; } catch (Exception ex) { string err = ex.Message; Response.Write(err); return string.Empty; } } /// <summary> /// 获取Post请求数据 /// </summary> private string PostInput() { Stream s = System.Web.HttpContext.Current.Request.InputStream; byte[] b = new byte[s.Length]; s.Read(b, 0, (int)s.Length); return Encoding.UTF8.GetString(b); } private wxmessage GetWxMessage() { wxmessage wx = new wxmessage(); StreamReader str = new StreamReader(Request.InputStream, System.Text.Encoding.UTF8); XmlDocument xml = new XmlDocument(); xml.Load(str); wx.ToUserName = xml.SelectSingleNode("xml").SelectSingleNode("ToUserName").InnerText; wx.FromUserName = xml.SelectSingleNode("xml").SelectSingleNode("FromUserName").InnerText; wx.MsgType = xml.SelectSingleNode("xml").SelectSingleNode("MsgType").InnerText; if (wx.MsgType.Trim() == "text") {//文字 wx.Content = xml.SelectSingleNode("xml").SelectSingleNode("Content").InnerText; } if (wx.MsgType.Trim() == "transfer_customer_service") { wx.Content = xml.SelectSingleNode("xml").SelectSingleNode("MsgType").InnerText; } if (wx.MsgType.Trim()=="image") {//图片 wx.Content = xml.SelectSingleNode("xml").SelectSingleNode("PicUrl").InnerText; } if (wx.MsgType.Trim() == "event") {//事件推送 wx.EventName = xml.SelectSingleNode("xml").SelectSingleNode("Event").InnerText;//关注/取消关注事件 wx.EventKey = xml.SelectSingleNode("xml").SelectSingleNode("EventKey").InnerText;//二维码 key值 } if (wx.MsgType.Trim() == "voice") {//语音 wx.Recognition = xml.SelectSingleNode("xml").SelectSingleNode("Recognition").InnerText; } return wx; } /// <summary> /// 发送者信息类 /// </summary> class wxmessage { public string FromUserName { get; set; } public string ToUserName { get; set; } public string MsgType { get; set; } public string EventName { get; set; } public string Content { get; set; } public string Recognition { get; set; } public string EventKey { get; set; } } /// <summary> /// 发送文字消息 /// </summary> /// <param name="wx">获取的收发者信息</param> /// <param name="content">内容</param> private string sendTextMessage(wxmessage wx, string content) { string res = string.Format(@"<xml> <ToUserName><![CDATA[{0}]]></ToUserName> <FromUserName><![CDATA[{1}]]></FromUserName> <CreateTime>{2}</CreateTime> <MsgType><![CDATA[text]]></MsgType> <Content><![CDATA[{3}]]></Content> </xml> ", wx.FromUserName, wx.ToUserName, DateTime.Now, content); return res; } /// <summary> /// 多客服 /// </summary> private string sendMessage(wxmessage wx, string content) { string res = string.Format(@"<xml> <ToUserName><![CDATA[{0}]]></ToUserName> <FromUserName><![CDATA[{1}]]></FromUserName> <CreateTime>{2}</CreateTime> <MsgType><![CDATA[transfer_customer_service]]></MsgType> </xml> ", wx.FromUserName, wx.ToUserName, DateTime.Now, content); return res; } /// <summary> /// 发送图文消息 /// </summary> /// <param name="wx">获取的收发者信息</param> /// <param name="content">内容</param> private string sendPicTextMessage(wxmessage _mode, string title,string description, string picurl, string url) { string res = string.Format(@"<xml> <ToUserName><![CDATA[{0}]]></ToUserName> <FromUserName><![CDATA[{1}]]></FromUserName> <CreateTime>{2}</CreateTime> <MsgType><![CDATA[news]]></MsgType> <ArticleCount>1</ArticleCount> <Articles> <item> <Title><![CDATA[{3}]]></Title> <Description><![CDATA[{4}]]></Description> <PicUrl><![CDATA[{5}]]></PicUrl> <Url><![CDATA[{6}]]></Url> </item> </Articles> </xml> ", _mode.FromUserName, _mode.ToUserName, DateTime.Now, title,description, picurl, url); return res; } /// <summary> /// 获取返回的信息(测试) /// </summary> //private void ResponseMsg(string weixinXML) //{ // try // { // XmlDocument doc = new XmlDocument(); // doc.LoadXml(weixinXML);//读取XML字符串 // XmlElement rootElement = doc.DocumentElement; // XmlNode MsgType = rootElement.SelectSingleNode("MsgType");//获取字符串中的消息类型 // string resxml = ""; // if (MsgType.InnerText == "text")//如果消息类型为文本消息 // { // var model = new // { // ToUserName = rootElement.SelectSingleNode("ToUserName").InnerText, // FromUserName = rootElement.SelectSingleNode("FromUserName").InnerText, // CreateTime = rootElement.SelectSingleNode("CreateTime").InnerText, // MsgType = MsgType.InnerText, // Content = rootElement.SelectSingleNode("Content").InnerText, // MsgId = rootElement.SelectSingleNode("MsgId").InnerText // }; // resxml += "<xml><ToUserName><![CDATA[" + model.FromUserName + "]]></ToUserName><FromUserName><![CDATA[" + model.ToUserName + "]]></FromUserName><CreateTime>" + ConvertDateTimeInt(DateTime.Now) + "</CreateTime>"; // if (!string.IsNullOrEmpty(model.Content))//如果接收到消息 // { // if (model.Content.Contains("你好") || model.Content.Contains("在") || model.Content.Contains("hi") || model.Content.Contains("hello")) // { // resxml += "<MsgType><![CDATA[text]]></MsgType><Content><![CDATA[您好,有事请留言,偶会及时回复你的哦。]]></Content><FuncFlag>0</FuncFlag></xml>"; // } // else // { // resxml += "<MsgType><![CDATA[text]]></MsgType><Content><![CDATA[您好,稍后会回复您。]]></Content><FuncFlag>0</FuncFlag></xml>"; // } // } // else//没有接收到消息 // { // resxml += "<MsgType><![CDATA[text]]></MsgType><Content><![CDATA[亲,感谢您对我的关注,有事请留言。]]></Content><FuncFlag>0</FuncFlag></xml>"; // } // Response.Write(resxml); // } // else if (MsgType.InnerText == "image")//如果消息类型为图片消息 // { // var model = new // { // ToUserName = rootElement.SelectSingleNode("ToUserName").InnerText, // FromUserName = rootElement.SelectSingleNode("FromUserName").InnerText, // CreateTime = rootElement.SelectSingleNode("CreateTime").InnerText, // MsgType = MsgType.InnerText, // PicUrl = rootElement.SelectSingleNode("PicUrl").InnerText, // MsgId = rootElement.SelectSingleNode("MsgId").InnerText // }; // resxml += "<xml><ToUserName><![CDATA[" + model.FromUserName + "]]></ToUserName><FromUserName><![CDATA[" + model.ToUserName + "]]></FromUserName><CreateTime>" + ConvertDateTimeInt(DateTime.Now) + "</CreateTime><MsgType><![CDATA[news]]></MsgType><ArticleCount>1</ArticleCount><Articles><item><Title><![CDATA[欢迎您的光临!]]></Title><Description><![CDATA[非常感谢您的关注!]]></Description><PicUrl><![CDATA[http://...jpg]]></PicUrl><Url><![CDATA[http://www.baidu.com/]]></Url></item></Articles><FuncFlag>0</FuncFlag></xml>"; // Response.Write(resxml); // } // else//如果是其余的消息类型 // { // var model = new // { // ToUserName = rootElement.SelectSingleNode("ToUserName").InnerText, // FromUserName = rootElement.SelectSingleNode("FromUserName").InnerText, // CreateTime = rootElement.SelectSingleNode("CreateTime").InnerText, // }; // resxml += "<xml><ToUserName><![CDATA[" + model.FromUserName + "]]></ToUserName><FromUserName><![CDATA[" + model.ToUserName + "]]></FromUserName><CreateTime>" + ConvertDateTimeInt(DateTime.Now) + "</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[亲,感谢您对我的关注,有事请留言,我会及时回复你的哦。]]></Content><FuncFlag>0</FuncFlag></xml>"; // Response.Write(resxml); // } // } // catch (Exception ex) // { // throw ex; // } // Response.End(); //} /// <summary> /// datetime转换成unixtime /// </summary> 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> private void WriteLog(string echostr) { if (!Directory.Exists(Server.MapPath(@"logs\"))) { Directory.CreateDirectory(Server.MapPath(@"logs\")); } string filename = Server.MapPath(@"logs/log.txt"); StreamWriter sr = null; try { if (!File.Exists(filename)) { sr = File.CreateText(filename); } else { sr = File.AppendText(filename); } sr.WriteLine(echostr); } catch { } finally { if (sr != null) sr.Close(); } } }