官方文档:https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421135319&token=&lang=zh_CN
#region 验证Token /// <summary> /// 验证微信签名 /// </summary> /// * 将token、timestamp、nonce三个参数进行字典序排序 /// * 将三个参数字符串拼接成一个字符串进行sha1加密 /// * 开发者获得加密后的字符串可与signature对比,标识该请求来源于微信。 /// <returns></returns> private static bool CheckSignature(string Token, string signature, string timestamp, string nonce) { string[] arrTmp = { Token, timestamp, nonce }; Array.Sort(arrTmp); string tmpStr = string.Join("", arrTmp); tmpStr = FormsAuthentication.HashPasswordForStoringInConfigFile(tmpStr, "SHA1"); if (tmpStr != null) { tmpStr = tmpStr.ToLower(); return tmpStr == signature; } return false; } #endregion
在配置的URL对应的地址中,加入如下方法
public ActionResult TestToken() { #region 验证Token string echoStr = Request.QueryString["echoStr"]; string signature = Request.QueryString["signature"]; string timestamp = Request.QueryString["timestamp"]; string nonce = Request.QueryString["nonce"]; if (AdminUtil.CheckSignature("微信公众号基本配置中的Token(令牌)", signature, timestamp, nonce) && !string.IsNullOrEmpty(echoStr)) { Response.Write(echoStr); Response.End(); } #endregion return View(); }