WeiXin 验证成为开发者和更换服务器验证代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.SqlClient;
using System.IO;
using System.Text;
using System.Xml;
using System.Xml.XPath;using System.Security;
using System.Net;
using System.Collections;
using System.Security.Cryptography;
using System.Web.Security;

public class Handler : IHttpHandler
{

    const string Token = "token";  //你的token    
    public void ProcessRequest(HttpContext context)
    {
        //测试成为开发者,验证成功后注释掉。更换服务器需重新验证
       Valid();

    }
    /// <summary>
    /// 测试成为开发者
    /// </summary>
    private void Valid()
    {

        string echoStr = HttpContext.Current.Request.QueryString["echoStr"].ToString();
        if (CheckSignature())
        {
            if (!string.IsNullOrEmpty(echoStr))
            {
                HttpContext.Current.Response.Write(echoStr);
                HttpContext.Current.Response.End();
            }
        }
    }
    public bool IsReusable
    {
        get
        {
            return false;
        }
    }
  

    /// <summary>
    /// 验证微信签名
    /// </summary>
    /// * 将token、timestamp、nonce三个参数进行字典序排序
    /// * 将三个参数字符串拼接成一个字符串进行sha1加密
    /// * 开发者获得加密后的字符串可与signature对比,标识该请求来源于微信。
    /// <returns></returns>
    private bool CheckSignature()
    {
        string signature = HttpContext.Current.Request.QueryString["signature"].ToString();
        string timestamp = HttpContext.Current.Request.QueryString["timestamp"].ToString();
        string nonce = HttpContext.Current.Request.QueryString["nonce"].ToString();
        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;
        }
    }

    /// <summary>
    /// 处理微信服务器发送来的信息,进行处理并返回信息(微信信息回复)
    /// </summary>
    /// <param name="weixinXML"></param>
    private void ResponseMsg(string weixinXML)
    {
        //回复消息的部分:你的代码写在这里       

    }
}

 

posted @ 2015-07-29 09:55  sekon  阅读(285)  评论(0编辑  收藏  举报