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

版权声明:本文为博主原创文章,只为分享而编,欢迎各位学习以及转载。 https://blog.csdn.net/qq285679784/article/details/42461651
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 验证微信签名
        /// <summary>
        /// 验证微信签名(保持默认即可)
        /// </summary>
        /// * 将token、timestamp、nonce三个参数进行字典序排序
        /// * 将三个参数字符串拼接成一个字符串进行sha1加密
        /// * 开发者获得加密后的字符串可与signature对比,标识该请求来源于微信。
        /// <returns></returns>
        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
    }
}


展开阅读全文

没有更多推荐了,返回首页