一、接入指南

一.第一步:填写服务器配置
进入微信公众平台后,点击基本配置--修改配置
1.将URL(服务器地址)修改为我们的服务器地址,如:http://xxx.xxx.com/Login/LoginWeiXin,此URL地址用于微信服务器验证我们的地址是否可用以及微信服务器的所有消息都会发到此地址上;
2.填写Token(令牌):此Token为我们自定义的字符串;
3.填写EncodingAESKey(消息加解密密钥:随机生成即可;
二.第二步:验证服务器地址的有效性
填写服务器配置后当点提交时,微信服务器会以GET请求将如下值发送到我们填写的URL地址上:
signature:微信加密签名,signature结合了开发者填写的token参数和请求中的timestamp参数、nonce参数。
timestamp:时间戳
nonce:随机数
echostr:随机字符串
所以我们应以GET方式获取这些值并按开发文档验证:
开发者通过检验signature对请求进行校验(下面有校验方式)。若确认此次GET请求来自微信服务器,请原样返回echostr参数内容,则接入生效,成为开发者成功,否则接入失败。
加密/校验流程如下:
1. 将token、timestamp、nonce三个参数进行字典序排序
2. 将三个参数字符串拼接成一个字符串进行sha1加密
3. 开发者获得加密后的字符串可与signature对比,标识该请求来源于微信

在Login/LoginWeiXin方法里面写:

if (Request.HttpMethod.ToLower().Equals("get")) //当请求是GET时进行验证
{
    //校验
    ValidateUrl();
}
/// <summary>
/// 校验
/// </summary>
public static void ValidateUrl()
{
    //接收请求过来的参数,由微信服务器发送过来
    string signature = HttpContext.Current.Request["signature"];
    string timestamp = HttpContext.Current.Request["timestamp"];
    string nonce = HttpContext.Current.Request["nonce"];
    string echostr = HttpContext.Current.Request["echostr"];

    string token = "phone2018"; //自定义Token值 

    //排序
    string[] temp1 = { token, timestamp, nonce };
    Array.Sort(temp1);

    //sha1加密
    string temp2 = string.Join("", temp1);
    string temp3 = FormsAuthentication.HashPasswordForStoringInConfigFile(temp2, "SHA1");

    //对比
    if (temp3.ToLower().Equals(signature))
    {
        HttpContext.Current.Response.Write(echostr);
    }
}
原文地址:https://www.cnblogs.com/genesis/p/5519322.html