.NET 微信Token验证和消息接收和回复
1 public class wxXmlModel 2 { 3 public string ToUserName { get; set; } 4 public string FromUserName { get; set; } 5 public string CreateTime { get; set; } 6 public string MsgType { get; set; } 7 public string Content { get; set; } 8 public string MsgId { get; set; } 9 10 }
1 public string Token = "Token"; 2 3 protected void Page_Load(object sender, EventArgs e) 4 { 5 string echoStr = Request.QueryString["echoStr"]; 6 7 8 9 if (CheckSignature() && !string.IsNullOrEmpty(echoStr)) 10 { 11 Response.Write(echoStr); 12 Response.End(); 13 } 14 else { 15 //如果没有接收到echostr说明不在是使用token验证 16 //接收微信发送过来的xml消息并且解析 17 Stream requestSream=HttpContext.Current.Request.InputStream; 18 byte[] requestByte=new byte[requestSream.Length]; 19 requestSream.Read(requestByte,0,(int)requestSream.Length); 20 string requestStr=Encoding.UTF8.GetString(requestByte); 21 22 if(!string.IsNullOrEmpty(requestStr)) 23 { 24 //封装请求类 25 XmlDocument requestDocXml=new XmlDocument(); 26 requestDocXml.LoadXml(requestStr); 27 XmlElement rootElement=requestDocXml.DocumentElement; 28 wxXmlModel wxXmlModel=new wxXmlModel(); 29 wxXmlModel.ToUserName=rootElement.SelectSingleNode("ToUserName").InnerText; 30 wxXmlModel.FromUserName=rootElement.SelectSingleNode("FromUserName").InnerText; 31 wxXmlModel.CreateTime=rootElement.SelectSingleNode("CreateTime").InnerText; 32 wxXmlModel.MsgType=rootElement.SelectSingleNode("MsgType").InnerText; 33 switch(wxXmlModel.MsgType) 34 { 35 case "text": 36 wxXmlModel.Content=rootElement.SelectSingleNode("Content").InnerText; 37 break; 38 default: 39 break; 40 41 } 42 string xmlMsg = "<xml>" + "<ToUserName><![CDATA[" + wxXmlModel.FromUserName+ "]]></ToUserName>" 43 + "<FromUserName><![CDATA[" + wxXmlModel.ToUserName + "]]></FromUserName>" 44 + "<CreateTime>" + DateTime.Now + "</CreateTime>" 45 + "<MsgType><![CDATA[text]]></MsgType>" 46 + "<Content><![CDATA["+wxXmlModel.Content+"]]></Content>" 47 + "</xml>"; 48 49 Response.Write(xmlMsg); 50 } 51 } 52 } 53 private bool CheckSignature() 54 { 55 string signature = Request.QueryString["signature"]; 56 string timestamp = Request.QueryString["timestamp"]; 57 string nonce = Request.QueryString["nonce"]; 58 59 string[] arrTmp = { Token, timestamp, nonce }; 60 Array.Sort(arrTmp); 61 string tmpStr = string.Join("", arrTmp); 62 tmpStr = FormsAuthentication.HashPasswordForStoringInConfigFile(tmpStr, "SHA1"); 63 if (tmpStr != null) 64 { 65 tmpStr = tmpStr.ToLower(); 66 return tmpStr == signature; 67 } 68 return false; 69 }