Exemplo n.º 1
0
        /// <summary>
        ///     普通红包发送
        /// </summary>
        public NormalRedPackResult SendNormalRedPack(NormalRedPackRequest model)
        {
            //发红包接口地址
            var url = "https://api.mch.weixin.qq.com/mmpaymkttransfers/sendredpack";

            NormalRedPackResult result = null;

            try
            {
                model.WxAppId = WeChatConfig.AppId;
                model.MchId   = PayConfig.MchId;
                //本地或者服务器的证书位置(证书在微信支付申请成功发来的通知邮件中)
                var cert = PayConfig.PayCertPath;
                //私钥(在安装证书时设置)
                var password = PayConfig.CertPassword;

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

                var dictionary = PayUtil.GetAuthors(model);
                model.Sign = PayUtil.CreateMd5Sign(dictionary, PayConfig.TenPayKey); //生成Sign
                //var dict = PayUtil.GetAuthors(model);

                result = PostXML <NormalRedPackResult>(url, model, cer);
            }
            catch (Exception ex)
            {
                WeChatHelper.LoggerAction?.Invoke(nameof(RedPackApi), ex.ToString());
            }
            return(result);
        }
Exemplo n.º 2
0
        /// <summary>
        ///     支付交易返回失败或支付系统超时,调用该接口撤销交易。如果此订单用户支付失败,微信支付系统会将此订单关闭;如果用户支付成功,微信支付系统会将此订单资金退还给用户。
        ///     注意:7天以内的交易单可调用撤销,其他正常支付的单如需实现相同功能请调用申请退款API。提交支付交易后调用【查询订单API】,没有明确的支付结果再调用【撤销订单API】。
        ///     调用支付接口后请勿立即调用撤销订单API,建议支付后至少15s后再调用撤销订单接口。
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public ReverseResult Reverse(ReverseRequest model)
        {
            var url = "https://api.mch.weixin.qq.com/secapi/pay/reverse";

            ReverseResult result = null;

            try
            {
                var wechatConfig = WeChatConfig;
                model.Appid     = wechatConfig.AppId;
                model.Mch_id    = PayConfig.MchId;
                model.Nonce_str = PayUtil.GetNoncestr();
                //本地或者服务器的证书位置(证书在微信支付申请成功发来的通知邮件中)
                var cert = PayConfig.PayCertPath;
                //私钥(在安装证书时设置)
                var password = PayConfig.CertPassword;

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

                var dictionary = PayUtil.GetAuthors(model);
                model.Sign = PayUtil.CreateMd5Sign(dictionary, PayConfig.TenPayKey); //生成Sign
                result     = PostXML <ReverseResult>(url, model, cer);
            }
            catch (Exception ex)
            {
                WeChatHelper.LoggerAction?.Invoke(nameof(TenPayV3), ex.ToString());
            }
            return(result);
        }
Exemplo n.º 3
0
        public EnterpriseResult EnterprisePayment(EnterpriseRequest model)
        {
            //发红包接口地址
            var url = "https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/transfers";

            EnterpriseResult result = null;

            try
            {
                var wechatConfig = WeChatConfig;
                model.MchAppId = wechatConfig.AppId;
                model.MchId    = PayConfig.MchId;
                //本地或者服务器的证书位置(证书在微信支付申请成功发来的通知邮件中)
                var cert = PayConfig.PayCertPath;
                //私钥(在安装证书时设置)
                var password = PayConfig.CertPassword;

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

                var dictionary = PayUtil.GetAuthors(model);
                model.Sign = PayUtil.CreateMd5Sign(dictionary, PayConfig.TenPayKey); //生成Sign

                result = PostXML <EnterpriseResult>(url, model, cer);
            }
            catch (Exception ex)
            {
                WeChatHelper.LoggerAction?.Invoke(nameof(EnterprisePayApi), ex.ToString());
            }
            return(result);
        }
Exemplo n.º 4
0
        /// <summary>
        /// 退款申请接口
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public RefundResult Refund(RefundRequest model)
        {
            var url = "https://api.mch.weixin.qq.com/secapi/pay/refund";

            RefundResult result = null;

            try
            {
                var wechatConfig = WeChatConfig;
                model.AppId      = wechatConfig.AppId;
                model.Mch_Id     = PayConfig.MchId;
                model.NonceStr   = PayUtil.GetNoncestr();
                model.Op_user_id = PayConfig.MchId;

                //本地或者服务器的证书位置(证书在微信支付申请成功发来的通知邮件中)
                var cert = HostingEnvironment.ApplicationPhysicalPath + PayConfig.PayCertPath;
                //私钥(在安装证书时设置)
                var password = PayConfig.CertPassword;

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

                var dictionary = PayUtil.GetAuthors(model);
                WeChatHelper.PayLogger.Log(LoggerLevels.Error, model.Total_fee);
                model.Sign = PayUtil.CreateMd5Sign(dictionary, PayConfig.TenPayKey); //生成Sign
                result     = PostXML <RefundResult>(url, model, cer);
            }
            catch (Exception ex)
            {
                WeChatHelper.PayLogger.Log(LoggerLevels.Error, ex);
            }
            return(result);
        }
Exemplo n.º 5
0
        public ActionResult TestPay()
        {
            #region 统一下单

            LogManager.GetCurrentClassLogger().Debug("开始下单");
            var model = new UnifiedorderRequest {
                OpenId = WeiChatApplicationContext.Current.WeiChatUser.OpenId
            };
            LogManager.GetCurrentClassLogger().Debug(JsonConvert.SerializeObject(model.OpenId));
            model.SpbillCreateIp = "8.8.8.8";
            model.OutTradeNo     = PayUtil.GenerateOutTradeNo();
            model.TotalFee       = "1";
            model.NonceStr       = PayUtil.GetNoncestr();
            model.TradeType      = "JSAPI";
            model.Body           = "购买商品";
            model.DeviceInfo     = "WEB";
            var result = WeChatApisContext.Current.TenPayV3Api.Unifiedorder(model);

            var _dict = new Dictionary <string, string>
            {
                { "appId", result.AppId },
                { "timeStamp", PayUtil.GetTimestamp() },
                { "nonceStr", result.NonceStr },
                { "package", "prepay_id=" + result.PrepayId },
                { "signType", "MD5" }
            };
            _dict.Add("paySign", PayUtil.CreateMd5Sign(_dict, WeChatConfigManager.Current.GetPayConfig().TenPayKey));

            #endregion

            ViewBag.PayPam = JsonConvert.SerializeObject(_dict);
            return(View());
        }
Exemplo n.º 6
0
        /// <summary>
        ///     订单查询接口
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public QueryResult OrderQuery(QueryRequest model)
        {
            var         url    = "https://api.mch.weixin.qq.com/pay/orderquery";
            QueryResult result = null;

            model.Appid     = WeChatConfig.AppId;
            model.Mch_id    = PayConfig.MchId;
            model.Nonce_str = PayUtil.GetNoncestr();
            var dictionary = PayUtil.GetAuthors(model);

            model.Sign = PayUtil.CreateMd5Sign(dictionary, PayConfig.TenPayKey); //生成Sign
            result     = PostXML <QueryResult>(url, model);
            return(result);
        }
Exemplo n.º 7
0
        public IHttpActionResult WechatPay(Guid id)
        {
            try
            {
                //查询订单
                var order =
                    db.Order_Infos.SingleOrDefault(
                        o => (o.Id == id) && (o.OpenId == WeiChatApplicationContext.Current.WeiChatUser.OpenId));
                if (null == order)
                {
                    return(BadRequest("订单信息不存在"));
                }

                #region 统一下单
                var model = new UnifiedorderRequest
                {
                    OpenId         = WeiChatApplicationContext.Current.WeiChatUser.OpenId,
                    SpbillCreateIp = "8.8.8.8",
                    OutTradeNo     = order.Code,
                    TotalFee       = Convert.ToInt32((order.TotalPrice + order.Shipping) * 100).ToString(),
                    NonceStr       = PayUtil.GetNoncestr(),
                    TradeType      = "JSAPI",
                    Body           = "购买商品",
                    DeviceInfo     = "WEB"
                };
                var result = WeChatApisContext.Current.TenPayV3Api.Unifiedorder(model);

                var _dict = new Dictionary <string, string>
                {
                    { "appId", result.AppId },
                    { "timeStamp", PayUtil.GetTimestamp() },
                    { "nonceStr", result.NonceStr },
                    { "package", "prepay_id=" + result.PrepayId },
                    { "signType", "MD5" }
                };
                _dict.Add("paySign", PayUtil.CreateMd5Sign(_dict, WeChatConfigManager.Current.GetPayConfig().TenPayKey));

                #endregion

                return(Ok(_dict));
            }
            catch (Exception ex)
            {
                log.Log(LoggerLevels.Error, "WechatPay:" + ex.Message);
            }
            return(BadRequest("操作失败,请联系管理员!"));
        }
Exemplo n.º 8
0
        public UnifiedorderResult Unifiedorder(UnifiedorderRequest model)
        {
            var url = "https://api.mch.weixin.qq.com/pay/unifiedorder";
            UnifiedorderResult result = null;

            model.AppId    = WeChatConfig.AppId;
            model.MchId    = PayConfig.MchId;
            model.NonceStr = PayUtil.GetNoncestr();
            if (model.NotifyUrl == null)
            {
                model.NotifyUrl = PayConfig.Notify;
            }
            var dictionary = PayUtil.GetAuthors(model);

            model.Sign = PayUtil.CreateMd5Sign(dictionary, PayConfig.TenPayKey); //生成Sign
            result     = PostXML <UnifiedorderResult>(url, model);
            return(result);
        }
Exemplo n.º 9
0
        /// <summary>
        /// 统一下单接口
        /// https://pay.weixin.qq.com/wiki/doc/api/app/app.php?chapter=9_1
        /// </summary>
        /// <param name="model"></param>
        /// <param name="sceneInfo"></param>
        /// <param name="tenPayKey"></param>
        /// <returns></returns>
        public UnifiedorderResult Unifiedorder(UnifiedorderRequest model, SceneInfo sceneInfo = null, string tenPayKey = null)
        {
            var url = "https://api.mch.weixin.qq.com/pay/unifiedorder";
            UnifiedorderResult result = null;

            model.AppId     = model.AppId ?? WeChatConfig.AppId;
            model.MchId     = model.MchId ?? PayConfig.MchId;
            model.NonceStr  = PayUtil.GetNoncestr();
            model.NotifyUrl = model.NotifyUrl ?? PayConfig.Notify;
            if (sceneInfo != null)
            {
                model.SceneInfo = JsonConvert.SerializeObject(sceneInfo);
            }
            var dictionary = PayUtil.GetAuthors(model);

            model.Sign = PayUtil.CreateMd5Sign(dictionary, tenPayKey ?? PayConfig.TenPayKey); //生成Sign

            result = PostXML <UnifiedorderResult>(url, model);
            return(result);
        }
Exemplo n.º 10
0
        public IHttpActionResult PayMoney([FromBody] Log_Recharge model)
        {
            log.Log(LoggerLevels.Debug, "进入API[PayMoney]");
            if (model.Amount <= 0)
            {
                return(BadRequest("充值金额必须大于0!"));
            }

            #region 统一下单

            var paymodel = new UnifiedorderRequest
            {
                OpenId         = WeiChatApplicationContext.Current.WeiChatUser.OpenId,
                SpbillCreateIp = "8.8.8.8",
                OutTradeNo     = PayUtil.GenerateOutTradeNo(),
                TotalFee       = Convert.ToInt32(model.Amount * 100).ToString(),
                NonceStr       = PayUtil.GetNoncestr(),
                TradeType      = "JSAPI",
                Body           = "购买商品",
                DeviceInfo     = "WEB"
            };
            var result = WeChatApisContext.Current.TenPayV3Api.Unifiedorder(paymodel);

            var _dict = new Dictionary <string, string>
            {
                { "appId", result.AppId },
                { "timeStamp", PayUtil.GetTimestamp() },
                { "nonceStr", result.NonceStr },
                { "package", string.Format("prepay_id={0}", result.PrepayId) },
                { "signType", "MD5" }
            };
            _dict.Add("paySign", PayUtil.CreateMd5Sign(_dict, WeChatConfigManager.Current.GetPayConfig().TenPayKey));

            #endregion

            return(Ok(_dict));
        }
Exemplo n.º 11
0
        /// <summary>
        /// 页面加载
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(AppId) && !string.IsNullOrEmpty(AppKey) && !string.IsNullOrEmpty(MchId))
            {
                PayUtil.SaveLog("单次支付开始", "");
                PayUtil.SaveLog("传递支付参数", string.Format("OrderSN={0}、Body={1}、TotalFee={2}、Attach={3}、UserOpenId={4}", this.OrderSN, this.Body, this.TotalFee, this.Attach, this.UserOpenId));

                #region 基本参数===========================

                //设置package订单参数  具体参数列表请参考官方pdf文档,请勿随意设置
                Hashtable hsRequest = new Hashtable();
                hsRequest.Add("body", this.Body); //商品信息 127字符
                hsRequest.Add("appid", AppId);
                hsRequest.Add("mch_id", MchId);
                hsRequest.Add("nonce_str", NonceStr.ToLower());
                hsRequest.Add("notify_url", PayConfig.NotifyUrl);
                hsRequest.Add("openid", this.UserOpenId);
                hsRequest.Add("out_trade_no", this.OrderSN);                     //商家订单号
                hsRequest.Add("spbill_create_ip", Page.Request.UserHostAddress); //用户的公网ip,不是商户服务器IP
                hsRequest.Add("total_fee", this.TotalFee);                       //商品金额,以分为单位(money * 100).ToString()
                hsRequest.Add("trade_type", "JSAPI");
                if (!string.IsNullOrEmpty(this.Attach))
                {
                    hsRequest.Add("attach", this.Attach);//自定义参数 127字符
                }
                #endregion

                #region ===========生成签名==========
                PayUtil.CreateMd5Sign(hsRequest, AppKey, Request.ContentEncoding.BodyName);
                PayUtil.SaveLog("Pay页面Sign:", Sign);
                #endregion

                #region ===========获取package扩展包==========
                hsRequest.Add("sign", Sign);
                string data = PayUtil.ParseXML(hsRequest);
                PayUtil.SaveLog("Pay页面package(XML):", data);

                string prepayXml = PayUtil.Send(data, "https://api.mch.weixin.qq.com/pay/unifiedorder");
                PayUtil.SaveLog("Pay页面package(Back_XML):", prepayXml);

                //获取预支付ID
                var xmlDoc = new XmlDocument();
                xmlDoc.LoadXml(prepayXml);
                XmlNode     xn  = xmlDoc.SelectSingleNode("xml");
                XmlNodeList xnl = xn.ChildNodes;
                if (xnl.Count > 7)
                {
                    PrepayId = xnl[7].InnerText;
                    Package  = string.Format("prepay_id={0}", PrepayId);
                    PayUtil.SaveLog("Pay页面package:", Package);
                }
                #endregion

                #region =======生成【微信支付签名】=======
                Hashtable hsPaySign = new Hashtable();
                hsPaySign.Add("appId", AppId);
                hsPaySign.Add("timeStamp", TimeStamp);
                hsPaySign.Add("nonceStr", NonceStr);
                hsPaySign.Add("package", Package);
                hsPaySign.Add("signType", "MD5");
                PaySign = PayUtil.CreateMd5Sign(hsPaySign, AppKey, Request.ContentEncoding.BodyName);
                PayUtil.SaveLog("Pay页面paySign:", PaySign);
                #endregion
                //页面数据显示
                BindData();
            }
            else
            {
                Response.Write("参数不正确");
                Response.End();
            }
        }