微信开发者-主动请求-实际开发-(5)验证TOKEN(C#)

验证URL及TOKEN时,微信服务器会向你填写的url发送get请求,你的服务器收到请求后确认请求来自微信,并返回微信请求中的一个参数,微信服务器收到正确相应后服务器即配置成功了。

(1)相关参数如下:

String signature = Request.QueryString["signature"] == null ? "" : Request["signature"];
String timestamp = Request.QueryString["timestamp"] == null ? "" : Request["timestamp"];
String nonce = Request.QueryString["nonce"] == null ? "" : Request["nonce"];
String echostr = Request["echostr"] == null ? "" : Request["echostr"];

(2)获取签名方法如下,参数token即为在认证界面填写的TOKEN

   /// <summary>
    /// 获取微信加密签名
    /// </summary>
    /// <param name="timestamp"></param>
    /// <param name="nonce"></param>
    /// <param name="token"></param>
    /// <returns></returns>
    private String GetSignature(String timestamp, String nonce, String token)
    {
        String[] str = { token, timestamp, nonce };
        Array.Sort(str);
        String bigStr = str[0] + str[1] + str[2];
        System.Security.Cryptography.SHA1CryptoServiceProvider osha1 = new System.Security.Cryptography.SHA1CryptoServiceProvider();
        String digest = System.BitConverter.ToString(osha1.ComputeHash(Encoding.UTF8.GetBytes(bigStr)));
        String digestLower = digest.Replace("-", "").ToLower();
        return digestLower;
    }

(3)当本地通过(2)中方法加密得到的signature与微信请求参数中的signature相同时,说明请求来自微信,此时写回微信请求参数“echostr”即可。

Response.Write(echostr);
Response.End();

(4)其实,也可不用验证请求是否来自微信,当参数中有“echostr”时,直接写回去也可以。但这样,本地网站中的参数就不能用“echostr”这个名字了。

(5)验证界面如下:

微信开发者-主动请求-实际开发-(5)验证TOKEN(C#)_第1张图片

(6)“此外请注意,微信公众号接口只支持80接口”----微信开发文档如是说,请注意。


你可能感兴趣的:(微信开发,token认证,url认证)