.NET 微信开放平台接口

1.如果是为了验证微信接口的token是否通过, 将valid注释去掉
2.如果要返回给用户值, 注释掉valid

作者:石世特
出处:http://www.cnblogs.com/TivonStone/

  1 <%@ WebHandler Language="C#" Class="WeixinInterface" %>
  2  
  3 using System;
  4 using System.Web;
  5  
  6 public class WeixinInterface : IHttpHandler
  7 {
  8     HttpContext context = null;
  9     string postStr = "";
 10     public void ProcessRequest(HttpContext param_context)
 11     {
 12         context = param_context;
 13  
 14         //以写日志为荣,以打断点为耻.
 15         //WriteLog("before valid \n");
 16         //valid();//用于验证
 17         //WriteLog("after valid, before post \n");
 18         if (context.Request.HttpMethod.ToLower() == "post")
 19         {
 20             System.IO.Stream s = context.Request.InputStream;
 21             byte[] b = new byte[s.Length];
 22             s.Read(b, 0, (int)s.Length);
 23             postStr = System.Text.Encoding.UTF8.GetString(b);
 24             if (!string.IsNullOrEmpty(postStr))
 25             {
 26                 responseMsg(postStr);
 27             }
 28             //WriteLog("-------AfterResponseMsg:-------\n" + postStr);
 29         }
 30     }
 31  
 32     public void valid()
 33     {
 34         var echostr = context.Request["echoStr"].ToString();
 35         if (checkSignature() && !string.IsNullOrEmpty(echostr))
 36         {
 37             context.Response.Write(echostr);
 38             context.Response.End();//推送...不然微信平台无法验证token
 39         }
 40     }
 41  
 42     public bool checkSignature()
 43     {
 44         var signature = context.Request["signature"].ToString();
 45         var timestamp = context.Request["timestamp"].ToString();
 46         var nonce = context.Request["nonce"].ToString();
 47         var token = "faketoken";
 48         string[] ArrTmp = { token, timestamp, nonce };
 49         Array.Sort(ArrTmp);     //字典排序
 50         string tmpStr = string.Join("", ArrTmp);
 51         tmpStr = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(tmpStr, "SHA1");
 52         tmpStr = tmpStr.ToLower();
 53         if (tmpStr == signature)
 54         {
 55             return true;
 56         }
 57         else
 58         {
 59             return false;
 60         }
 61     }
 62  
 63     public string GetSha1(System.Collections.Generic.List<string> codelist)
 64     {
 65         codelist.Sort();
 66         var combostr = string.Empty;
 67         for (int i = 0; i < codelist.Count; i++)
 68         {
 69             combostr += codelist[i];
 70         }
 71         return EncryptToSHA1(combostr);
 72     }
 73  
 74     public string EncryptToSHA1(string str)
 75     {
 76         System.Security.Cryptography.SHA1CryptoServiceProvider sha1 = new System.Security.Cryptography.SHA1CryptoServiceProvider();
 77         byte[] str1 = System.Text.Encoding.UTF8.GetBytes(str);
 78         byte[] str2 = sha1.ComputeHash(str1);
 79         sha1.Clear();
 80         (sha1 as IDisposable).Dispose();
 81         return Convert.ToBase64String(str2);
 82     }
 83  
 84     public void responseMsg(string postStr)
 85     {
 86         System.Xml.XmlDocument postObj = new System.Xml.XmlDocument();
 87         postObj.LoadXml(postStr);
 88         WriteLog("responseMsg:-------" + postStr);
 89         var FromUserNameList = postObj.GetElementsByTagName("FromUserName");
 90         string FromUserName = string.Empty;
 91         for (int i = 0; i < FromUserNameList.Count; i++)
 92         {
 93             if (FromUserNameList[i].ChildNodes[0].NodeType == System.Xml.XmlNodeType.CDATA)
 94             {
 95                 FromUserName = FromUserNameList[i].ChildNodes[0].Value;
 96             }
 97         }
 98         var toUsernameList = postObj.GetElementsByTagName("ToUserName");
 99         string ToUserName = string.Empty;
100         for (int i = 0; i < toUsernameList.Count; i++)
101         {
102             if (toUsernameList[i].ChildNodes[0].NodeType == System.Xml.XmlNodeType.CDATA)
103             {
104                 ToUserName = toUsernameList[i].ChildNodes[0].Value;
105             }
106         }
107         var keywordList = postObj.GetElementsByTagName("Content");
108         string Content = string.Empty;
109         for (int i = 0; i < keywordList.Count; i++)
110         {
111             if (keywordList[i].ChildNodes[0].NodeType == System.Xml.XmlNodeType.CDATA)
112             {
113                 Content = keywordList[i].ChildNodes[0].Value;
114             }
115         }
116         var time = DateTime.Now;
117         var textpl = "<xml><ToUserName><![CDATA[" + FromUserName + "]]></ToUserName>" +
118             "<FromUserName><![CDATA[" + ToUserName + "]]></FromUserName>" +
119             "<CreateTime>" + ConvertDateTimeInt(DateTime.Now) + "</CreateTime><MsgType><![CDATA[text]]></MsgType>" +
120             "<Content><![CDATA[欢迎来到微信世界---" + Content + "]]></Content><FuncFlag>0</FuncFlag></xml> ";
121         context.Response.Write(textpl);
122         context.Response.End();
123     }
124      
125     private DateTime UnixTimeToTime(string timeStamp)
126     {
127         DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
128         long lTime = long.Parse(timeStamp + "0000000");
129         TimeSpan toNow = new TimeSpan(lTime);
130         return dtStart.Add(toNow);
131     }
132  
133     private int ConvertDateTimeInt(System.DateTime time)
134     {
135         System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));
136         return (int)(time - startTime).TotalSeconds;
137     }
138  
139     private void WriteLog(string strMemo)
140     {
141         string filename = "D:/WEBHOME/logs/log.txt";
142         if (!System.IO.Directory.Exists("D:/WEBHOME/logs/"))
143             System.IO.Directory.CreateDirectory("D:/WEBHOME/logs/");
144         System.IO.StreamWriter sr = null;
145         try
146         {
147             if (!System.IO.File.Exists(filename))
148             {
149                 sr = System.IO.File.CreateText(filename);
150             }
151             else
152             {
153                 sr = System.IO.File.AppendText(filename);
154             }
155             sr.WriteLine(strMemo);
156         }
157         catch
158         {
159         }
160         finally
161         {
162             if (sr != null)
163                 sr.Close();
164         }
165     }
166  
167     public bool IsReusable
168     {
169         get
170         {
171             return false;
172         }
173     }
174 }

 

posted @ 2013-11-26 09:20  duanyong  阅读(363)  评论(0编辑  收藏  举报