微信token驗證源碼分享(c#版)


在開發時遇到一個問題:

  上線后提交申請微信提示"您的服務器沒有正確響應token驗證。。。",我查看日志發現根本就沒有接收到來自微信的參數。

后來我又記錄了微信請求方式和請求的字符串,想看看微信服務器到底有沒有給我的服務器響應請求。結果是有的。並且通過了。

代碼就添加了Request.HttpMethod和Request.QueryString沒變,但不曉得怎么回事。

 /// <summary> 按照api說明對signature進行校驗,校驗成功返回參數echostr </summary>
        /// <returns></returns>
        public string CheckSign()
        {
            var httpMethod = Request.HttpMethod.ToLower();
            string httpString = string.Empty;
            if (httpMethod == "get")
            {
                httpString = Request.QueryString.ToString();
            }
            else if (httpMethod == "post")
            {
                httpMethod = Request.Form.ToString();
            }
            else
            {
                httpMethod = "請求方式不是get和post";
            }
            var strSignature = Request["signature"];
            var strEchostr = Request["echostr"];
            var strToken = "58jiancai";
            var strTimestamp = Request["timestamp"];
            var strNonce = Request["nonce"];

            log4net.LogManager.GetLogger("請求方式").Info(httpMethod);
            log4net.LogManager.GetLogger("請求字符串").Info(httpString);
            log4net.LogManager.GetLogger("pram1.strSignature").Info(strSignature);
            log4net.LogManager.GetLogger("pram2.strEchostr").Info(strEchostr);
            log4net.LogManager.GetLogger("pram3.strToken").Info(strToken);
            log4net.LogManager.GetLogger("pram4.strTimestamp").Info(strTimestamp);
            log4net.LogManager.GetLogger("pram5.strNonce").Info(strNonce);

            //step1:字典序排序
            string[] array = new[] { strToken, strTimestamp, strNonce };
            Array.Sort(array);
            log4net.LogManager.GetLogger("sort").Info(array[0] + "||" + array[1] + "||" + array[2]);

            //step2:sha1加密
            var strResult = FormsAuthentication.HashPasswordForStoringInConfigFile(string.Concat(array), "SHA1").ToLower();
            log4net.LogManager.GetLogger("sha1").Info(strResult);

            //step3:加密后的字符串與參數signature值比較
            if (strResult == strSignature.ToLower())
            {
                log4net.LogManager.GetLogger("result").Info("success");
                return strEchostr;
            }
            log4net.LogManager.GetLogger("result").Info("fail");
            return string.Empty;
        }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM