CFXIXI工作室首页
CF西西的博客 | .NET WCF 微信开放平台接口

.NET WCF 微信开放平台接口

30. 六月 2013

参考:http://www.cnblogs.com/TivonStone/archive/2012/12/21/2827347.html

/*cfxixi code 20130630 微信请求*/
        public string GetWeixinInfo()
        {
            //WebOperationContext.Current.OutgoingResponse.Headers.Add("Access-Control-Allow-Origin", "*");

            IncomingWebRequestContext request = WebOperationContext.Current.IncomingRequest;

            var method = request.Method;

            switch (method)
            {
                case "POST":
                    System.IO.Stream s = HttpContext.Current.Request.InputStream;
                    byte[] b = new byte[s.Length];
                    s.Read(b, 0, (int)s.Length);
                    string postStr = System.Text.Encoding.UTF8.GetString(b);
                    if (!string.IsNullOrEmpty(postStr))
                    {
                        return responseMsg(postStr);
                    }
                    return "POST...";
                case "DELETE":
                    return "DELETE...";
                case "PUT":
                    return "UPDATE...";
                default:
                    WriteLog("before valid \n");
                    return Valid(request);//用于验证
            }
        }

        public string Valid(IncomingWebRequestContext request)
        {
            var echostr = request.UriTemplateMatch.QueryParameters["echoStr"];
            if (checkSignature(request) && !string.IsNullOrEmpty(echostr))
            {
                HttpContext.Current.Response.Write(echostr );
HttpContext.Current.ApplicationInstance.CompleteRequest();//推送...不然微信平台无法验证token } return "error"; } public bool checkSignature(IncomingWebRequestContext request) { //IncomingWebRequestContext request = WebOperationContext.Current.IncomingRequest; var signature = request.UriTemplateMatch.QueryParameters["signature"]; var timestamp = request.UriTemplateMatch.QueryParameters["timestamp"]; var nonce = request.UriTemplateMatch.QueryParameters["nonce"]; var token = "fakeToken"; string[] ArrTmp = { token, timestamp, nonce }; Array.Sort(ArrTmp); //字典排序 string tmpStr = string.Join("", ArrTmp); tmpStr = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(tmpStr, "SHA1"); tmpStr = tmpStr.ToLower(); if (tmpStr == signature) { return true; } else { return false; } } public string GetSha1(System.Collections.Generic.List<string> codelist) { codelist.Sort(); var combostr = string.Empty; for (int i = 0; i < codelist.Count; i++) { combostr += codelist[i]; } return EncryptToSHA1(combostr); } public string EncryptToSHA1(string str) { System.Security.Cryptography.SHA1CryptoServiceProvider sha1 = new System.Security.Cryptography.SHA1CryptoServiceProvider(); byte[] str1 = System.Text.Encoding.UTF8.GetBytes(str); byte[] str2 = sha1.ComputeHash(str1); sha1.Clear(); (sha1 as IDisposable).Dispose(); return Convert.ToBase64String(str2); } public string responseMsg(string postStr) { System.Xml.XmlDocument postObj = new System.Xml.XmlDocument(); postObj.LoadXml(postStr); WriteLog("responseMsg:-------" + postStr); var fromUserNameList = postObj.GetElementsByTagName("FromUserName"); string fromUserName = string.Empty; for (int i = 0; i < fromUserNameList.Count; i++) { if (fromUserNameList[i].ChildNodes[0].NodeType == System.Xml.XmlNodeType.CDATA) { fromUserName = fromUserNameList[i].ChildNodes[0].Value; } } var toUsernameList = postObj.GetElementsByTagName("ToUserName"); string toUserName = string.Empty; for (int i = 0; i < toUsernameList.Count; i++) { if (toUsernameList[i].ChildNodes[0].NodeType == System.Xml.XmlNodeType.CDATA) { toUserName = toUsernameList[i].ChildNodes[0].Value; } } var keywordList = postObj.GetElementsByTagName("Content"); string content = string.Empty; for (int i = 0; i < keywordList.Count; i++) { if (keywordList[i].ChildNodes[0].NodeType == System.Xml.XmlNodeType.CDATA) { content = keywordList[i].ChildNodes[0].Value; } } var time = DateTime.Now; var textpl = "<xml><ToUserName><![CDATA[" + fromUserName + "]]></ToUserName>" + "<FromUserName><![CDATA[" + toUserName + "]]></FromUserName>" + "<CreateTime>" + ConvertDateTimeInt(DateTime.Now) + "</CreateTime><MsgType><![CDATA[text]]></MsgType>" + "<Content><![CDATA[欢迎来到微信世界---" + content + "]]></Content><FuncFlag>0</FuncFlag></xml> "; HttpContext.Current.Response.Write(textpl );
                HttpContext.Current.ApplicationInstance.CompleteRequest();
//推送...不然微信平台无法验证token
} 
private int ConvertDateTimeInt(System.DateTime time) 
{ System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1)); return (int)(time - startTime).TotalSeconds; } private void WriteLog(string strMemo) { string filename = "E:/WEBHOME/logs/log.txt"; if (!System.IO.Directory.Exists("E:/WEBHOME/logs/")) System.IO.Directory.CreateDirectory("E:/WEBHOME/logs/"); System.IO.StreamWriter sr = null; try { if (!System.IO.File.Exists(filename)) { sr = System.IO.File.CreateText(filename); } else { sr = System.IO.File.AppendText(filename); } sr.WriteLine(strMemo); } catch { } finally { if (sr != null) sr.Close(); } } public bool IsReusable { get { return false; } } /*cfxixi code end*/

.NET, WCF