/// <summary>
        /// 调用微信支付请求通用接口
        /// </summary>
        public TResponse Excute <TResponse>(IWechatPayRequest <TResponse> request) where TResponse : WechatPayResponse
        {
            if (request == null)
            {
                throw new ArgumentNullException("request");
            }
            if (string.IsNullOrEmpty(this.Charset))
            {
                this.Charset = "utf-8";
            }

            //插入默认请求参数
            var parameters = request.GetParameters();

            parameters[STR_APPID]     = AppId;
            parameters[STR_MCHID]     = MchId;
            parameters[STR_NONCE_STR] = WechatExtensions.CreateNonceStr(16);
            parameters[STR_SIGN]      = WechatSignature.Create(parameters, "key=" + MchKey);
            //证书
            X509Certificate2 cert = null;

            if (request.NeedCert)
            {
                cert = new X509Certificate2(CertificatePath, MchId);
            }
            var body = webUtils.DoPost(request.ApiUrl, parameters, cert, Charset);

            //XML解析返回内容
            IWechatParser <TResponse> rsp = new WechatXmlParser <TResponse>();
            TResponse response            = rsp.Parse(body, Charset);
            var       dicCheck            = new Dictionary <string, string>(response.Parameters);

            dicCheck.Remove(STR_SIGN);

            //验证签名 有时如果缺少参数返回信息没有签名
            if (response.Parameters.ContainsKey(STR_SIGN))
            {
                bool check = WechatSignature.Check(response.Parameters[STR_SIGN], dicCheck, "key=" + MchKey);
                if (!check)
                {
                    throw new Exception("签名验证失败");
                }
            }
            return(response);
        }
Exemple #2
0
        /// <summary>
        /// 解析支付消息通知文本并验证消息
        /// </summary>
        /// <param name="content">微信支付消息内容</param>
        /// <param name="mchKey">商户密钥</param>
        /// <returns>微信支付消息</returns>
        public static WechatPayNotifyResult ParserNotifyAndCheck(string content, string mchKey)
        {
            if (string.IsNullOrEmpty(content))
            {
                throw new ArgumentNullException("content");
            }
            var Parser = new WechatXmlParser <WechatPayNotifyResult>();
            var result = Parser.Parse(content, "utf-8");

            var dicCheck = new Dictionary <string, string>(result.Parameters);

            dicCheck.Remove("sign");

            //验证签名 有时如果缺少参数返回信息没有签名
            if (result.Parameters.ContainsKey("sign"))
            {
                bool check = WechatSignature.Check(result.Parameters["sign"], dicCheck, "key=" + mchKey);
                if (!check)
                {
                    throw new Exception("签名验证失败");
                }
            }
            return(result);
        }