zoukankan      html  css  js  c++  java
  • 微信消息接收 验证URL有效性 C#代码示例

    官方文档只给出了PHP的示例代码

    开发者提交信息后,微信服务器将发送GET请求到填写的URL上,GET请求携带四个参数:

    参数描述
    signature 微信加密签名,signature结合了开发者填写的token参数和请求中的timestamp参数、nonce参数。
    timestamp 时间戳
    nonce 随机数
    echostr 随机字符串

    开发者通过检验signature对请求进行校验(下面有校验方式)。若确认此次GET请求来自微信服务器,请原样返回echostr参数内容,则接入生效,成为开发者成功,否则接入失败。

    加密/校验流程如下:
    1. 将token、timestamp、nonce三个参数进行字典序排序
    2. 将三个参数字符串拼接成一个字符串进行sha1加密
    3. 开发者获得加密后的字符串可与signature对比,标识该请求来源于微信
    

    检验signature的PHP示例代码:

    private function checkSignature()
    {
            $signature = $_GET["signature"];
            $timestamp = $_GET["timestamp"];
            $nonce = $_GET["nonce"];	
            		
    	$token = TOKEN;
    	$tmpArr = array($token, $timestamp, $nonce);
    	sort($tmpArr, SORT_STRING);
    	$tmpStr = implode( $tmpArr );
    	$tmpStr = sha1( $tmpStr );
    	
    	if( $tmpStr == $signature ){
    		return true;
    	}else{
    		return false;
    	}
    }


    C#代码示例如下:

    string signature = "a948c4f99d23c1b6ef78204c1eb867166e2276e8";//context.Request.QueryString["signature"];
    string timestamp = "1405665299";//context.Request.QueryString["timestamp"];
    string nonce = "42752994";//context.Request.QueryString["nonce"];
    string token = "Topevery";

    List<string> list = new List<string>();
    list.Add(token);
    list.Add(timestamp);
    list.Add(nonce);
    list.Sort();

    list.Sort();

    string res = string.Join("", list.ToArray());


    Byte[] data1ToHash = Encoding.ASCII.GetBytes(res);
    byte[] hashvalue1 = ((HashAlgorithm)CryptoConfig.CreateFromName("SHA1")).ComputeHash(data1ToHash);

    StringBuilder sb = new StringBuilder();
    foreach (byte b in hashvalue1)
    {
    sb.Append(b.ToString("x2"));
    }
    //string s = BitConverter.ToString(hashvalue1).Replace("-", string.Empty).ToLower();
    if (signature == sb.ToString())
    {
    Console.Write("OK");
    }
    else
    {
    Console.Write("NO");
    }

  • 相关阅读:
    laravel 查询指定字段的值
    laravel 连表查询数据库
    jar包在控制台下运行
    jsp 中文乱码
    PHP垃圾回收深入理解
    php在foreach中使用引用赋值&可能遇到的问题
    接口和抽象类有什么区别
    关于php优化 你必须知道的一些事情
    yii 表单小部件
    yii 表单小部件的使用方式
  • 原文地址:https://www.cnblogs.com/weiweictgu/p/3854674.html
Copyright © 2011-2022 走看看