예제 #1
0
        // 检验消息的真实性,并且获取解密后的明文
        // @param sMsgSignature: 签名串,对应URL参数的msg_signature
        // @param sTimeStamp: 时间戳,对应URL参数的timestamp
        // @param sNonce: 随机串,对应URL参数的nonce
        // @param sPostData: 密文,对应POST请求的数据
        // @param sMsg: 解密后的原文,当return返回0时有效
        // @return: 成功0,失败返回对应的错误码
        public int DecryptMsg(string sMsgSignature, string sTimeStamp, string sNonce, string sPostData, ref string sMsg)
        {
            if (m_sEncodingAESKey.Length != 43)
            {
                return((int)WXBizMsgCryptErrorCode.WXBizMsgCrypt_IllegalAesKey);
            }
            XmlDocument doc = new Senparc.CO2NET.ExtensionEntities.XmlDocument_XxeFixed();
            XmlNode     root;
            string      sEncryptMsg;

            try
            {
                doc.LoadXml(sPostData);
                root        = doc.FirstChild;
                sEncryptMsg = root["Encrypt"].InnerText;
            }
            catch (Exception)
            {
                return((int)WXBizMsgCryptErrorCode.WXBizMsgCrypt_ParseXml_Error);
            }
            //verify signature
            int ret = 0;

            ret = VerifySignature(m_sToken, sTimeStamp, sNonce, sEncryptMsg, sMsgSignature);
            if (ret != 0)
            {
                return(ret);
            }
            //decrypt
            string cpid = "";

            try
            {
                sMsg = Cryptography.AES_decrypt(sEncryptMsg, m_sEncodingAESKey, ref cpid);
            }
            catch (FormatException)
            {
                sMsg = "";
                return((int)WXBizMsgCryptErrorCode.WXBizMsgCrypt_DecodeBase64_Error);
            }
            catch (Exception)
            {
                sMsg = "";
                return((int)WXBizMsgCryptErrorCode.WXBizMsgCrypt_DecryptAES_Error);
            }
            if (cpid != m_sReceiveId)
            {
                return((int)WXBizMsgCryptErrorCode.WXBizMsgCrypt_ValidateCorpid_Error);
            }
            return(0);
        }
예제 #2
0
        public virtual void SetContent(string content)
        {
            this.Content = content;
            XmlDocument xmlDoc = new Senparc.CO2NET.ExtensionEntities.XmlDocument_XxeFixed();

            xmlDoc.LoadXml(content);
            XmlNode     root = xmlDoc.SelectSingleNode("root");
            XmlNodeList xnl  = root.ChildNodes;

            foreach (XmlNode xnf in xnl)
            {
                this.SetParameter(xnf.Name, xnf.InnerXml);
            }
        }
예제 #3
0
        /// <summary>
        /// 获取页面提交的get和post参数
        /// </summary>
        /// <param name="httpContext"></param>
        public ResponseHandler(HttpContext httpContext)
        {
            Parameters = new Hashtable();
            XmlMap     = new Hashtable();

            this.HttpContext = httpContext ?? HttpContext.Current;
            NameValueCollection collection;

            //post data
            if (this.HttpContext.Request.HttpMethod == "POST")
            {
                collection = this.HttpContext.Request.Form;
                foreach (string k in collection)
                {
                    string v = (string)collection[k];
                    this.SetParameter(k, v);
                }
            }
            //query string
            collection = this.HttpContext.Request.QueryString;
            foreach (string k in collection)
            {
                string v = (string)collection[k];
                this.SetParameter(k, v);
            }
            if (this.HttpContext.Request.InputStream.Length > 0)
            {
                XmlDocument xmlDoc = new Senparc.CO2NET.ExtensionEntities.XmlDocument_XxeFixed();
                xmlDoc.Load(this.HttpContext.Request.InputStream);
                XmlNode     root = xmlDoc.SelectSingleNode("xml");
                XmlNodeList xnl  = root.ChildNodes;

                foreach (XmlNode xnf in xnl)
                {
                    XmlMap.Add(xnf.Name, xnf.InnerText);
                    this.SetParameter(xnf.Name, xnf.InnerText);
                }
            }
        }
예제 #4
0
        /// <summary>
        /// 获取页面提交的get和post参数
        /// </summary>
        /// <param name="httpContext"></param>
        public ResponseHandler(HttpContext httpContext)
        {
            Parameters = new Hashtable();
            XmlMap     = new Hashtable();

            this.HttpContext = httpContext ?? new DefaultHttpContext();
            IFormCollection collection;

            //post data
            if (this.HttpContext.Request.Method.ToUpper() == "POST" && this.HttpContext.Request.HasFormContentType)
            {
                collection = this.HttpContext.Request.Form;
                foreach (var k in collection)
                {
                    this.SetParameter(k.Key, k.Value[0]);
                }
            }
            //query string
            var coll = this.HttpContext.Request.Query;

            foreach (var k in coll)
            {
                this.SetParameter(k.Key, k.Value[0]);
            }
            if (this.HttpContext.Request.Body.Length > 0)
            {
                XmlDocument xmlDoc = new Senparc.CO2NET.ExtensionEntities.XmlDocument_XxeFixed();
                xmlDoc.Load(this.HttpContext.Request.Body);
                XmlNode     root = xmlDoc.SelectSingleNode("xml");
                XmlNodeList xnl  = root.ChildNodes;

                foreach (XmlNode xnf in xnl)
                {
                    XmlMap.Add(xnf.Name, xnf.InnerText);
                }
            }
        }
예제 #5
0
        /// <summary>
        /// 查询红包(包括普通红包和裂变红包)
        /// </summary>
        /// <param name="appId">公众账号AppID</param>
        /// <param name="mchId">商户MchID</param>
        /// <param name="tenPayKey">支付密钥,微信商户平台(pay.weixin.qq.com)-->账户设置-->API安全-->密钥设置</param>
        /// <param name="tenPayCertPath">证书地址(硬盘地址,形如E://cert//apiclient_cert.p12)</param>
        /// <param name="mchBillNo">商家订单号</param>
        /// <returns></returns>
        public static SearchRedPackResult SearchRedPack(string appId, string mchId, string tenPayKey, string tenPayCertPath, string mchBillNo)
        {
            string         nonceStr          = TenPayV3Util.GetNoncestr();
            RequestHandler packageReqHandler = new RequestHandler();

            packageReqHandler.SetParameter("nonce_str", nonceStr);        //随机字符串
            packageReqHandler.SetParameter("appid", appId);               //公众账号ID
            packageReqHandler.SetParameter("mch_id", mchId);              //商户号
            packageReqHandler.SetParameter("mch_billno", mchBillNo);      //填入商家订单号
            packageReqHandler.SetParameter("bill_type", "MCHT");          //MCHT:通过商户订单号获取红包信息。
            string sign = packageReqHandler.CreateMd5Sign("key", tenPayKey);

            packageReqHandler.SetParameter("sign", sign);                           //签名
            //发红包需要post的数据
            string data = packageReqHandler.ParseXML();

            //发红包接口地址
            string url = "https://api.mch.weixin.qq.com/mmpaymkttransfers/gethbinfo";
            //本地或者服务器的证书位置(证书在微信支付申请成功发来的通知邮件中)
            string cert = tenPayCertPath;
            //私钥(在安装证书时设置)
            string password = mchId;

            //调用证书
            //X509Certificate cer = new X509Certificate(cert, password);
            X509Certificate2 cer = new X509Certificate2(cert, password, X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.MachineKeySet);

            XmlDocument doc = new Senparc.CO2NET.ExtensionEntities.XmlDocument_XxeFixed();

            #region 发起post请求,载入到doc中

#if NET35 || NET40 || NET45 || NET461
            ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);

            HttpWebRequest webrequest = (HttpWebRequest)HttpWebRequest.Create(url);
            webrequest.ClientCertificates.Add(cer);
            webrequest.Method = "post";


            byte[] postdatabyte = Encoding.UTF8.GetBytes(data);
            webrequest.ContentLength = postdatabyte.Length;
            Stream stream = webrequest.GetRequestStream();
            stream.Write(postdatabyte, 0, postdatabyte.Length);
            stream.Close();

            HttpWebResponse httpWebResponse = (HttpWebResponse)webrequest.GetResponse();
            StreamReader    streamReader    = new StreamReader(httpWebResponse.GetResponseStream());
            string          response        = streamReader.ReadToEnd();
            doc.LoadXml(response);
#else
            HttpClientHandler handler = new HttpClientHandler();
            handler.ClientCertificates.Add(cer);

            HttpClient  client   = new HttpClient(handler);
            HttpContent hc       = new StringContent(data);
            var         request  = client.PostAsync(url, hc).Result;
            var         response = request.Content.ReadAsStreamAsync().Result;
            doc.Load(response);
#endif
            #endregion



            SearchRedPackResult searchReturn = new SearchRedPackResult
            {
                err_code     = "",
                err_code_des = ""
            };
            if (doc.SelectSingleNode("/xml/return_code") != null)
            {
                searchReturn.return_code = (doc.SelectSingleNode("/xml/return_code").InnerText.ToUpper() == "SUCCESS");
            }
            if (doc.SelectSingleNode("/xml/return_msg") != null)
            {
                searchReturn.return_msg = doc.SelectSingleNode("/xml/return_msg").InnerText;
            }

            if (searchReturn.return_code == true)
            {
                //redReturn.sign = doc.SelectSingleNode("/xml/sign").InnerText;
                if (doc.SelectSingleNode("/xml/result_code") != null)
                {
                    searchReturn.result_code = (doc.SelectSingleNode("/xml/result_code").InnerText.ToUpper() == "SUCCESS");
                }

                if (searchReturn.result_code == true)
                {
                    if (doc.SelectSingleNode("/xml/mch_billno") != null)
                    {
                        searchReturn.mch_billno = doc.SelectSingleNode("/xml/mch_billno").InnerText;
                    }
                    if (doc.SelectSingleNode("/xml/mch_id") != null)
                    {
                        searchReturn.mch_id = doc.SelectSingleNode("/xml/mch_id").InnerText;
                    }
                    if (doc.SelectSingleNode("/xml/detail_id") != null)
                    {
                        searchReturn.detail_id = doc.SelectSingleNode("/xml/detail_id").InnerText;
                    }
                    if (doc.SelectSingleNode("/xml/status") != null)
                    {
                        searchReturn.status = doc.SelectSingleNode("/xml/status").InnerText;
                    }
                    if (doc.SelectSingleNode("/xml/send_type") != null)
                    {
                        searchReturn.send_type = doc.SelectSingleNode("/xml/send_type").InnerText;
                    }
                    if (doc.SelectSingleNode("/xml/hb_type") != null)
                    {
                        searchReturn.hb_type = doc.SelectSingleNode("/xml/hb_type").InnerText;
                    }
                    if (doc.SelectSingleNode("/xml/total_num") != null)
                    {
                        searchReturn.total_num = doc.SelectSingleNode("/xml/total_num").InnerText;
                    }
                    if (doc.SelectSingleNode("/xml/total_amount") != null)
                    {
                        searchReturn.total_amount = doc.SelectSingleNode("/xml/total_amount").InnerText;
                    }

                    if (doc.SelectSingleNode("/xml/reason") != null)
                    {
                        searchReturn.reason = doc.SelectSingleNode("/xml/reason").InnerText;
                    }
                    if (doc.SelectSingleNode("/xml/send_time") != null)
                    {
                        searchReturn.send_time = doc.SelectSingleNode("/xml/send_time").InnerText;
                    }
                    if (doc.SelectSingleNode("/xml/refund_time") != null)
                    {
                        searchReturn.refund_time = doc.SelectSingleNode("/xml/refund_time").InnerText;
                    }
                    if (doc.SelectSingleNode("/xml/refund_amount") != null)
                    {
                        searchReturn.refund_amount = doc.SelectSingleNode("/xml/refund_amount").InnerText;
                    }

                    if (doc.SelectSingleNode("/xml/wishing") != null)
                    {
                        searchReturn.wishing = doc.SelectSingleNode("/xml/wishing").InnerText;
                    }
                    if (doc.SelectSingleNode("/xml/remark") != null)
                    {
                        searchReturn.remark = doc.SelectSingleNode("/xml/remark").InnerText;
                    }

                    if (doc.SelectSingleNode("/xml/act_name") != null)
                    {
                        searchReturn.act_name = doc.SelectSingleNode("/xml/act_name").InnerText;
                    }

                    if (doc.SelectSingleNode("/xml/hblist") != null)
                    {
                        searchReturn.hblist = new List <RedPackHBInfo>();

                        foreach (XmlNode hbinfo in doc.SelectNodes("/xml/hblist/hbinfo"))
                        {
                            RedPackHBInfo wechatHBInfo = new RedPackHBInfo();
                            wechatHBInfo.openid = hbinfo.SelectSingleNode("openid").InnerText;
                            //wechatHBInfo.status = hbinfo.SelectSingleNode("status").InnerText;
                            wechatHBInfo.amount   = hbinfo.SelectSingleNode("amount").InnerText;
                            wechatHBInfo.rcv_time = hbinfo.SelectSingleNode("rcv_time").InnerText;

                            searchReturn.hblist.Add(wechatHBInfo);
                        }
                    }
                }
                else
                {
                    if (doc.SelectSingleNode("/xml/err_code") != null)
                    {
                        searchReturn.err_code = doc.SelectSingleNode("/xml/err_code").InnerText;
                    }
                    if (doc.SelectSingleNode("/xml/err_code_des") != null)
                    {
                        searchReturn.err_code_des = doc.SelectSingleNode("/xml/err_code_des").InnerText;
                    }
                }
            }

            return(searchReturn);
        }
예제 #6
0
        /// <summary>
        /// 裂变红包发送
        /// <para>裂变红包:一次可以发放一组红包。首先领取的用户为种子用户,种子用户领取一组红包当中的一个,并可以通过社交分享将剩下的红包给其他用户。裂变红包充分利用了人际传播的优势。</para>
        /// </summary>
        /// <param name="appId">公众账号AppID</param>
        /// <param name="mchId">商户MchID</param>
        /// <param name="tenPayKey">支付密钥,微信商户平台(pay.weixin.qq.com)-->账户设置-->API安全-->密钥设置</param>
        /// <param name="tenPayCertPath">证书地址(硬盘物理地址,形如E:\\cert\\apiclient_cert.p12)</param>
        /// <param name="openId">要发红包的用户的OpenID</param>
        /// <param name="senderName">红包发送者名称,会显示给接收红包的用户</param>
        /// <param name="iP">发送红包的服务器地址</param>
        /// <param name="redPackAmount">付款金额,单位分。红包金额大于200时,请求参数scene必传。</param>
        /// <param name="wishingWord">祝福语</param>
        /// <param name="actionName">活动名称(请注意活动名称长度,官方文档提示为32个字符,实际限制不足32个字符)</param>
        /// <param name="remark">活动描述,用于低版本微信显示</param>
        /// <param name="nonceStr">将nonceStr随机字符串返回,开发者可以存到数据库用于校验</param>
        /// <param name="paySign">将支付签名返回,开发者可以存到数据库用于校验</param>
        /// <param name="mchBillNo">商户订单号,新的订单号可以从RedPackApi.GetNewBillNo(mchId)方法获得,如果传入null,则系统自动生成</param>
        /// <param name="scene">场景id(非必填),红包金额大于200时,请求参数scene必传</param>
        /// <param name="riskInfo">活动信息(非必填),String(128)posttime:用户操作的时间戳。
        /// <para>示例:posttime%3d123123412%26clientversion%3d234134%26mobile%3d122344545%26deviceid%3dIOS</para>
        /// <para>mobile:业务系统账号的手机号,国家代码-手机号。不需要+号</para>
        /// <para>deviceid :mac 地址或者设备唯一标识</para>
        /// <para>clientversion :用户操作的客户端版本</para>
        /// <para>把值为非空的信息用key = value进行拼接,再进行urlencode</para>
        /// <para>urlencode(posttime= xx & mobile = xx & deviceid = xx)</para>
        /// </param>
        /// <param name="consumeMchId">资金授权商户号,服务商替特约商户发放时使用(非必填),String(32)。示例:1222000096</param>
        /// <param name="amtType">红包金额设置方式,默认填写“ALL_RAND”,ALL_RAND—全部随机,商户指定总金额和红包发放总人数,由微信支付随机计算出各红包金额</param>
        /// <returns></returns>
        public static NormalRedPackResult SendNGroupRedPack(string appId, string mchId, string tenPayKey, string tenPayCertPath,
                                                            string openId, string senderName,
                                                            string iP, int redPackAmount, string wishingWord, string actionName, string remark,
                                                            out string nonceStr, out string paySign, string mchBillNo, RedPack_Scene?scene = null, string riskInfo = null, string consumeMchId = null, string amtType = "ALL_RAND", int total_num = 3)
        {
            mchBillNo = mchBillNo ?? GetNewBillNo(mchId);

            nonceStr = TenPayV3Util.GetNoncestr();
            //RequestHandler packageReqHandler = new RequestHandler(null);

            //string accessToken = AccessTokenContainer.GetAccessToken(ConstantClass.AppID);
            //UserInfoJson userInforResult = UserApi.Info(accessToken, openID);

            RequestHandler packageReqHandler = new RequestHandler();

            //设置package订单参数

            packageReqHandler.SetParameter("mch_billno", mchBillNo);                  //填入商家订单号
            packageReqHandler.SetParameter("mch_id", mchId);                          //商户号
            packageReqHandler.SetParameter("wxappid", appId);                         //公众账号ID
            packageReqHandler.SetParameter("send_name", senderName);                  //红包发送者名称
            packageReqHandler.SetParameter("re_openid", openId);                      //接受收红包的用户的openId
            packageReqHandler.SetParameter("total_amount", redPackAmount.ToString()); //付款金额,单位分
            packageReqHandler.SetParameter("amt_type", amtType);                      //签名
            packageReqHandler.SetParameter("total_num", total_num.ToString());        //红包发放总人数
            packageReqHandler.SetParameter("wishing", wishingWord);                   //红包祝福语
            packageReqHandler.SetParameter("act_name", actionName);                   //活动名称
            packageReqHandler.SetParameter("remark", remark);                         //备注信息

            //比普通红包多的部分
            if (scene.HasValue)
            {
                packageReqHandler.SetParameter("scene_id", scene.Value.ToString()); //场景id
            }
            packageReqHandler.SetParameter("nonce_str", nonceStr);                  //随机字符串
            if (riskInfo != null)
            {
                packageReqHandler.SetParameter("risk_info", riskInfo);//活动信息
            }
            if (consumeMchId != null)
            {
                packageReqHandler.SetParameter("consume_mch_id", consumeMchId);//活动信息
            }

            paySign = packageReqHandler.CreateMd5Sign("key", tenPayKey);
            packageReqHandler.SetParameter("sign", paySign);                        //签名
            //最新的官方文档中将以下三个字段去除了
            //packageReqHandler.SetParameter("nick_name", "提供方名称");                 //提供方名称
            //packageReqHandler.SetParameter("max_value", "100");                //最大红包金额,单位分
            //packageReqHandler.SetParameter("min_value", "100");                //最小红包金额,单位分

            //发红包需要post的数据
            string data = packageReqHandler.ParseXML();

            //发红包接口地址
            //string url = "https://api.mch.weixin.qq.com/mmpaymkttransfers/sendredpack";
            string url = "https://api.mch.weixin.qq.com/mmpaymkttransfers/sendgroupredpack";
            //本地或者服务器的证书位置(证书在微信支付申请成功发来的通知邮件中)
            string cert = tenPayCertPath;
            //私钥(在安装证书时设置)
            string password = mchId;

            //调用证书
            X509Certificate2 cer = new X509Certificate2(cert, password, X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.MachineKeySet);

            XmlDocument doc = new Senparc.CO2NET.ExtensionEntities.XmlDocument_XxeFixed();

            #region 发起post请求,载入到doc中

#if NET35 || NET40 || NET45 || NET461
            ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
            //X509Certificate cer = new X509Certificate(cert, password);

            HttpWebRequest webrequest = (HttpWebRequest)HttpWebRequest.Create(url);
            webrequest.ClientCertificates.Add(cer);
            webrequest.Method = "post";


            byte[] postdatabyte = Encoding.UTF8.GetBytes(data);
            webrequest.ContentLength = postdatabyte.Length;
            Stream stream = webrequest.GetRequestStream();
            stream.Write(postdatabyte, 0, postdatabyte.Length);
            stream.Close();

            HttpWebResponse httpWebResponse = (HttpWebResponse)webrequest.GetResponse();
            StreamReader    streamReader    = new StreamReader(httpWebResponse.GetResponseStream());
            string          response        = streamReader.ReadToEnd();
            doc.LoadXml(response);
#else
            HttpClientHandler handler = new HttpClientHandler();
            handler.ClientCertificates.Add(cer);

            HttpClient  client   = new HttpClient(handler);
            HttpContent hc       = new StringContent(data);
            var         request  = client.PostAsync(url, hc).Result;
            var         response = request.Content.ReadAsStreamAsync().Result;
            doc.Load(response);
#endif
            #endregion


            //XDocument xDoc = XDocument.Load(responseContent);

            //if (xDoc==null)
            //{
            //    throw new WeixinException("微信支付XML响应格式错误");
            //}

            NormalRedPackResult normalReturn = new NormalRedPackResult
            {
                err_code     = "",
                err_code_des = ""
            };

            if (doc.SelectSingleNode("/xml/return_code") != null)
            {
                normalReturn.return_code = doc.SelectSingleNode("/xml/return_code").InnerText;
            }
            if (doc.SelectSingleNode("/xml/return_msg") != null)
            {
                normalReturn.return_msg = doc.SelectSingleNode("/xml/return_msg").InnerText;
            }

            if (normalReturn.ReturnCodeSuccess)
            {
                //redReturn.sign = doc.SelectSingleNode("/xml/sign").InnerText;
                if (doc.SelectSingleNode("/xml/result_code") != null)
                {
                    normalReturn.result_code = doc.SelectSingleNode("/xml/result_code").InnerText;
                }

                if (normalReturn.ResultCodeSuccess)
                {
                    if (doc.SelectSingleNode("/xml/mch_billno") != null)
                    {
                        normalReturn.mch_billno = doc.SelectSingleNode("/xml/mch_billno").InnerText;
                    }
                    if (doc.SelectSingleNode("/xml/mch_id") != null)
                    {
                        normalReturn.mch_id = doc.SelectSingleNode("/xml/mch_id").InnerText;
                    }
                    if (doc.SelectSingleNode("/xml/wxappid") != null)
                    {
                        normalReturn.wxappid = doc.SelectSingleNode("/xml/wxappid").InnerText;
                    }
                    if (doc.SelectSingleNode("/xml/re_openid") != null)
                    {
                        normalReturn.re_openid = doc.SelectSingleNode("/xml/re_openid").InnerText;
                    }
                    if (doc.SelectSingleNode("/xml/total_amount") != null)
                    {
                        normalReturn.total_amount = doc.SelectSingleNode("/xml/total_amount").InnerText;
                    }

                    //裂变红包才有
                    if (doc.SelectSingleNode("/xml/send_time") != null)
                    {
                        normalReturn.send_time = doc.SelectSingleNode("/xml/send_time").InnerText;
                    }
                    //裂变红包才有
                    if (doc.SelectSingleNode("/xml/send_listid") != null)
                    {
                        normalReturn.send_listid = doc.SelectSingleNode("/xml/send_listid").InnerText;
                    }
                }
                else
                {
                    if (doc.SelectSingleNode("/xml/err_code") != null)
                    {
                        normalReturn.err_code = doc.SelectSingleNode("/xml/err_code").InnerText;
                    }
                    if (doc.SelectSingleNode("/xml/err_code_des") != null)
                    {
                        normalReturn.err_code_des = doc.SelectSingleNode("/xml/err_code_des").InnerText;
                    }
                    if (doc.SelectSingleNode("/xml/mch_billno") != null)
                    {
                        normalReturn.mch_billno = doc.SelectSingleNode("/xml/mch_billno").InnerText;
                    }
                    if (doc.SelectSingleNode("/xml/mch_id") != null)
                    {
                        normalReturn.mch_id = doc.SelectSingleNode("/xml/mch_id").InnerText;
                    }
                    if (doc.SelectSingleNode("/xml/wxappid") != null)
                    {
                        normalReturn.wxappid = doc.SelectSingleNode("/xml/wxappid").InnerText;
                    }
                    if (doc.SelectSingleNode("/xml/re_openid") != null)
                    {
                        normalReturn.re_openid = doc.SelectSingleNode("/xml/re_openid").InnerText;
                    }
                    if (doc.SelectSingleNode("/xml/total_amount") != null)
                    {
                        normalReturn.total_amount = doc.SelectSingleNode("/xml/total_amount").InnerText;
                    }
                }
            }

            return(normalReturn);
        }
예제 #7
0
        /*
         * 错误码	描述	解决方案
         * NO_AUTH	发放失败,此请求可能存在风险,已被微信拦截	请提醒用户检查自身帐号是否异常。使用常用的活跃的微信号可避免这种情况。
         * SENDNUM_LIMIT	该用户今日领取红包个数超过限制	如有需要、请在微信支付商户平台【api安全】中重新配置 【每日同一用户领取本商户红包不允许超过的个数】。
         * CA_ERROR	请求未携带证书,或请求携带的证书出错	到商户平台下载证书,请求带上证书后重试。
         * ILLEGAL_APPID	错误传入了app的appid	接口传入的所有appid应该为公众号的appid(在mp.weixin.qq.com申请的),不能为APP的appid(在open.weixin.qq.com申请的)。
         * SIGN_ERROR	商户签名错误	按文档要求重新生成签名后再重试。
         * FREQ_LIMIT	受频率限制	请对请求做频率控制
         * XML_ERROR	请求的xml格式错误,或者post的数据为空	检查请求串,确认无误后重试
         * PARAM_ERROR	参数错误	请查看err_code_des,修改设置错误的参数
         * OPENID_ERROR	Openid错误	根据用户在商家公众账号上的openid,获取用户在红包公众账号上的openid 错误。请核对商户自身公众号appid和用户在此公众号下的openid。
         * NOTENOUGH	余额不足	商户账号余额不足,请登录微信支付商户平台充值
         * FATAL_ERROR	重复请求时,参数与原单不一致	使用相同商户单号进行重复请求时,参数与第一次请求时不一致,请检查并修改参数后再重试。
         * SECOND_OVER_LIMITED	企业红包的按分钟发放受限	每分钟发送红包数量不得超过1800个;(可联系微信支付[email protected]调高额度)
         * DAY_ OVER_LIMITED	企业红包的按天日发放受限	单个商户日发送红包数量不大于10000个;(可联系微信支付[email protected]调高额度)
         * MONEY_LIMIT	红包金额发放限制	每个红包金额必须大于1元,小于1000元(可联系微信支付[email protected]调高额度至4999元)
         * SEND_FAILED	红包发放失败,请更换单号再重试	原商户单号已经失败,如果还要对同一个用户发放红包, 需要更换新的商户单号再试。
         * SYSTEMERROR	系统繁忙,请再试。	可用同一商户单号再次调用,只会发放一个红包
         * PROCESSING	请求已受理,请稍后使用原单号查询发放结果	二十分钟后查询,按照查询结果成功失败进行处理
         */

        #endregion

        /// <summary>
        /// 发放企业红包接口
        /// </summary>
        /// <param name="appId">公众账号AppID</param>
        /// <param name="mchId">商户MchID</param>
        /// <param name="tenPayKey">支付密钥,微信商户平台(pay.weixin.qq.com)-->账户设置-->API安全-->密钥设置</param>
        /// <param name="tenPayCertPath">证书地址(硬盘物理地址,形如E:\\cert\\apiclient_cert.p12)</param>
        /// <param name="senderName">红包发送者名称,会显示给接收红包的用户</param>
        /// <param name="iP">发送红包的服务器地址</param>
        /// <param name="redPackAmount">付款金额,单位分。红包金额大于200时,请求参数scene必传。</param>
        /// <param name="wishingWord">祝福语</param>
        /// <param name="actionName">活动名称(请注意活动名称长度,官方文档提示为32个字符,实际限制不足32个字符)</param>
        /// <param name="remark">活动描述,用于低版本微信显示</param>
        /// <param name="nonceStr">将nonceStr随机字符串返回,开发者可以存到数据库用于校验</param>
        /// <param name="paySign">将支付签名返回,开发者可以存到数据库用于校验</param>
        /// <param name="mchBillNo">商户订单号,新的订单号可以从RedPackApi.GetNewBillNo(mchId)方法获得,如果传入null,则系统自动生成</param>
        /// <para>示例:posttime%3d123123412%26clientversion%3d234134%26mobile%3d122344545%26deviceid%3dIOS</para>
        /// <para>mobile:业务系统账号的手机号,国家代码-手机号。不需要+号</para>
        /// <para>deviceid :mac 地址或者设备唯一标识</para>
        /// <para>clientversion :用户操作的客户端版本</para>
        /// <para>把值为非空的信息用key = value进行拼接,再进行urlencode</para>
        /// <para>urlencode(posttime= xx & mobile = xx & deviceid = xx)</para>

        /// <param name="consumeMchId">资金授权商户号,服务商替特约商户发放时使用(非必填),String(32)。示例:1222000096</param>
        /// <returns></returns>
        public static NormalRedPackResult SendWorkRedPack(string appId, string mchId, string tenPayKey, string tenPayCertPath,
                                                          string senderName, int redPackAmount, string wishingWord, string actionName, string remark, int agentId,
                                                          out string nonceStr, out string paySign, out string WorkpaySign, string openId, string amtType, string SenderHeader, string sceneId,
                                                          string mchBillNo)
        {
            mchBillNo = mchBillNo ?? GetNewBillNo(mchId);

            nonceStr = TenPayV3Util.GetNoncestr();

            RequestHandler packageReqHandler = new RequestHandler();

            //设置package订单参数
            packageReqHandler.SetParameter("nonce_str", nonceStr);                    //随机字符串
            packageReqHandler.SetParameter("wxappid", appId);                         //公众账号ID
            packageReqHandler.SetParameter("mch_id", mchId);                          //商户号
            packageReqHandler.SetParameter("mch_billno", mchBillNo);                  //填入商家订单号
            packageReqHandler.SetParameter("sender_name", senderName);                //红包发送者名称
            packageReqHandler.SetParameter("agentid", agentId.ToString());            //发送红包的应用id
            packageReqHandler.SetParameter("sender_header_media_id", SenderHeader);   //发送者头像
            packageReqHandler.SetParameter("re_openid", openId);                      //用户openid
            packageReqHandler.SetParameter("total_amount", redPackAmount.ToString()); //付款金额,单位分
            packageReqHandler.SetParameter("wishing", wishingWord);                   //红包祝福语
            packageReqHandler.SetParameter("act_name", actionName);                   //活动名称
            packageReqHandler.SetParameter("remark", remark);                         //备注信息
            packageReqHandler.SetParameter("scene_id", sceneId);                      //场景

            WorkpaySign = packageReqHandler.CreateMd5Sign("key", tenPayKey);
            packageReqHandler.SetParameter("workwx_sign", WorkpaySign);   //企业微信签名

            paySign = packageReqHandler.CreateMd5Sign("key", tenPayKey);
            packageReqHandler.SetParameter("sign", paySign);                        //签名


            //最新的官方文档中将以下三个字段去除了
            //packageReqHandler.SetParameter("nick_name", "提供方名称");                 //提供方名称
            //packageReqHandler.SetParameter("max_value", "100");                //最大红包金额,单位分
            //packageReqHandler.SetParameter("min_value", "100");                //最小红包金额,单位分

            //发红包需要post的数据
            string data = packageReqHandler.ParseXML();

            //发红包接口地址
            string url = "https://api.mch.weixin.qq.com/mmpaymkttransfers/sendworkwxredpack";
            //本地或者服务器的证书位置(证书在微信支付申请成功发来的通知邮件中)
            string cert = tenPayCertPath;
            //私钥(在安装证书时设置)
            string password = mchId;

            //调用证书
            X509Certificate2 cer = new X509Certificate2(cert, password, X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.MachineKeySet);

            XmlDocument doc = new Senparc.CO2NET.ExtensionEntities.XmlDocument_XxeFixed();

#if NET45
            ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
            //X509Certificate cer = new X509Certificate(cert, password);
            #region 发起post请求
            HttpWebRequest webrequest = (HttpWebRequest)HttpWebRequest.Create(url);
            webrequest.ClientCertificates.Add(cer);
            webrequest.Method = "post";


            byte[] postdatabyte = Encoding.UTF8.GetBytes(data);
            webrequest.ContentLength = postdatabyte.Length;
            Stream stream = webrequest.GetRequestStream();
            stream.Write(postdatabyte, 0, postdatabyte.Length);
            stream.Close();

            HttpWebResponse httpWebResponse = (HttpWebResponse)webrequest.GetResponse();
            StreamReader    streamReader    = new StreamReader(httpWebResponse.GetResponseStream());
            string          response        = streamReader.ReadToEnd();
            #endregion
            doc.LoadXml(response);
#else
            #region 发起post请求
            HttpClientHandler handler = new HttpClientHandler();
            handler.ClientCertificates.Add(cer);

            HttpClient  client   = new HttpClient(handler);
            HttpContent hc       = new StringContent(data);
            var         request  = client.PostAsync(url, hc).Result;
            var         response = request.Content.ReadAsStreamAsync().Result;
            #endregion
            doc.Load(response);
#endif

            //XDocument xDoc = XDocument.Load(responseContent);

            NormalRedPackResult normalReturn = new NormalRedPackResult
            {
                err_code     = "",
                err_code_des = ""
            };

            if (doc.SelectSingleNode("/xml/return_code") != null)
            {
                normalReturn.return_code = doc.SelectSingleNode("/xml/return_code").InnerText;
            }
            if (doc.SelectSingleNode("/xml/return_msg") != null)
            {
                normalReturn.return_msg = doc.SelectSingleNode("/xml/return_msg").InnerText;
            }

            if (normalReturn.ReturnCodeSuccess)
            {
                //redReturn.sign = doc.SelectSingleNode("/xml/sign").InnerText;
                if (doc.SelectSingleNode("/xml/result_code") != null)
                {
                    normalReturn.result_code = doc.SelectSingleNode("/xml/result_code").InnerText;
                }

                if (normalReturn.ResultCodeSuccess)
                {
                    if (doc.SelectSingleNode("/xml/mch_billno") != null)
                    {
                        normalReturn.mch_billno = doc.SelectSingleNode("/xml/mch_billno").InnerText;
                    }
                    if (doc.SelectSingleNode("/xml/mch_id") != null)
                    {
                        normalReturn.mch_id = doc.SelectSingleNode("/xml/mch_id").InnerText;
                    }
                    if (doc.SelectSingleNode("/xml/wxappid") != null)
                    {
                        normalReturn.wxappid = doc.SelectSingleNode("/xml/wxappid").InnerText;
                    }
                    if (doc.SelectSingleNode("/xml/re_openid") != null)
                    {
                        normalReturn.re_openid = doc.SelectSingleNode("/xml/re_openid").InnerText;
                    }
                    if (doc.SelectSingleNode("/xml/total_amount") != null)
                    {
                        normalReturn.total_amount = doc.SelectSingleNode("/xml/total_amount").InnerText;
                    }
                }
                else
                {
                    if (doc.SelectSingleNode("/xml/err_code") != null)
                    {
                        normalReturn.err_code = doc.SelectSingleNode("/xml/err_code").InnerText;
                    }
                    if (doc.SelectSingleNode("/xml/err_code_des") != null)
                    {
                        normalReturn.err_code_des = doc.SelectSingleNode("/xml/err_code_des").InnerText;
                    }
                    if (doc.SelectSingleNode("/xml/mch_billno") != null)
                    {
                        normalReturn.mch_billno = doc.SelectSingleNode("/xml/mch_billno").InnerText;
                    }
                    if (doc.SelectSingleNode("/xml/mch_id") != null)
                    {
                        normalReturn.mch_id = doc.SelectSingleNode("/xml/mch_id").InnerText;
                    }
                    if (doc.SelectSingleNode("/xml/wxappid") != null)
                    {
                        normalReturn.wxappid = doc.SelectSingleNode("/xml/wxappid").InnerText;
                    }
                    if (doc.SelectSingleNode("/xml/re_openid") != null)
                    {
                        normalReturn.re_openid = doc.SelectSingleNode("/xml/re_openid").InnerText;
                    }
                    if (doc.SelectSingleNode("/xml/total_amount") != null)
                    {
                        normalReturn.total_amount = doc.SelectSingleNode("/xml/total_amount").InnerText;
                    }
                    if (doc.SelectSingleNode("/xml/send_listid") != null)
                    {
                        normalReturn.send_listid = doc.SelectSingleNode("/xml/send_listid").InnerText;
                    }
                }
            }

            return(normalReturn);
        }
예제 #8
0
        /// <summary>
        /// 发送小程序红包
        /// </summary>
        /// <param name="appId">公众账号AppID</param>
        /// <param name="mchId">商户MchID</param>
        /// <param name="tenPayKey">支付密钥,微信商户平台(pay.weixin.qq.com)-->账户设置-->API安全-->密钥设置</param>
        /// <param name="tenPayCertPath">证书地址(硬盘物理地址,形如E:\\cert\\apiclient_cert.p12)</param>
        /// <param name="openId">要发红包的用户的OpenID</param>
        /// <param name="senderName">红包发送者名称,会显示给接收红包的用户</param>
        /// <param name="redPackAmount">付款金额,单位分。红包金额大于200时,请求参数scene必传。</param>
        /// <param name="wishingWord">祝福语</param>
        /// <param name="actionName">活动名称(请注意活动名称长度,官方文档提示为32个字符,实际限制不足32个字符)</param>
        /// <param name="remark">活动描述,用于低版本微信显示</param>
        /// <param name="nonceStr">将nonceStr随机字符串返回,开发者可以存到数据库用于校验</param>
        /// <param name="paySign">将支付签名返回,开发者可以存到数据库用于校验</param>
        /// <param name="mchBillNo">商户订单号,新的订单号可以从RedPackApi.GetNewBillNo(mchId)方法获得,如果传入null,则系统自动生成</param>
        /// <param name="scene">场景id(非必填),红包金额大于200时,请求参数scene必传</param>
        /// <param name="consumeMchId">资金授权商户号,服务商替特约商户发放时使用(非必填),String(32)。示例:1222000096</param>
        /// <returns></returns>
        public static MiniAppRedPackResult SendMiniAppRedPack(string appId, string mchId, string tenPayKey, string tenPayCertPath,
                                                              string openId, string senderName,
                                                              int redPackAmount, string wishingWord, string actionName, string remark,
                                                              out string nonceStr, out string paySign,
                                                              string mchBillNo, RedPack_Scene?scene = null, string consumeMchId = null)
        {
            mchBillNo = mchBillNo ?? GetNewBillNo(mchId);

            nonceStr = TenPayV3Util.GetNoncestr();

            RequestHandler packageReqHandler = new RequestHandler();

            //设置package订单参数
            packageReqHandler.SetParameter("nonce_str", nonceStr);                      //随机字符串
            packageReqHandler.SetParameter("wxappid", appId);                           //公众账号ID
            packageReqHandler.SetParameter("mch_id", mchId);                            //商户号
            packageReqHandler.SetParameter("mch_billno", mchBillNo);                    //填入商家订单号
            packageReqHandler.SetParameter("send_name", senderName);                    //红包发送者名称
            packageReqHandler.SetParameter("re_openid", openId);                        //接受收红包的用户的openId
            packageReqHandler.SetParameter("total_amount", redPackAmount.ToString());   //付款金额,单位分
            packageReqHandler.SetParameter("total_num", "1");                           //红包发放总人数
            packageReqHandler.SetParameter("wishing", wishingWord);                     //红包祝福语
            packageReqHandler.SetParameter("act_name", actionName);                     //活动名称
            packageReqHandler.SetParameter("remark", remark);                           //备注信息
            packageReqHandler.SetParameter("notify_way", "MINI_PROGRAM_JSAPI");         //通知用户形式,通过JSAPI方式领取红包,小程序红包固定传"MINI_PROGRAM_JSAPI"

            if (scene.HasValue)
            {
                packageReqHandler.SetParameter("scene_id", scene.Value.ToString());     //场景id
            }
            if (consumeMchId != null)
            {
                packageReqHandler.SetParameter("consume_mch_id", consumeMchId);         //活动信息
            }

            paySign = packageReqHandler.CreateMd5Sign("key", tenPayKey);
            packageReqHandler.SetParameter("sign", paySign);                            //签名


            //发红包需要post的数据
            string data = packageReqHandler.ParseXML();

            //发红包接口地址
            string url = Senparc.Weixin.Config.TenPayV3Host + "/mmpaymkttransfers/sendminiprogramhb";
            //本地或者服务器的证书位置(证书在微信支付申请成功发来的通知邮件中)
            string cert = tenPayCertPath;
            //私钥(在安装证书时设置)
            string password = mchId;

            //调用证书
            X509Certificate2 cer = new X509Certificate2(cert, password, X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.MachineKeySet);

            XmlDocument doc = new Senparc.CO2NET.ExtensionEntities.XmlDocument_XxeFixed();

#if NET451
            ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
            //X509Certificate cer = new X509Certificate(cert, password);
            #region 发起post请求
            HttpWebRequest webrequest = (HttpWebRequest)HttpWebRequest.Create(url);
            webrequest.ClientCertificates.Add(cer);
            webrequest.Method = "post";


            byte[] postdatabyte = Encoding.UTF8.GetBytes(data);
            webrequest.ContentLength = postdatabyte.Length;
            Stream stream = webrequest.GetRequestStream();
            stream.Write(postdatabyte, 0, postdatabyte.Length);
            stream.Close();

            HttpWebResponse httpWebResponse = (HttpWebResponse)webrequest.GetResponse();
            StreamReader    streamReader    = new StreamReader(httpWebResponse.GetResponseStream());
            string          response        = streamReader.ReadToEnd();
            #endregion
            doc.LoadXml(response);
#else
            #region 发起post请求
            HttpClientHandler handler = new HttpClientHandler();
            handler.ClientCertificates.Add(cer);

            HttpClient  client   = new HttpClient(handler);
            HttpContent hc       = new StringContent(data);
            var         request  = client.PostAsync(url, hc).Result;
            var         response = request.Content.ReadAsStreamAsync().Result;
            #endregion
            doc.Load(response);
#endif

            //XDocument xDoc = XDocument.Load(responseContent);

            MiniAppRedPackResult miniAppRedPackResult = new MiniAppRedPackResult
            {
                err_code     = "",
                err_code_des = ""
            };

            if (doc.SelectSingleNode("/xml/return_code") != null)
            {
                miniAppRedPackResult.return_code = doc.SelectSingleNode("/xml/return_code").InnerText;
            }
            if (doc.SelectSingleNode("/xml/return_msg") != null)
            {
                miniAppRedPackResult.return_msg = doc.SelectSingleNode("/xml/return_msg").InnerText;
            }

            if (miniAppRedPackResult.ReturnCodeSuccess)
            {
                //redReturn.sign = doc.SelectSingleNode("/xml/sign").InnerText;
                if (doc.SelectSingleNode("/xml/result_code") != null)
                {
                    miniAppRedPackResult.result_code = doc.SelectSingleNode("/xml/result_code").InnerText;
                }

                if (miniAppRedPackResult.ResultCodeSuccess)
                {
                    if (doc.SelectSingleNode("/xml/mch_billno") != null)
                    {
                        miniAppRedPackResult.mch_billno = doc.SelectSingleNode("/xml/mch_billno").InnerText;
                    }
                    if (doc.SelectSingleNode("/xml/mch_id") != null)
                    {
                        miniAppRedPackResult.mch_id = doc.SelectSingleNode("/xml/mch_id").InnerText;
                    }
                    if (doc.SelectSingleNode("/xml/wxappid") != null)
                    {
                        miniAppRedPackResult.wxappid = doc.SelectSingleNode("/xml/wxappid").InnerText;
                    }
                    if (doc.SelectSingleNode("/xml/re_openid") != null)
                    {
                        miniAppRedPackResult.re_openid = doc.SelectSingleNode("/xml/re_openid").InnerText;
                    }
                    if (doc.SelectSingleNode("/xml/total_amount") != null)
                    {
                        miniAppRedPackResult.total_amount = doc.SelectSingleNode("/xml/total_amount").InnerText;
                    }

                    //小程序红包才有
                    if (doc.SelectSingleNode("/xml/send_listid") != null)
                    {
                        miniAppRedPackResult.package = doc.SelectSingleNode("/xml/package").InnerText;
                    }
                }
                else
                {
                    if (doc.SelectSingleNode("/xml/err_code") != null)
                    {
                        miniAppRedPackResult.err_code = doc.SelectSingleNode("/xml/err_code").InnerText;
                    }
                    if (doc.SelectSingleNode("/xml/err_code_des") != null)
                    {
                        miniAppRedPackResult.err_code_des = doc.SelectSingleNode("/xml/err_code_des").InnerText;
                    }
                    if (doc.SelectSingleNode("/xml/mch_billno") != null)
                    {
                        miniAppRedPackResult.mch_billno = doc.SelectSingleNode("/xml/mch_billno").InnerText;
                    }
                    if (doc.SelectSingleNode("/xml/mch_id") != null)
                    {
                        miniAppRedPackResult.mch_id = doc.SelectSingleNode("/xml/mch_id").InnerText;
                    }
                    if (doc.SelectSingleNode("/xml/wxappid") != null)
                    {
                        miniAppRedPackResult.wxappid = doc.SelectSingleNode("/xml/wxappid").InnerText;
                    }
                    if (doc.SelectSingleNode("/xml/re_openid") != null)
                    {
                        miniAppRedPackResult.re_openid = doc.SelectSingleNode("/xml/re_openid").InnerText;
                    }
                    if (doc.SelectSingleNode("/xml/total_amount") != null)
                    {
                        miniAppRedPackResult.total_amount = doc.SelectSingleNode("/xml/total_amount").InnerText;
                    }
                }
            }

            return(miniAppRedPackResult);
        }
예제 #9
0
        /// <summary>
        /// 获取页面提交的get和post参数
        /// 注意:.NetCore环境必须传入HttpContext实例,不能传Null,这个接口调试特别困难,千万别出错!
        /// </summary>
        /// <param name="httpContext"></param>
        public ResponseHandler(HttpContext httpContext)
        {
#if NET45
            Parameters = new Hashtable();

            this.HttpContext = httpContext ?? HttpContext.Current;
            NameValueCollection collection;
            //post data
            if (this.HttpContext.Request.HttpMethod == "POST")
            {
                collection = this.HttpContext.Request.Form;
                foreach (string k in collection)
                {
                    string v = (string)collection[k];
                    this.SetParameter(k, v);
                }
            }
            //query string
            collection = this.HttpContext.Request.QueryString;
            foreach (string k in collection)
            {
                string v = (string)collection[k];
                this.SetParameter(k, v);
            }
            if (this.HttpContext.Request.InputStream.Length > 0)
            {
                XmlDocument xmlDoc = new Senparc.CO2NET.ExtensionEntities.XmlDocument_XxeFixed();
                xmlDoc.XmlResolver = null;
                xmlDoc.Load(this.HttpContext.Request.InputStream);
                XmlNode     root = xmlDoc.SelectSingleNode("xml");
                XmlNodeList xnl  = root.ChildNodes;

                foreach (XmlNode xnf in xnl)
                {
                    this.SetParameter(xnf.Name, xnf.InnerText);
                }
            }
#else
            Parameters = new Hashtable();

            //#if NETSTANDARD2_0
            //            HttpContext = httpContext ?? throw new WeixinException(".net standard 2.0 环境必须传入HttpContext的实例");
            //#else
            HttpContext = httpContext ?? CO2NET.SenparcDI.GetService <IHttpContextAccessor>()?.HttpContext;
            //#endif

            //post data
            if (HttpContext.Request.Method.ToUpper() == "POST" && HttpContext.Request.HasFormContentType)
            {
                foreach (var k in HttpContext.Request.Form)
                {
                    SetParameter(k.Key, k.Value[0]);
                }
            }
            //query string
            foreach (var k in HttpContext.Request.Query)
            {
                SetParameter(k.Key, k.Value[0]);
            }
            if (HttpContext.Request.ContentLength > 0)
            {
                var xmlDoc = new Senparc.CO2NET.ExtensionEntities.XmlDocument_XxeFixed();
                xmlDoc.XmlResolver = null;
                //xmlDoc.Load(HttpContext.Request.Body);
                using (var reader = new System.IO.StreamReader(HttpContext.Request.Body))
                {
                    xmlDoc.Load(reader);
                }
                var root = xmlDoc.SelectSingleNode("xml");

                foreach (XmlNode xnf in root.ChildNodes)
                {
                    SetParameter(xnf.Name, xnf.InnerText);
                }
            }
#endif
        }
예제 #10
0
파일: Sample.cs 프로젝트: wyh0395/Berry
        static void Main(string[] args)
        {
            //公众平台上开发者设置的token, appID, EncodingAESKey
            string sToken          = "QDG6eK";
            string sAppID          = "wx5823bf96d3bd56c7";
            string sEncodingAESKey = "jWmYm7qr5nMoAUwZRjGtBxmz3KA1tkAj3ykkR6q2B2C";

            WXBizMsgCrypt wxcpt = new WXBizMsgCrypt(sToken, sEncodingAESKey, sAppID);

            /* 1. 对用户回复的数据进行解密。
             * 用户回复消息或者点击事件响应时,企业会收到回调消息,假设企业收到的推送消息:
             *  POST /cgi-bin/wxpush? msg_signature=477715d11cdb4164915debcba66cb864d751f3e6&timestamp=1409659813&nonce=1372623149 HTTP/1.1
             *     Host: qy.weixin.qq.com
             * Content-Length: 613
             *
             *  <xml>
             *         <ToUserName><![CDATA[wx5823bf96d3bd56c7]]></ToUserName>
             *         <Encrypt><![CDATA[RypEvHKD8QQKFhvQ6QleEB4J58tiPdvo+rtK1I9qca6aM/wvqnLSV5zEPeusUiX5L5X/0lWfrf0QADHHhGd3QczcdCUpj911L3vg3W/sYYvuJTs3TUUkSUXxaccAS0qhxchrRYt66wiSpGLYL42aM6A8dTT+6k4aSknmPj48kzJs8qLjvd4Xgpue06DOdnLxAUHzM6+kDZ+HMZfJYuR+LtwGc2hgf5gsijff0ekUNXZiqATP7PF5mZxZ3Izoun1s4zG4LUMnvw2r+KqCKIw+3IQH03v+BCA9nMELNqbSf6tiWSrXJB3LAVGUcallcrw8V2t9EL4EhzJWrQUax5wLVMNS0+rUPA3k22Ncx4XXZS9o0MBH27Bo6BpNelZpS+/uh9KsNlY6bHCmJU9p8g7m3fVKn28H3KDYA5Pl/T8Z1ptDAVe0lXdQ2YoyyH2uyPIGHBZZIs2pDBS8R07+qN+E7Q==]]></Encrypt>
             * </xml>
             */
            string sReqMsgSig    = "477715d11cdb4164915debcba66cb864d751f3e6";
            string sReqTimeStamp = "1409659813";
            string sReqNonce     = "1372623149";
            string sReqData      = "<xml><ToUserName><![CDATA[wx5823bf96d3bd56c7]]></ToUserName><Encrypt><![CDATA[RypEvHKD8QQKFhvQ6QleEB4J58tiPdvo+rtK1I9qca6aM/wvqnLSV5zEPeusUiX5L5X/0lWfrf0QADHHhGd3QczcdCUpj911L3vg3W/sYYvuJTs3TUUkSUXxaccAS0qhxchrRYt66wiSpGLYL42aM6A8dTT+6k4aSknmPj48kzJs8qLjvd4Xgpue06DOdnLxAUHzM6+kDZ+HMZfJYuR+LtwGc2hgf5gsijff0ekUNXZiqATP7PF5mZxZ3Izoun1s4zG4LUMnvw2r+KqCKIw+3IQH03v+BCA9nMELNqbSf6tiWSrXJB3LAVGUcallcrw8V2t9EL4EhzJWrQUax5wLVMNS0+rUPA3k22Ncx4XXZS9o0MBH27Bo6BpNelZpS+/uh9KsNlY6bHCmJU9p8g7m3fVKn28H3KDYA5Pl/T8Z1ptDAVe0lXdQ2YoyyH2uyPIGHBZZIs2pDBS8R07+qN+E7Q==]]></Encrypt></xml>";
            string sMsg          = ""; //解析之后的明文
            int    ret           = 0;

            ret = wxcpt.DecryptMsg(sReqMsgSig, sReqTimeStamp, sReqNonce, sReqData, ref sMsg);
            if (ret != 0)
            {
                System.Console.WriteLine("ERR: Decrypt fail, ret: " + ret);
                return;
            }
            System.Console.WriteLine(sMsg);


            /*
             * 2. 企业回复用户消息也需要加密和拼接xml字符串。
             * 假设企业需要回复用户的消息为:
             *      <xml>
             *      <ToUserName><![CDATA[mycreate]]></ToUserName>
             *      <FromUserName><![CDATA[wx5823bf96d3bd56c7]]></FromUserName>
             *      <CreateTime>1348831860</CreateTime>
             *      <MsgType><![CDATA[text]]></MsgType>
             *      <Content><![CDATA[this is a test]]></Content>
             *      <MsgId>1234567890123456</MsgId>
             *      </xml>
             * 生成xml格式的加密消息过程为:
             */
            string sRespData   = "<xml><ToUserName><![CDATA[mycreate]]></ToUserName><FromUserName><![CDATA[wx582测试一下中文的情况,消息长度是按字节来算的396d3bd56c7]]></FromUserName><CreateTime>1348831860</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[this is a test]]></Content><MsgId>1234567890123456</MsgId></xml>";
            string sEncryptMsg = ""; //xml格式的密文

            ret = wxcpt.EncryptMsg(sRespData, sReqTimeStamp, sReqNonce, ref sEncryptMsg);
            System.Console.WriteLine("sEncryptMsg");
            System.Console.WriteLine(sEncryptMsg);

            /*测试:
             * 将sEncryptMsg解密看看是否是原文
             * */
            XmlDocument doc = new Senparc.CO2NET.ExtensionEntities.XmlDocument_XxeFixed();

            doc.LoadXml(sEncryptMsg);
            XmlNode root      = doc.FirstChild;
            string  sig       = root["MsgSignature"].InnerText;
            string  enc       = root["Encrypt"].InnerText;
            string  timestamp = root["TimeStamp"].InnerText;
            string  nonce     = root["Nonce"].InnerText;
            string  stmp      = "";

            ret = wxcpt.DecryptMsg(sig, timestamp, nonce, sEncryptMsg, ref stmp);
            System.Console.WriteLine("stemp");
            System.Console.WriteLine(stmp + ret);
            return;
        }
예제 #11
0
        /// <summary>
        /// 获取页面提交的get和post参数
        /// 注意:.NetCore环境必须传入HttpContext实例,不能传Null,这个接口调试特别困难,千万别出错!
        /// </summary>
        /// <param name="httpContext"></param>
        public ResponseHandler(HttpContext httpContext)
        {
#if NET45
            Parameters = new Hashtable();

            this.HttpContext = httpContext ?? HttpContext.Current;
            NameValueCollection collection;
            //post data
            if (this.HttpContext.Request.HttpMethod == "POST")
            {
                collection = this.HttpContext.Request.Form;
                foreach (string k in collection)
                {
                    string v = (string)collection[k];
                    this.SetParameter(k, v);
                }
            }
            //query string
            collection = this.HttpContext.Request.QueryString;
            foreach (string k in collection)
            {
                string v = (string)collection[k];
                this.SetParameter(k, v);
            }
            if (this.HttpContext.Request.InputStream.Length > 0)
            {
                XmlDocument xmlDoc = new Senparc.CO2NET.ExtensionEntities.XmlDocument_XxeFixed();
                xmlDoc.XmlResolver = null;
                xmlDoc.Load(this.HttpContext.Request.InputStream);
                XmlNode     root = xmlDoc.SelectSingleNode("xml");
                XmlNodeList xnl  = root.ChildNodes;

                foreach (XmlNode xnf in xnl)
                {
                    this.SetParameter(xnf.Name, xnf.InnerText);
                }
            }
#else
            Parameters = new Hashtable();

            //#if NETSTANDARD2_0 || NETCOREAPP3_0
            //            HttpContext = httpContext ?? throw new WeixinException(".net standard 2.0 环境必须传入HttpContext的实例");
            //#else
            HttpContext = httpContext ?? CO2NET.SenparcDI.GetService <IHttpContextAccessor>()?.HttpContext;
            //#endif

            //post data
            if (HttpContext.Request.Method.ToUpper() == "POST" && HttpContext.Request.HasFormContentType)
            {
                foreach (var k in HttpContext.Request.Form)
                {
                    SetParameter(k.Key, k.Value[0]);
                }
            }
            //query string
            foreach (var k in HttpContext.Request.Query)
            {
                SetParameter(k.Key, k.Value[0]);
            }
            if (HttpContext.Request.ContentLength > 0)
            {
                //https://github.com/aspnet/AspNetCore/issues/7644
                //解决.Net Core 3.0以上版本 Synchronous operations are disallowed. Call ReadAsync or set AllowSynchronousIO to true instead
                var syncIOFeature = HttpContext.Features.Get <IHttpBodyControlFeature>();

                if (syncIOFeature != null)
                {
                    syncIOFeature.AllowSynchronousIO = true;
                }

                var xmlDoc = new Senparc.CO2NET.ExtensionEntities.XmlDocument_XxeFixed();
                xmlDoc.XmlResolver = null;
                //xmlDoc.Load(HttpContext.Request.Body);
                using (var reader = new System.IO.StreamReader(HttpContext.Request.Body))
                {
                    xmlDoc.Load(reader);
                }
                var root = xmlDoc.SelectSingleNode("xml");

                foreach (XmlNode xnf in root.ChildNodes)
                {
                    SetParameter(xnf.Name, xnf.InnerText);
                }
            }
#endif
        }
예제 #12
0
        /// <summary>
        /// 获取页面提交的get和post参数
        /// </summary>
        /// <param name="httpContext"></param>
        public ResponseHandler(HttpContext httpContext)
        {
#if NET35 || NET40 || NET45 || NET461
            Parameters = new Hashtable();
            XmlMap     = new Hashtable();

            this.HttpContext = httpContext ?? HttpContext.Current;
            NameValueCollection collection;
            //post data
            if (this.HttpContext.Request.HttpMethod == "POST")
            {
                collection = this.HttpContext.Request.Form;
                foreach (string k in collection)
                {
                    string v = (string)collection[k];
                    this.SetParameter(k, v);
                }
            }
            //query string
            collection = this.HttpContext.Request.QueryString;
            foreach (string k in collection)
            {
                string v = (string)collection[k];
                this.SetParameter(k, v);
            }
            if (this.HttpContext.Request.InputStream.Length > 0)
            {
                XmlDocument xmlDoc = new Senparc.CO2NET.ExtensionEntities.XmlDocument_XxeFixed();
                xmlDoc.XmlResolver = null;
                xmlDoc.Load(this.HttpContext.Request.InputStream);
                XmlNode     root = xmlDoc.SelectSingleNode("xml");
                XmlNodeList xnl  = root.ChildNodes;

                foreach (XmlNode xnf in xnl)
                {
                    XmlMap.Add(xnf.Name, xnf.InnerText);
                }
            }
#else
            Parameters = new Hashtable();
            XmlMap     = new Hashtable();

            this.HttpContext = httpContext ?? new DefaultHttpContext();
            IFormCollection collection;
            //post data
            if (this.HttpContext.Request.Method.ToUpper() == "POST" && this.HttpContext.Request.HasFormContentType)
            {
                collection = this.HttpContext.Request.Form;
                foreach (var k in collection)
                {
                    this.SetParameter(k.Key, k.Value[0]);
                }
            }
            //query string
            var coll = this.HttpContext.Request.Query;
            foreach (var k in coll)
            {
                this.SetParameter(k.Key, k.Value[0]);
            }
            if (this.HttpContext.Request.Body.Length > 0)
            {
                XmlDocument xmlDoc = new XmlDocument_XxeFixed();
                xmlDoc.XmlResolver = null;
                xmlDoc.Load(this.HttpContext.Request.Body);
                XmlNode     root = xmlDoc.SelectSingleNode("xml");
                XmlNodeList xnl  = root.ChildNodes;

                foreach (XmlNode xnf in xnl)
                {
                    XmlMap.Add(xnf.Name, xnf.InnerText);
                }
            }
#endif
        }
예제 #13
0
        /// <summary>
        /// 获取页面提交的get和post参数
        /// 注意:.NetCore环境必须传入HttpContext实例,不能传Null,这个接口调试特别困难,千万别出错!
        /// </summary>
        /// <param name="httpContext"></param>
        public ResponseHandler(HttpContext httpContext)
        {
#if NET451
            Parameters = new Hashtable();

            this.HttpContext = httpContext ?? HttpContext.Current;
            NameValueCollection collection;
            //post data
            if (this.HttpContext.Request.HttpMethod == "POST")
            {
                collection = this.HttpContext.Request.Form;
                foreach (string k in collection)
                {
                    string v = (string)collection[k];
                    this.SetParameter(k, v);
                }
            }
            //query string
            collection = this.HttpContext.Request.QueryString;
            foreach (string k in collection)
            {
                string v = (string)collection[k];
                this.SetParameter(k, v);
            }
            if (this.HttpContext.Request.InputStream.Length > 0)
            {
                XmlDocument xmlDoc = new Senparc.CO2NET.ExtensionEntities.XmlDocument_XxeFixed();
                xmlDoc.XmlResolver = null;
                xmlDoc.Load(this.HttpContext.Request.InputStream);
                XmlNode     root = xmlDoc.SelectSingleNode("xml");
                XmlNodeList xnl  = root.ChildNodes;

                foreach (XmlNode xnf in xnl)
                {
                    this.SetParameter(xnf.Name, xnf.InnerText);
                }
            }
#else
            Parameters = new Hashtable();

            //#if NETSTANDARD2_0 || NETSTANDARD2_1
            //            HttpContext = httpContext ?? throw new WeixinException(".net standard 2.0 环境必须传入HttpContext的实例");
            //#else

            var serviceProvider = SenparcDI.GetServiceProvider();
            HttpContext = httpContext ?? serviceProvider.GetService <IHttpContextAccessor>()?.HttpContext;
            //#endif

            //post data
            if (HttpContext.Request.Method.ToUpper() == "POST" && HttpContext.Request.HasFormContentType)
            {
                foreach (var k in HttpContext.Request.Form)
                {
                    SetParameter(k.Key, k.Value[0]);
                }
            }
            //query string
            foreach (var k in HttpContext.Request.Query)
            {
                SetParameter(k.Key, k.Value[0]);
            }
            if (HttpContext.Request.ContentLength > 0)
            {
                var xmlDoc = new Senparc.CO2NET.ExtensionEntities.XmlDocument_XxeFixed();
                xmlDoc.XmlResolver = null;
                //xmlDoc.Load(HttpContext.Request.Body);
                try
                {
                    var ms            = new MemoryStream();
                    var requestStream = HttpContext.Request.GetRequestMemoryStream();
                    requestStream.Seek(0, System.IO.SeekOrigin.Begin);

                    requestStream.CopyTo(ms);
                    ms.Position = 0;
                    ms.Seek(0, System.IO.SeekOrigin.Begin);

                    var sr            = new StreamReader(ms);
                    var streamContent = sr.ReadToEnd();
                    Senparc.Weixin.WeixinTrace.SendCustomLog("微信支付(旧)V3 ResponseHandler 收到来自微信服务器消息", streamContent);

                    ms.Position = 0;
                    ms.Seek(0, System.IO.SeekOrigin.Begin);
                    xmlDoc.Load(ms);

                    //using (var reader = new System.IO.StreamReader(HttpContext.Request.Body))
                    //{
                    //    xmlDoc.Load(reader);
                    //}

                    var root = xmlDoc.SelectSingleNode("xml");

                    foreach (XmlNode xnf in root.ChildNodes)
                    {
                        SetParameter(xnf.Name, xnf.InnerText);
                    }
                }
                catch (Exception ex)
                {
                    var weixinEx = new WeixinException("微信支付ResponseHandler错误", ex, false);
                    Senparc.Weixin.WeixinTrace.WeixinExceptionLog(weixinEx);
                }
            }
#endif
        }
예제 #14
0
파일: Sample.cs 프로젝트: huning1990/123
        static void Main(string[] args)
        {
            //公众平台上开发者设置的token, corpID, EncodingAESKey
            string sToken          = "QDG6eK";
            string sCorpID         = "wx5823bf96d3bd56c7";
            string sEncodingAESKey = "jWmYm7qr5nMoAUwZRjGtBxmz3KA1tkAj3ykkR6q2B2C";

            WXBizMsgCrypt wxcpt = new WXBizMsgCrypt(sToken, sEncodingAESKey, sCorpID);

            /*
             * 假定公众平台上开发者设置的Token
             * 1. 验证回调URL
             * 点击验证时,企业收到类似请求:
             * GET /cgi-bin/wxpush?msg_signature=5c45ff5e21c57e6ad56bac8758b79b1d9ac89fd3&timestamp=1409659589&nonce=263014780&echostr=P9nAzCzyDtyTWESHep1vC5X9xho%2FqYX3Zpb4yKa9SKld1DsH3Iyt3tP3zNdtp%2B4RPcs8TgAE7OaBO%2BFZXvnaqQ%3D%3D
             * HTTP/1.1 Host: qy.weixin.qq.com
             * 接收到该请求时,企业应1.先验证签名的正确性 2. 解密出echostr原文。
             * 以上两步用verifyURL完成
             */
            //解析出url上的参数值如下:
            string sVerifyMsgSig    = "5c45ff5e21c57e6ad56bac8758b79b1d9ac89fd3";
            string sVerifyTimeStamp = "1409659589";
            string sVerifyNonce     = "263014780";
            string sVerifyEchoStr   = "P9nAzCzyDtyTWESHep1vC5X9xho/qYX3Zpb4yKa9SKld1DsH3Iyt3tP3zNdtp+4RPcs8TgAE7OaBO+FZXvnaqQ==";
            int    ret      = 0;
            string sEchoStr = "";

            ret = wxcpt.VerifyURL(sVerifyMsgSig, sVerifyTimeStamp, sVerifyNonce, sVerifyEchoStr, ref sEchoStr);
            if (ret != 0)
            {
                System.Console.WriteLine("ERR: VerifyURL fail, ret: " + ret);
                string input3 = System.Console.ReadLine();
                return;
            }
            System.Console.WriteLine(sEchoStr);

            /* 2. 对用户回复的数据进行解密。
             * 用户回复消息或者点击事件响应时,企业会收到回调消息,假设企业收到的推送消息:
             *  POST /cgi-bin/wxpush? msg_signature=477715d11cdb4164915debcba66cb864d751f3e6&timestamp=1409659813&nonce=1372623149 HTTP/1.1
             *     Host: qy.weixin.qq.com
             * Content-Length: 613
             *
             *  <xml>
             *         <ToUserName><![CDATA[wx5823bf96d3bd56c7]]></ToUserName>
             *         <Encrypt><![CDATA[RypEvHKD8QQKFhvQ6QleEB4J58tiPdvo+rtK1I9qca6aM/wvqnLSV5zEPeusUiX5L5X/0lWfrf0QADHHhGd3QczcdCUpj911L3vg3W/sYYvuJTs3TUUkSUXxaccAS0qhxchrRYt66wiSpGLYL42aM6A8dTT+6k4aSknmPj48kzJs8qLjvd4Xgpue06DOdnLxAUHzM6+kDZ+HMZfJYuR+LtwGc2hgf5gsijff0ekUNXZiqATP7PF5mZxZ3Izoun1s4zG4LUMnvw2r+KqCKIw+3IQH03v+BCA9nMELNqbSf6tiWSrXJB3LAVGUcallcrw8V2t9EL4EhzJWrQUax5wLVMNS0+rUPA3k22Ncx4XXZS9o0MBH27Bo6BpNelZpS+/uh9KsNlY6bHCmJU9p8g7m3fVKn28H3KDYA5Pl/T8Z1ptDAVe0lXdQ2YoyyH2uyPIGHBZZIs2pDBS8R07+qN+E7Q==]]></Encrypt>
             *         <AgentID><![CDATA[218]]></AgentID>
             * </xml>
             */
            string sReqMsgSig    = "477715d11cdb4164915debcba66cb864d751f3e6";
            string sReqTimeStamp = "1409659813";
            string sReqNonce     = "1372623149";
            string sReqData      = "<xml><ToUserName><![CDATA[wx5823bf96d3bd56c7]]></ToUserName><Encrypt><![CDATA[RypEvHKD8QQKFhvQ6QleEB4J58tiPdvo+rtK1I9qca6aM/wvqnLSV5zEPeusUiX5L5X/0lWfrf0QADHHhGd3QczcdCUpj911L3vg3W/sYYvuJTs3TUUkSUXxaccAS0qhxchrRYt66wiSpGLYL42aM6A8dTT+6k4aSknmPj48kzJs8qLjvd4Xgpue06DOdnLxAUHzM6+kDZ+HMZfJYuR+LtwGc2hgf5gsijff0ekUNXZiqATP7PF5mZxZ3Izoun1s4zG4LUMnvw2r+KqCKIw+3IQH03v+BCA9nMELNqbSf6tiWSrXJB3LAVGUcallcrw8V2t9EL4EhzJWrQUax5wLVMNS0+rUPA3k22Ncx4XXZS9o0MBH27Bo6BpNelZpS+/uh9KsNlY6bHCmJU9p8g7m3fVKn28H3KDYA5Pl/T8Z1ptDAVe0lXdQ2YoyyH2uyPIGHBZZIs2pDBS8R07+qN+E7Q==]]></Encrypt><AgentID><![CDATA[218]]></AgentID></xml>";
            string sMsg          = ""; //解析之后的明文

            ret = wxcpt.DecryptMsg(sReqMsgSig, sReqTimeStamp, sReqNonce, sReqData, ref sMsg);
            if (ret != 0)
            {
                System.Console.WriteLine("ERR: Decrypt fail, ret: " + ret);
                return;
            }
            System.Console.WriteLine(sMsg);


            /*
             * 3. 企业回复用户消息也需要加密和拼接xml字符串。
             * 假设企业需要回复用户的消息为:
             *      <xml>
             *      <ToUserName><![CDATA[mycreate]]></ToUserName>
             *      <FromUserName><![CDATA[wx5823bf96d3bd56c7]]></FromUserName>
             *      <CreateTime>1348831860</CreateTime>
             *      <MsgType><![CDATA[text]]></MsgType>
             *      <Content><![CDATA[this is a test]]></Content>
             *      <MsgId>1234567890123456</MsgId>
             *      <AgentID>128</AgentID>
             *      </xml>
             * 生成xml格式的加密消息过程为:
             */
            string sRespData   = "<xml><ToUserName><![CDATA[mycreate]]></ToUserName><FromUserName><![CDATA[wx582测试一下中文的情况,消息长度是按字节来算的396d3bd56c7]]></FromUserName><CreateTime>1348831860</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[this is这是一个中文测试 a test]]></Content><MsgId>1234567890123456</MsgId><AgentID>128</AgentID></xml>";
            string sEncryptMsg = ""; //xml格式的密文

            ret = wxcpt.EncryptMsg(sRespData, sReqTimeStamp, sReqNonce, ref sEncryptMsg);
            System.Console.WriteLine("sEncryptMsg");
            System.Console.WriteLine(sEncryptMsg);

            /*测试:
             * 将sEncryptMsg解密看看是否是原文
             * */
            XmlDocument doc = new Senparc.CO2NET.ExtensionEntities.XmlDocument_XxeFixed();

            doc.LoadXml(sEncryptMsg);
            XmlNode root      = doc.FirstChild;
            string  sig       = root["MsgSignature"].InnerText;
            string  enc       = root["Encrypt"].InnerText;
            string  timestamp = root["TimeStamp"].InnerText;
            string  nonce     = root["Nonce"].InnerText;
            string  stmp      = "";

            ret = wxcpt.DecryptMsg(sig, timestamp, nonce, sEncryptMsg, ref stmp);
            System.Console.WriteLine("stemp");
            System.Console.WriteLine(stmp + ret);
            return;
        }