微信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;

        }

 

你可能感兴趣的:(token)