C# 响应微信发送的Token验证,文字、图文自动回复、请求客服对话.....

代码如下,有需要的可以参考:

  1 using System;
  2 using System.Collections.Generic;
  3 using System.Linq;
  4 using System.Web;
  5 using System.Web.UI;
  6 using System.Web.UI.WebControls;
  7 using System.Data;
  8 using System.IO;
  9 using System.Net;
 10 using System.Text;
 11 using System.Xml;
 12 using System.Web.Security;
 13 using Newtonsoft.Json.Linq;
 14 using System.Net.Security;
 15 
 16 namespace SY.Web.weixinApp
 17 {
 18     public partial class Token_url : System.Web.UI.Page
 19     {
 20         protected string Token = "";//你的token
 21 
 22         protected void Page_Load(object sender, EventArgs e)
 23         {
 24             string postStr = "";
 25 
 26             if (Request.HttpMethod.ToLower() == "post")
 27             {
 28                 System.IO.Stream s = System.Web.HttpContext.Current.Request.InputStream;
 29 
 30                 byte[] b = new byte[s.Length];
 31 
 32                 s.Read(b, 0, (int)s.Length);
 33 
 34                 postStr = System.Text.Encoding.UTF8.GetString(b);
 35                 string _resStr = "";
 36 
 37                 if (!string.IsNullOrEmpty(postStr))
 38                 {
 39                     _resStr = ResponseMsg(postStr);
 40                     WriteFileLog(postStr);
 41                 }
 42                 Response.Write(_resStr);
 43                 Response.End();
 44             }
 45 
 46             else
 47             {
 48                 Valid();   //正确响应微信发送的Token验证
 49             }
 50 
 51         }
 52 
 53         /// <summary>
 54         /// 验证微信签名
 55         /// </summary>
 56         /// * 将token、timestamp、nonce三个参数进行字典序排序
 57         /// * 将三个参数字符串拼接成一个字符串进行sha1加密
 58         /// * 开发者获得加密后的字符串可与signature对比,标识该请求来源于微信。
 59         /// <returns></returns>
 60         private bool CheckSignature()
 61         {
 62 
 63             string signature = Request.QueryString["signature"].ToString();
 64             string timestamp = Request.QueryString["timestamp"].ToString();
 65             string nonce = Request.QueryString["nonce"].ToString();
 66             string[] ArrTmp = { Token, timestamp, nonce };
 67             Array.Sort(ArrTmp);     //字典排序
 68             string tmpStr = string.Join("", ArrTmp);
 69             tmpStr = FormsAuthentication.HashPasswordForStoringInConfigFile(tmpStr, "SHA1");
 70             tmpStr = tmpStr.ToLower();
 71             if (tmpStr == signature)
 72             {
 73                 return true;
 74             }
 75             else
 76             {
 77                 return false;
 78             }
 79         }
 80         
 81         //正确响应微信发送的Token验证
 82         private void Valid()
 83         {
 84 
 85             string echoStr = Request.QueryString["echoStr"].ToString();
 86 
 87             if (CheckSignature())
 88             {
 89                 if (!string.IsNullOrEmpty(echoStr))
 90                 {
 91                     Response.Write(echoStr);
 92                     Response.End();
 93                 }
 94             }
 95 
 96         }
 97 
 98         /// <summary>
 99         /// 返回信息结果(微信信息返回)
100         /// </summary>
101         /// <param name="weixinXML"></param>
102         private string ResponseMsg(string weixinXML)
103         {
104             XmlDocument xx = new XmlDocument();
105             xx.LoadXml(weixinXML);
106 
107             XmlNode root = xx.SelectSingleNode("xml");
108 
109             XmlNode _ToName = root.SelectSingleNode("ToUserName");
110             XmlNode _FromName = root.SelectSingleNode("FromUserName");
111             XmlNode _CreatTime = root.SelectSingleNode("CreateTime");
112             XmlNode _MsgType = root.SelectSingleNode("MsgType");
113 
114             #region Click/View 事件处理
115             if (_MsgType.InnerText == "event")
116             {
117                 XmlNode _Event = root.SelectSingleNode("Event");
118                 XmlNode _EventKey = root.SelectSingleNode("EventKey");
119                 if (_Event.InnerText == "subscribe")
120                 {
121                     //关注后返回信息代码
122                     _returnStr = "<xml><ToUserName><![CDATA[" + _FromName.InnerText + "]]></ToUserName><FromUserName><![CDATA[" + _ToName.InnerText + "]]></FromUserName><CreateTime>" + ConvertDateTimeInt(DateTime.Now) + "</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[欢迎关注!]]></Content></xml>";
123 
124                     return _returnStr;
125 
126                 }
127                 
128                 #region  click事件
129                 if (_Event.InnerText == "CLICK")
130                 {
131 
132                     //请求和客服对话,关键词:rgfw
133                     if (_EventKey.InnerText == "rgfw")
134                     {
135                         //文字信息
136                         _returnStr = "<xml><ToUserName><![CDATA[" + _FromName.InnerText + "]]></ToUserName><FromUserName><![CDATA[" + _ToName.InnerText + "]]></FromUserName><CreateTime>" + ConvertDateTimeInt(DateTime.Now) + "</CreateTime><MsgType><![CDATA[transfer_customer_service]]></MsgType></xml>";
137                         return _returnStr;
138                     }
139                     else
140                     {
141                         //关键词:piclist自动回复图文信息
142                         if (_EventKey.InnerText == "piclist")
143                         {
144                             DataTable dt = new DataTable();
145                             dt = dal.GetList(8, "CID=525", "ID desc");   //获取需要回复的图文信息列表
146                             StringBuilder sbpic = new StringBuilder();
147                             if (dt != null && dt.Rows.Count > 0)
148                             {
149                                 sbpic.Append("<xml>");
150                                 sbpic.AppendFormat("<ToUserName><![CDATA[{0}]]></ToUserName>", _FromName.InnerText);
151                                 sbpic.AppendFormat("<FromUserName><![CDATA[{0}]]></FromUserName>", _ToName.InnerText);
152                                 sbpic.AppendFormat("<CreateTime><![CDATA[{0}]]></CreateTime>", ConvertDateTimeInt(DateTime.Now));
153                                 sbpic.AppendFormat("<MsgType><![CDATA[{0}]]></MsgType>", "news");
154                                 sbpic.AppendFormat("<ArticleCount><![CDATA[{0}]]></ArticleCount>", dt.Rows.Count);
155                                 sbpic.Append("<Articles>");
156                                 foreach (DataRow dr in dt.Rows)
157                                 {
158                                     sbpic.Append("<item>");
159                                     sbpic.AppendFormat("<Title><![CDATA[{0}]]></Title>", dr["Title"]);  //标题
160                                     sbpic.AppendFormat("<Description><![CDATA[{0}]]></Description>", dr["Des"]);  //导读
161                                     sbpic.AppendFormat("<PicUrl><![CDATA[{0}]]></PicUrl>", "http://www.xxx.com/" + dr["Pic"]);  //图片地址url
162                                     sbpic.AppendFormat("<Url><![CDATA[{0}]]></Url>", "http://www.xxx.com/test.aspx?id=" + dr["ID"]);   //原文链接
163                                     sbpic.Append("</item>");
164                                 }
165 
166                                 sbpic.Append("</Articles></xml>");
167 
168                                 _returnStr = sbpic.ToString();
169                                 return _returnStr;
170                             }
171                         }
172 
173                     }
174                 }
175                 #endregion
176 
177             }
178             #endregion
179 
180             #region View事件   关键词自动回复文字或图片信息处理
181             if (_MsgType.InnerText == "text")
182             {
183                 XmlNode _Content = root.SelectSingleNode("Content");
184 
185                 //关键词:rgfw请求和客服对话,
186                 if (!string.IsNullOrEmpty(_Content.InnerText) && _Content.InnerText == "rgfw")  
187                 {
188                     _returnStr = "<xml><ToUserName><![CDATA[" + _FromName.InnerText + "]]></ToUserName><FromUserName><![CDATA[" + _ToName.InnerText + "]]></FromUserName><CreateTime>" + ConvertDateTimeInt(DateTime.Now) + "</CreateTime><MsgType><![CDATA[transfer_customer_service]]></MsgType></xml>";
189                     return _returnStr;
190                 }
191                 else
192                 {
193                     //文字信息
194                     _returnStr = "<xml><ToUserName><![CDATA[" + _FromName.InnerText + "]]></ToUserName><FromUserName><![CDATA[" + _ToName.InnerText + "]]></FromUserName><CreateTime>" + ConvertDateTimeInt(DateTime.Now) + "</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[文字信息]]></Content></xml>";
195                     return _returnStr;
196                 }
197 
198             }
199             #endregion
200 
201             return _returnStr;
202         }
203 
204 
205         /// <summary>
206         /// unix时间转换为datetime
207         /// </summary>
208         /// <param name="timeStamp"></param>
209         /// <returns></returns>
210         private DateTime UnixTimeToTime(string timeStamp)
211         {
212             DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
213             long lTime = long.Parse(timeStamp + "0000000");
214             TimeSpan toNow = new TimeSpan(lTime);
215             return dtStart.Add(toNow);
216         }
217 
218         /// <summary>
219         /// datetime转换为unixtime
220         /// </summary>
221         /// <param name="time"></param>
222         /// <returns></returns>
223         private int ConvertDateTimeInt(System.DateTime time)
224         {
225             System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));
226             return (int)(time - startTime).TotalSeconds;
227         }
228 
229         /// <summary>
230         /// 写入文件日志
231         /// </summary>
232         /// <param name="strMemo"></param>
233         private void WriteFileLog(string strMemo)
234         {
235             string _filepath = Server.MapPath("/logs");
236             string _filename = Server.MapPath("/logs/logs.log");
237 
238             if (!Directory.Exists(_filepath))
239             {
240                 Directory.CreateDirectory(_filepath);
241                 if (!File.Exists(_filename))
242                 {
243                     FileStream fs1 = File.Create(_filename);
244                     fs1.Close();
245                     fs1.Dispose();
246                 }
247             }
248 
249             //将文件信息读入流中
250             using (FileStream fs = new FileStream(_filename, FileMode.OpenOrCreate | FileMode.Append))
251             {
252                 lock (fs)//锁住流
253                 {
254                     //if (!fs.CanWrite)
255                     //{
256                     //    throw new System.Security.SecurityException("文件fileName=" + _filename + "是只读文件不能写入!");
257                     //}
258 
259                     StreamWriter sw = new StreamWriter(fs);
260                     sw.WriteLine(strMemo);
261                     sw.Dispose();
262                     sw.Close();
263                 }
264             }
265 
266         }
267 
268 
269     }
270 }

 

C# 响应微信发送的Token验证,文字、图文自动回复、请求客服对话.....

上一篇:微信开发-接入说明


下一篇:微信与朋友圈分享点击无响应/图片大小超过32k