asp.net微信商城检验signature的示例代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace WxPay.example
{
    public partial class TokenValid : System.Web.UI.Page
    {
        public string Token = "Token";//验证Token
        public string EncodingAESKey = "EncodingAESKey";//消息加密密钥
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Request.HttpMethod.ToLower() == "get")
            {
                Valid();
            }
        }

        #region 验证微信签名
        /// 
        /// 验证微信签名(保持默认即可)
        /// 
        /// * 将token、timestamp、nonce三个参数进行字典序排序
        /// * 将三个参数字符串拼接成一个字符串进行sha1加密
        /// * 开发者获得加密后的字符串可与signature对比,标识该请求来源于微信。
        /// 
        private bool CheckSignature()
        {
            string signature = Request.QueryString["signature"].ToString();
            string timestamp = Request.QueryString["timestamp"].ToString();
            string nonce = Request.QueryString["nonce"].ToString();
            string[] ArrTmp = { Token, timestamp, nonce };
            Array.Sort(ArrTmp);	 //字典排序
            string tmpStr = string.Join("", ArrTmp);
            tmpStr = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(tmpStr, "SHA1");
            tmpStr = tmpStr.ToLower();
            if (tmpStr == signature)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        private void Valid()
        {
            if (Request.QueryString["echoStr"] != null)
            {
                string echoStr = Request.QueryString["echoStr"].ToString();
                if (CheckSignature())
                {
                    if (!string.IsNullOrEmpty(echoStr))
                    {
                        Response.Write(echoStr);
                        Response.End();
                    }
                }
            }
        }
        #endregion
    }
}


你可能感兴趣的:(微信公众平台,asp.net,web)