0
点赞
收藏
分享

微信扫一扫

ASP.NET WEBAPI 接入微信公众平台总结,Token验证失败解决办法


首先,请允许我说一句:shit!

因为这个问题不难,但是网上有关 ASP.NET WEBAPI的资料太少。都是PHP等等的。

我也是在看了某位大神的博客后有启发,一点点研究出来的。

来看正题!

1.微信公众平台的接入方法,无非4个参数(signature, timestamp, nonce, echostr)加1个Token(两边对应)

2.Token, timestamp, nonce字典排序后,按照字符串“SHA1”加密。得出一串字符串 tmpStr(转化为小写)

3.然后比对 tmpStr 是否等于 signature,如果相等,则表示此次请求是来自于微信。

4.确定请求来自于微信,则已经完成一大步了。剩下一个,将echostr参数传出给微信公众平台的工作了。(也正是这一步,耗费了3、4个小时)

PHP的代码就不说了,有例子,网上资料也很多。值得一提的是 ASP.NET MVC的操作,Senparc.Weixin.MP SDK 微信公众平台开发教程 索引

下面结合代码来详细解释我的 ASP.NET WebAPI 对微信公众平台接入的操作。

1.获取四个参数,此处可以看Log能否输出获取到的4个参数

///声明Log全局变量
     private static log4net.ILog Log = LogManager.GetLogger("WeChatConnect");
     ///声明Token
        public readonly string Token = "weixin";//与微信公众账号后台的Token设置保持一致,区分大小写。

        ///申请消息
        [HttpGet]
        public HttpResponseMessage ConnWeChat(string signature, string timestamp, string nonce, string echostr)
        {
            try
            {
                Log.Debug("测试输出: echostr = " + echostr);
                Log.Debug("测试输出: nonce = " + nonce);
                Log.Debug("测试输出: timestamp = " + timestamp);
                Log.Debug("测试输出: signature = " + signature);

                string EchoStr = Valid(signature, timestamp, nonce, echostr);

                if (!string.IsNullOrEmpty(EchoStr))
                {
                    Log.Debug("验证成功!");
                    return JsonTools.ToHttpMsgForWeChat(echostr);
                }
                else
                {
                    Log.Debug("验证失败!");
                    return JsonTools.ToHttpMsgForWeChat("验证失败!");
                }
            }
            catch (Exception ex)
            {
                Log.Error("Log 测试输出:异常!", ex);
                return JsonTools.ToHttpMsgForWeChat(ex.ToString());
            }
        }

2. Token, timestamp, nonce字典排序后,按照字符串“SHA1”加密。得出一串字符串 tmpStr(转化为小写),

    比对 tmpStr 是否等于 signature,如果相等,则表示此次请求是来自于微信。

private string Valid(string signature, string timestamp, string nonce, string echostr)
        {
            if (CheckSignature(signature,timestamp,nonce))
            {
                if (!string.IsNullOrEmpty(echostr))
                {
                    return echostr;
                }
            }

            return "";
        }

        /// <summary>
        /// 验证微信签名
        /// </summary>
        /// * 将token、timestamp、nonce三个参数进行字典序排序
        /// * 将三个参数字符串拼接成一个字符串进行sha1加密
        /// * 开发者获得加密后的字符串可与signature对比,标识该请求来源于微信。
        /// <returns></returns>
        private bool CheckSignature(string signature,string timestamp,string nonce)
        {
            string[] ArrTmp = { Token, timestamp, nonce };
            Array.Sort(ArrTmp); //字典排序
            string tmpStr = string.Join("", ArrTmp);
            tmpStr = FormsAuthentication.HashPasswordForStoringInConfigFile(tmpStr, "SHA1");
            tmpStr = tmpStr.ToLower();
            if (tmpStr == signature)
            {
                return true;
            }
            else
            {
                return false;
            }
        }

3.确定请求来自于微信,则只剩下将echostr参数传出给微信公众平台了。

//来看看我上面代码中的输出方式:HttpResponseMessage
public HttpResponseMessage ConnWeChat(string signature, string timestamp, string nonce, string echostr)
        
//输出语句
return JsonTools.ToHttpMsgForWeChat(echostr);


//返回字符串调用方法: 
public static HttpResponseMessage ToHttpMsgForWeChat(string strMsg) { 
  HttpResponseMessage result = new HttpResponseMessage { 
    Content = new StringContent(strMsg, Encoding.GetEncoding("UTF-8"), "application/x-www-form-urlencoded") 
  }; 
  return result; 
}

此处要强调一下,参照PHP的 echo $echoStr , WebFrom 的 Response.Write(echoStr)等。一次次的调试判断出微信的接受方式,只会以 "application/x-www-form-urlencoded" 来接受,所以我用HttpResponseMessage来指定其输出方式。最后测试成功!


网上各位大神给出的接入方法足以研究出接入规则,我通过某大神给的工具:Ngrok工具,成功部署本机80端口开放给外网,更加便于调试。感谢!

博客开了3年,第一次规规矩矩的写一次技术博文。不足的地方,望大家多多谅解。

专注于研究ASP.NET技术,最近迷上ASP.NET WebAPI。


举报

相关推荐

0 条评论