Ejemplo n.º 1
0
        /// <summary>
        /// Initializes a new instance of the <see cref="PoolConfig"/> class.
        /// </summary>
        /// <param name="config">The configuration.</param>
        /// <param name="coinConfig"></param>
        public PoolConfig(dynamic config, ICoinConfig coinConfig)
        {
            try
            {
                Enabled = config.enabled ? config.enabled : false;

                if (Enabled == false) // if the configuration is not enabled
                {
                    return;           // just skip reading rest of the parameters.
                }
                Coin = coinConfig;    // assign the coin config.

                // load the sections.
                Daemon   = new DaemonConfig(config.daemon);
                Meta     = new MetaConfig(config.meta);
                Wallet   = new WalletConfig(config.wallet);
                Rewards  = new RewardsConfig(config.rewards);
                Payments = new PaymentConfig(config.payments);
                Miner    = new MinerConfig(config.miner);
                Job      = new JobConfig(config.job);
                Stratum  = new StratumServerConfig(config.stratum);
                Banning  = new BanConfig(config.banning);
                Storage  = new RedisConfig(config.storage.redis);
                Vanilla  = new VanillaServerConfig(config.vanilla);

                Valid = true;
            }
            catch (Exception e)
            {
                Valid = false;
                Log.Logger.ForContext <PoolConfig>().Error(e, "Error loading pool configuration");
            }
        }
Ejemplo n.º 2
0
        static Payment()
        {
            var type     = typeof(Payment).GetTypeInfo();
            var resource = $"{type.Namespace}.payment.json";

            _config = Wechat.LoadConfiguration <PaymentConfig>(type.Assembly, resource);
        }
Ejemplo n.º 3
0
        protected override CommandResult <PayOrderResult> OnExecute(object commandParameter)
        {
            var           param     = commandParameter as PayOrderParamter;
            var           result    = new CommandResult <PayOrderResult>();
            PaymentConfig payConfig = null;

            using (CoreContext db = new CoreContext())
            {
                PayOrder payOrder = param.Order;

                if (payOrder == null)
                {
                    Serilog.Log.Logger.Error($"#{System.Reflection.MethodBase.GetCurrentMethod().DeclaringType}#order payment not fount {payOrder.OrderNo}");
                    result.ErrorCode    = -1;
                    result.ErrorMessage = "order payment not fount";
                    return(result);
                }
                if (payOrder.PayFee != param.PaymentPrice)
                {
                    Serilog.Log.Logger.Error($"#{System.Reflection.MethodBase.GetCurrentMethod().DeclaringType}#Weixinpaynotify#支付失败,paymentNo ={payOrder.OrderNo}," +
                                             $" tradeNo ={param.TradeNo},totalprice={param.PaymentPrice}");
                    result.ErrorCode    = -1;
                    result.ErrorMessage = $"requestfee-{param.PaymentPrice} and checkfee-{payOrder.PayFee} not match ";
                    return(result);
                }
                payConfig = db.PaymentConfig.Where(p => p.Id == payOrder.PaymentId && p.Status == "1").FirstOrDefault();

                int updateRes = db.Database.ExecuteSqlCommand($@"update pay_order set status=1 where order_no={payOrder.OrderNo} and status !=1 ");
                if (updateRes == 1 && payConfig != null)
                {
                    // payOrder.Status = 1;

                    db.PaymentLog.Add(new PaymentLog()
                    {
                        PayStatus      = "1",
                        CreateDate     = DateTime.Now,
                        PaymentAccount = payOrder.MemberAccount,
                        PaymentFee     = payOrder.PayFee,
                        PaymentId      = payConfig.Id,
                        PaymentNo      = payOrder.OrderNo,
                        PayTime        = DateTime.Now,
                        TradeNo        = param.TradeNo
                    });
                    db.SaveChanges();
                    Serilog.Log.Logger.Error($"#{System.Reflection.MethodBase.GetCurrentMethod().DeclaringType}#Weixinpaynotify#支付成功,paymentNo ={payOrder.OrderNo}," +
                                             $" tradeNo ={param.TradeNo},totalprice={param.PaymentPrice}");

                    result.Data = new PayOrderResult
                    {
                        PayOrder = payOrder
                    };
                    result.Data.PayOrder.Status = 1;
                }
            }
            return(result);
        }
        // GET: api/PaymentConfig
        public IHttpActionResult Get()
        {
            var Paypal = new PaymentConfig();

            Paypal.clientID = "ATeP6-3U_7VqZH1E1PI00z6-W4R3GraTkM0PUW5QGXIt_W8SFBXCsy8uIUW0zmiJut7-gkhp2AFIo_Lt";
            var PaypalBuisness = new PaymentConfig {
                clientID = "ARADpfI3AFhDI9dYkFe-13tvLGYmtVQuR17bqF62DGTo_xegU1nqST7OfJXe3KmgUczLkbXzZj0nu99o"
            };

            return(Ok(Paypal));
        }
        public IActionResult WeiXinPayCallBack()
        {
            Hashtable requestHash = WxPayUtil.ParseXML(Request.Body);
            string    payno       = requestHash["out_trade_no"] as string;

            LogUtil.Log("wxpay", payno, JsonConvert.SerializeObject(requestHash));

            PaymentConfig payConfig = null;
            PayOrder      payOrder  = (from o in _context.PayOrder where o.OrderNo == payno select o).FirstOrDefault();

            payConfig = (from p in _context.PaymentConfig where p.Status == "1" && p.Id == payOrder.PaymentId select p).FirstOrDefault();
            if (payOrder == null || payConfig == null)
            {
                return(Content("fail"));
            }

            if (!WxPayUtil.CheckSign(requestHash, payConfig.PrivateKey))
            {
                logger.Error("Weixinpay:验证签名失败" + payno);
                return(Content("fail"));
            }

            //获取交易状态
            string returnCode = requestHash["return_code"] as string;
            string resultCode = requestHash["result_code"] as string;

            //状态正常的时候才能调用PayOrder接口
            if (returnCode == "SUCCESS" && resultCode == "SUCCESS")
            {
                string  tradeNo    = requestHash["transaction_id"] as string;
                decimal paymentFee = Convert.ToDecimal(requestHash["total_fee"]) / 100;

                var payRes = new PayOrderCommand().Execute(new PayOrderParamter()
                {
                    PaymentPrice = paymentFee,
                    Order        = payOrder,
                    TradeNo      = tradeNo
                });

                if (payRes.ErrorCode != 0)
                {
                    logger.Error(payRes.ErrorMessage);
                    return(Content("fail"));
                }
                else
                {
                    return(Content("<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>"));
                }
            }
            else
            {
                return(Content("fail"));
            }
        }
Ejemplo n.º 6
0
        /// <summary>
        /// Initializes a new instance of the <see cref="PoolConfig"/> class.
        /// </summary>
        /// <param name="config">The configuration.</param>
        /// <param name="coinConfig"></param>
        public PoolConfig(dynamic config, ICoinConfig coinConfig)
        {
            try
            {
                _logger = Log.ForContext <PoolConfig>().ForContext("Component", coinConfig.Name);

                Enabled = config.enabled ? config.enabled : false;

                if (Enabled == false) // if the configuration is not enabled
                {
                    return;           // just skip reading rest of the parameters.
                }
                Coin = coinConfig;    // assign the coin config.

                // load the sections.
                Daemon   = new DaemonConfig(config.daemon);
                Meta     = new MetaConfig(config.meta);
                Wallet   = new WalletConfig(config.wallet);
                Rewards  = new RewardsConfig(config.rewards);
                Payments = new PaymentConfig(config.payments);
                Miner    = new MinerConfig(config.miner);
                Job      = new JobConfig(config.job);
                Stratum  = new StratumServerConfig(config.stratum);
                Banning  = new BanConfig(config.banning);
                Storage  = new StorageConfig(config.storage);
                Vanilla  = new VanillaServerConfig(config.vanilla);

                // process extra checks
                if (Storage.Layer is MposStorageLayerConfig)
                {
                    if (Payments.Enabled)
                    {
                        Payments.Disable();
                        _logger.Information("Disabled payments processor as it can not be enabled when MPOS mode is on");
                    }
                }

                Valid = true;
            }
            catch (Exception e)
            {
                Valid = false;
                _logger.Error(e, "Error loading pool configuration");
            }
        }
Ejemplo n.º 7
0
        /// <summary>
        /// Initializes a new instance of the <see cref="PoolConfig"/> class.
        /// </summary>
        /// <param name="config">The configuration.</param>
        /// <param name="coinConfig"></param>
        public PoolConfig(dynamic config, ICoinConfig coinConfig)
        {
            try
            {
                _logger = Log.ForContext<PoolConfig>().ForContext("Component", coinConfig.Name);

                Enabled = config.enabled ? config.enabled : false;

                if (Enabled == false) // if the configuration is not enabled
                    return; // just skip reading rest of the parameters.

                // load the sections.
                Coin = coinConfig; // assign the coin config.
                Daemon = new DaemonConfig(config.daemon);
                Meta = new MetaConfig(config.meta);
                Wallet = new WalletConfig(config.wallet);
                Rewards = new RewardsConfig(config.rewards);
                Payments = new PaymentConfig(config.payments);
                Miner = new MinerConfig(config.miner);
                Job = new JobConfig(config.job);
                Stratum = new StratumServerConfig(config.stratum);
                Banning = new BanConfig(config.banning);
                Storage = new StorageConfig(config.storage);
                Getwork = new GetworkServerConfig(config.getwork);

                // process extra checks
                if (Storage.Layer is MposStorageConfig)
                {
                    if (Payments.Enabled)
                    {
                        Payments.Disable();
                        _logger.Information("Disabled payment processor as it can not be enabled when MPOS mode is on");
                    }
                }

                Valid = true;
            }
            catch (Exception e)
            {
                Valid = false;
                _logger.Error(e, "Error loading pool configuration");
            }
        }
Ejemplo n.º 8
0
        public void Projection_Returns_Null_For_Nested_Property()
        {
            using (var store = GetDocumentStore())
            {
                using (var session = store.OpenSession())
                {
                    var config = new PaymentConfig {
                        Currency = "USD"
                    };
                    session.Store(config, PaymentConfig.Id);

                    var order = new Order
                    {
                        CustomerName = "Bob",
                        OrderItems   = new[]
                        {
                            new OrderItem {
                                ItemId = "1", Price = 100
                            },
                            new OrderItem {
                                ItemId = "2", Price = 50
                            }
                        }
                    };
                    session.Store(order);

                    session.SaveChanges();
                }

                WaitForIndexing(store);

                using (var session = store.OpenSession())
                {
                    var st = (from o in session.Query <Order>()
                              let config = RavenQuery.Load <PaymentConfig>(PaymentConfig.Id)
                                           select new OrderProjection
                    {
                        OrderId = o.Id,
                        CustomerName = o.CustomerName,
                        OrderItems = from i in o.OrderItems
                                     select new OrderItemProjection
                        {
                            ItemId = i.ItemId,
                            Price = i.Price,
                            Currency = config.Currency
                        }
                    }).ToString();

                    var result = (from o in session.Query <Order>()
                                  let config = RavenQuery.Load <PaymentConfig>(PaymentConfig.Id)
                                               select new OrderProjection
                    {
                        OrderId = o.Id,
                        CustomerName = o.CustomerName,
                        OrderItems = from i in o.OrderItems
                                     select new OrderItemProjection
                        {
                            ItemId = i.ItemId,
                            Price = i.Price,
                            Currency = config.Currency
                        }
                    }).Single();
                    WaitForUserToContinueTheTest(store);
                    Assert.All(result.OrderItems, item => Assert.Equal("USD", item.Currency));
                }
            }
        }
Ejemplo n.º 9
0
        private string OnPay(DataRow row)
        {
            #region 获取基本参数
            string CommunityId = string.Empty;
            if (row.Table.Columns.Contains("CommunityId"))
            {
                CommunityId = row["CommunityId"].ToString();
            }
            string RoomID = string.Empty;
            if (row.Table.Columns.Contains("RoomID"))
            {
                RoomID = row["RoomID"].ToString();
            }
            string CustID = string.Empty;
            if (row.Table.Columns.Contains("CustID"))
            {
                CustID = row["CustID"].ToString();
            }
            string OpenID = string.Empty;
            if (row.Table.Columns.Contains("OpenID"))
            {
                OpenID = row["OpenID"].ToString();
            }
            if (!row.Table.Columns.Contains("PayChannel") || string.IsNullOrEmpty(row["PayChannel"].ToString()))
            {
                return(new ApiResult(false, "参数PayChannel有误").toJson());
            }
            var community = GetCommunity(CommunityId);
            if (community == null)
            {
                return(JSONHelper.FromString(false, "未查询到小区信息"));
            }

            int CommID = AppGlobal.StrToInt(community.CommID);
            PubConstant.hmWyglConnectionString = GetConnectionStr(community);

            var payChannel = row["PayChannel"].ToString();
            var payType    = 0;

            switch (payChannel.ToLower())
            {
            case PayChannelString.Alipay:
                payType = 1;
                break;

            case PayChannelString.WechatPay:
                payType = 2;
                break;

            case PayChannelString.AllInPay_Alipay:
                payType = 1;
                break;

            case PayChannelString.AllInPay_WechatPay:
                payType = 2;
                break;

            default:
                return(new ApiResult(false, "参数payChannel有误").toJson());
            }
            if (payType == 2)
            {
                if (payChannel.ToLower().Equals(PayChannelString.AllInPay_WechatPay) && string.IsNullOrEmpty(OpenID))
                {
                    return(new ApiResult(false, "参数OpenID不能为空").toJson());
                }
            }

            #endregion

            using (IDbConnection erpConn = new SqlConnection(PubConstant.hmWyglConnectionString))
            {
                dynamic tb_Payment_Config = erpConn.QueryFirstOrDefault <dynamic>("SELECT * FROM Tb_Payment_Config WITH(NOLOCK) WHERE CommID = @CommID", new { CommID });
                if (null == tb_Payment_Config)
                {
                    return(new ApiResult(false, "该项目未开通对应支付方式").toJson());
                }
                // 旧方式获取对应支付配置
                AllinConfig allinConfig = null;
                // 新方式获取支付配置
                PaymentConfig paymentConfig = null;
                if (payChannel == PayChannelString.AllInPay_Alipay || payChannel == PayChannelString.AllInPay_WechatPay)
                {
                    try
                    {
                        allinConfig = JsonConvert.DeserializeObject <AllinConfig>(tb_Payment_Config.Config);
                        if (null == allinConfig)
                        {
                            return(new ApiResult(false, "该项目支付类型对应配置有误").toJson());
                        }
                    }
                    catch (Exception)
                    {
                        return(new ApiResult(false, "该项目支付类型对应配置有误").toJson());
                    }
                }
                else
                {
                    // 新的方式,Config存储多个配置
                    try
                    {
                        // ERP的配置表,要求存储一个Json数组,用于配置支持不同支付方式
                        // 配置项要求存储一个
                        List <PaymentConfig> configs = JsonConvert.DeserializeObject <List <PaymentConfig> >(tb_Payment_Config.Config);
                        if (null == configs || configs.Count <= 0)
                        {
                            return(new ApiResult(false, "该项目支付类型对应配置有误").toJson());
                        }
                        if (payChannel == PayChannelString.Alipay)
                        {
                            paymentConfig = configs.Find(item => item.type == "AliPay");
                        }
                        if (payChannel == PayChannelString.WechatPay)
                        {
                            paymentConfig = configs.Find(item => item.type == "WChatPay");
                        }
                        if (null == paymentConfig)
                        {
                            return(new ApiResult(false, "该项目支付类型对应配置有误").toJson());
                        }
                    }
                    catch (Exception)
                    {
                    }
                }
                #region 计算金额
                if (!row.Table.Columns.Contains("PayData") || string.IsNullOrEmpty(row["PayData"].ToString()))
                {
                    return(new ApiResult(false, "缺少参数PayData").toJson());
                }
                string PayData = row["PayData"].ToString();
                if (!CheckPayData(Global_Fun.BurstConnectionString(CommID, Global_Fun.BURST_TYPE_CHARGE), Convert.ToInt64(CustID), Convert.ToInt64(RoomID), PayData, out decimal Amt, out string errMsg, true, false, !"1940".Equals(Global_Var.LoginCorpID)))
                {
                    return(new ApiResult(false, errMsg).toJson());
                }
                if (Amt <= 0.00M)
                {
                    return(new ApiResult(false, "金额必须大于0").toJson());
                }
                #endregion

                JObject PayDataObj = JObject.Parse(PayData);
                int     Type       = (int)PayDataObj["Type"];

                #region 查询项目名称和房屋编号,拼接费用备注
                string FeesMemo = string.Empty;
                string RoomSign = string.Empty;
                if (Type == 1)
                {
                    FeesMemo = "物业综合费用缴纳";
                    string CommName = erpConn.QueryFirstOrDefault <string>("SELECT CommName FROM Tb_HSPR_Community WHERE CommID = @CommID", new { CommID });
                    if (string.IsNullOrEmpty(CommName))
                    {
                        CommName = Convert.ToString(CommID);
                    }
                    RoomSign = erpConn.QueryFirstOrDefault <string>("SELECT ISNULL(RoomSign,RoomName) AS RoomSign FROM Tb_HSPR_Room WHERE RoomID = @RoomID", new { RoomID });
                    if (string.IsNullOrEmpty(RoomSign))
                    {
                        RoomSign = Convert.ToString(RoomID);
                    }

                    FeesMemo += string.Format("-{0}-{1}", CommName, RoomSign);
                }
                else
                {
                    FeesMemo = "物业综合费用预存";
                    string CommName = erpConn.QueryFirstOrDefault <string>("SELECT CommName FROM Tb_HSPR_Community WHERE CommID = @CommID", new { CommID });
                    if (string.IsNullOrEmpty(CommName))
                    {
                        CommName = Convert.ToString(CommID);
                    }
                    RoomSign = erpConn.QueryFirstOrDefault <string>("SELECT ISNULL(RoomSign,RoomName) AS RoomSign FROM Tb_HSPR_Room WHERE RoomID = @RoomID", new { RoomID });
                    if (string.IsNullOrEmpty(RoomSign))
                    {
                        RoomSign = Convert.ToString(RoomID);
                    }

                    FeesMemo += string.Format("-{0}-{1}", CommName, RoomSign);
                }
                #endregion

                string NoticeId = Guid.NewGuid().ToString();

                // 生成订单
                if (erpConn.Execute("INSERT INTO Tb_Notice(Id, CommID, RoomID, CustID, PayData, CreateTime) VALUES(@Id, @CommID, @RoomID, @CustID, @PayData, @CreateTime)", new { Id = NoticeId, CommID, RoomID, CustID, PayData, CreateTime = DateTime.Now.ToString() }) <= 0)
                {
                    return(new ApiResult(false, "创建收款订单失败,请重试").toJson());
                }
                string ChargeMode = "业主APP缴费";
                if (payChannel == PayChannelString.AllInPay_Alipay)
                {
                    ChargeMode = "通联_业主APP(支付宝)";
                }
                else if (payChannel == PayChannelString.AllInPay_WechatPay)
                {
                    ChargeMode = "通联_业主APP(微信)";
                }
                else
                {
                    ChargeMode = "通联_业主APP";
                }
                #region 修改收款方式
                if (erpConn.QueryFirstOrDefault <int>("SELECT COUNT(1) FROM syscolumns WHERE id=object_id('Tb_Notice') AND name = 'ChargeMode'") > 0)
                {
                    erpConn.Execute("UPDATE Tb_Notice SET ChargeMode = @ChargeMode WHERE Id = @Id", new { ChargeMode, Id = NoticeId });
                }
                #endregion
                DateTime dateNow          = DateTime.Now;
                string   OrderSN          = dateNow.ToString("yyyyMMddHHmmssfff") + Utils.BuildRandomStr(3);
                string   PaymentNotifyUrl = string.Empty;

                Dictionary <string, string> param = null;
                if (payChannel == PayChannelString.AllInPay_Alipay || payChannel == PayChannelString.AllInPay_WechatPay)
                {
                    #region 请求通联支付
                    #region 获取对应类型的下账地址
                    if (Type == 1)
                    {
                        PaymentNotifyUrl = AppGlobal.GetAppSetting("AllinPay_Notify_Url") + "?CommID=" + CommID;
                    }
                    else
                    {
                        PaymentNotifyUrl = AppGlobal.GetAppSetting("AllinPay_Prec_Notify_Url") + "?CommID=" + CommID;
                    }
                    #endregion
                    try
                    {
                        param = SybWxPayService.Pay(Convert.ToInt64(Amt * 100), OrderSN, payChannel == PayChannelString.AllInPay_Alipay ? "A01" : "W06", FeesMemo, RoomSign, OpenID, "", PaymentNotifyUrl, "", "", "", "", allinConfig.orgid, allinConfig.appid, allinConfig.custid, allinConfig.appkey, allinConfig.subbranch);

                        if (param == null || !param.ContainsKey("payinfo"))
                        {
                            GetLog().Error("OnPay:" + JsonConvert.SerializeObject(param));
                            return(new ApiResult(false, "生成支付订单失败,请重试").toJson());
                        }
                    }
                    catch (Exception ex)
                    {
                        GetLog().Error("OnPay", ex);
                        return(new ApiResult(false, "生成支付订单失败,请重试").toJson());
                    }
                    if (erpConn.Execute(@"INSERT INTO Tb_Payment_Order(PayType, OrderSN, NoticeId, Amt, CreateTime) 
                                            VALUES(@PayType, @OrderSN, @NoticeId, @Amt, @CreateTime)",
                                        new { PayType = payType, OrderSN = OrderSN, NoticeId = NoticeId, Amt = Amt, CreateTime = dateNow }) <= 0)
                    {
                        return(new ApiResult(false, "生成支付订单失败,请重试(1003)").toJson());
                    }
                    return(new ApiResult(true, new { OrderSN = OrderSN, QrCode = param["payinfo"].ToString() }).toJson());

                    #endregion
                }
                if (payChannel == PayChannelString.Alipay)
                {
                    AliConfig aliConfig = null;
                    try
                    {
                        aliConfig = Config.GetConfig <AliConfig>(paymentConfig.config);
                        if (null == aliConfig)
                        {
                            return(new ApiResult(false, "该项目支付类型对应配置有误").toJson());
                        }
                    }
                    catch (Exception)
                    {
                        return(new ApiResult(false, "该项目支付类型对应配置有误").toJson());
                    }
                    #region 请求支付宝官方支付
                    #region 获取对应类型的下账地址
                    PaymentNotifyUrl = AppGlobal.GetAppSetting("AliPay_Notify_Url");
                    #endregion
                    AlipayTradeAppPayResponse response = null;
                    try
                    {
                        JObject BizContent = new JObject();
                        //要求15分钟内支付
                        BizContent.Add("timeout_express", "15m");
                        BizContent.Add("total_amount", Amt);
                        BizContent.Add("body", FeesMemo);
                        BizContent.Add("subject", FeesMemo);
                        BizContent.Add("out_trade_no", OrderSN);
                        IAopClient client = new DefaultAopClient("https://openapi.alipay.com/gateway.do", aliConfig.appid, aliConfig.app_private_key, "json", "1.0", "RSA2", aliConfig.alipay_public_key, "UTF-8", false);
                        AlipayTradeAppPayRequest request = new AlipayTradeAppPayRequest
                        {
                            BizContent = JsonConvert.SerializeObject(BizContent),
                        };
                        request.SetNotifyUrl(PaymentNotifyUrl);
                        response = client.SdkExecute(request);
                    }
                    catch (Exception ex)
                    {
                        Log(ex.Message, "AliPayLogs\\");
                        GetLog().Error(ex.Message + Environment.CommandLine + ex.StackTrace);
                        return(new ApiResult(false, "请求订单失败,请重试").toJson());
                    }
                    if (erpConn.Execute("INSERT INTO Tb_Payment_Order(PayType, OrderSN, NoticeId, Amt, CreateTime) VALUES(@PayType, @OrderSN, @NoticeId, @Amt, @CreateTime)", new { PayType = 1, OrderSN, NoticeId = NoticeId, Amt = Amt, CreateTime = dateNow }) <= 0)
                    {
                        return(new ApiResult(false, "生成订单失败").toJson());
                    }
                    return(new ApiResult(true, new { OrderSN = OrderSN, QrCode = response.Body }).toJson());

                    #endregion
                }
                if (payChannel == PayChannelString.WechatPay)
                {
                    WxConfig wxConfig = null;
                    try
                    {
                        wxConfig = Config.GetConfig <WxConfig>(paymentConfig.config);
                        if (null == wxConfig)
                        {
                            return(new ApiResult(false, "该项目支付类型对应配置有误").toJson());
                        }
                    }
                    catch (Exception)
                    {
                        return(new ApiResult(false, "该项目支付类型对应配置有误").toJson());
                    }

                    #region 请求微信官方支付
                    #region 获取对应类型的下账地址
                    PaymentNotifyUrl = AppGlobal.GetAppSetting("WxPay_Notify_Url");
                    #endregion
                    WxPayData wxPayData = new WxPayData();
                    wxPayData.SetValue("appid", wxConfig.appid);
                    wxPayData.SetValue("body", FeesMemo);
                    wxPayData.SetValue("mch_id", wxConfig.mch_id);
                    wxPayData.SetValue("nonce_str", WxPayApi.GenerateNonceStr());
                    wxPayData.SetValue("notify_url", PaymentNotifyUrl);
                    wxPayData.SetValue("out_trade_no", OrderSN);
                    wxPayData.SetValue("spbill_create_ip", "8.8.8.8");
                    wxPayData.SetValue("total_fee", Convert.ToInt32(Amt * 100));
                    wxPayData.SetValue("trade_type", "APP");
                    wxPayData.SetValue("sign_type", wxpay.utils.WxPayData.SIGN_TYPE_HMAC_SHA256);
                    wxPayData.SetValue("sign", wxPayData.MakeSign(wxConfig.appkey));
                    try
                    {
                        wxPayData = WxPayApi.UnifiedOrder(wxPayData);
                    }
                    catch (Exception)
                    {
                        return(new ApiResult(false, "请求超时,请重试").toJson());
                    }
                    if (!wxPayData.IsSet("return_code") || !"SUCCESS".Equals(wxPayData.GetValue("return_code").ToString()))
                    {
                        return(new ApiResult(false, "请求支付订单失败").toJson());
                    }
                    if (!wxPayData.IsSet("result_code") || !"SUCCESS".Equals(wxPayData.GetValue("result_code").ToString()))
                    {
                        return(new ApiResult(false, "请求支付订单失败").toJson());
                    }
                    if (!wxPayData.IsSet("prepay_id"))
                    {
                        return(new ApiResult(false, "请求支付订单失败").toJson());
                    }
                    string prepay_id = wxPayData.GetValue("prepay_id").ToString();
                    if (erpConn.Execute("INSERT INTO Tb_Payment_Order(PayType, OrderSN, NoticeId, Amt, CreateTime) VALUES(@PayType, @OrderSN, @NoticeId, @Amt, @CreateTime)", new { PayType = 2, OrderSN, NoticeId = NoticeId, Amt = Amt, CreateTime = dateNow }) <= 0)
                    {
                        return(new ApiResult(false, "生成订单失败").toJson());
                    }
                    WxPayData result = new WxPayData();
                    result.SetValue("appid", wxPayData.GetValue("appid").ToString());
                    result.SetValue("partnerid", wxPayData.GetValue("mch_id").ToString());
                    result.SetValue("prepayid", prepay_id);
                    result.SetValue("package", "Sign=WXPay");
                    result.SetValue("noncestr", wxPayData.GetValue("nonce_str").ToString());
                    result.SetValue("timestamp", WxPayApi.GenerateTimeStamp());
                    result.SetValue("sign", result.MakeSign(wxpay.utils.WxPayData.SIGN_TYPE_HMAC_SHA256, wxConfig.appkey));
                    JObject jObj = JObject.Parse(result.ToJson());
                    return(new ApiResult(true, new { OrderSN = OrderSN, QrCode = jObj }).toJson());

                    #endregion
                }
                return(new ApiResult(false, "不支持的支付方式").toJson());
            }
        }
Ejemplo n.º 10
0
 public WxPayConfig()
 {
     PaymentConfig.Init(config);
 }
Ejemplo n.º 11
0
        protected override CommandResult <int> OnExecute(object commandParameter)
        {
            var param  = commandParameter as CheckWeiXinPayParameter;
            var result = new CommandResult <int>();

            result.Data = 0;
            using (CoreContext context = new CoreContext())
            {
                var      payno = param.PayNo;
                PayOrder order = context.PayOrder.Where(o => o.OrderNo == payno).FirstOrDefault();
                if (order != null)
                {
                    if (order.Status == 1)
                    {
                        result.Data = 1;
                        return(result);
                    }
                    PaymentConfig payment  = context.PaymentConfig.Where(p => p.Id == order.PaymentId).FirstOrDefault();
                    Hashtable     webParam = new Hashtable
                    {
                        ["out_trade_no"] = payno,
                        ["nonce_str"]    = Guid.NewGuid().ToString("N"),
                        ["appid"]        = payment.AppId,
                        ["mch_id"]       = payment.UserId
                    };

                    WxPayUtil.SetMD5Sign(webParam, payment.PrivateKey);

                    string body = WxPayUtil.GetXMLString(webParam);

                    string         posturl = "https://api.mch.weixin.qq.com/pay/orderquery";
                    WebClient      web     = new WebClient();
                    HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(posturl);
                    request.ContentType = "application/x-www-form-urlencoded";
                    request.Method      = "POST";

                    byte[] postdata = Encoding.GetEncoding("UTF-8").GetBytes(body);
                    request.ContentLength = postdata.Length;

                    Stream newStream = request.GetRequestStream();

                    newStream.Write(postdata, 0, postdata.Length);
                    newStream.Close();

                    HttpWebResponse myResponse = (HttpWebResponse)request.GetResponse();
                    //StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8);

                    Hashtable hash = WxPayUtil.ParseXML(myResponse.GetResponseStream());
                    if (hash["return_code"] as string == "SUCCESS" && hash["result_code"] as string == "SUCCESS" && hash["trade_state"] as string == "SUCCESS")
                    {
                        var payRes = new PayOrderCommand().Execute(new PayOrderParamter()
                        {
                            PaymentPrice = Convert.ToDecimal(hash["total_fee"]) / 100,
                            Order        = order,
                            TradeNo      = hash["transaction_id"] as string
                        });
                        if (payRes.Data.PayOrder.Status == 1)
                        {
                            result.Data = 1;
                        }
                    }
                    //记录同步操作
                    Serilog.Log.Logger.Information("wxpay_synchro", posturl,
                                                   "post====>\n" + Newtonsoft.Json.JsonConvert.SerializeObject(webParam) +
                                                   "res====>\n" + Newtonsoft.Json.JsonConvert.SerializeObject(hash));
                }
            }
            return(result);
        }
Ejemplo n.º 12
0
        protected override CommandResult <CreateBookOrderResult> OnExecute(object commandParameter)
        {
            var param  = commandParameter as CreateBookOrderParameter;
            var result = new CommandResult <CreateBookOrderResult>();

            result.Data = new CreateBookOrderResult();
            using (CoreContext context = new CoreContext())
            {
                var book = new BookUtil();
                if (book._Config == null)
                {
                    result.ErrorCode    = -1;
                    result.ErrorMessage = "活动已结束";
                    return(result);
                }
                if (DateTime.Now < book._Config.StartTime)
                {
                    result.ErrorCode    = -1;
                    result.ErrorMessage = "活动未开始";
                    return(result);
                }
                if (book._Config.EndTime < DateTime.Now)
                {
                    result.ErrorCode    = -1;
                    result.ErrorMessage = "活动已结束";
                    return(result);
                }

                var pmodel = book._ProductConfig.Where(p => p.ProductNo == param.ProductNo).FirstOrDefault();
                if (pmodel == null)
                {
                    return(ErrorResult <CreateBookOrderResult> .ParameterError);
                }
                var pSku = pmodel.SkuList.Where(s => s.ProductSkuNo == param.ProductSkuNo).FirstOrDefault();
                if (pSku == null)
                {
                    return(ErrorResult <CreateBookOrderResult> .ParameterError);
                }

                PaymentConfig payment = (from p in context.PaymentConfig where p.Id == param.PayId select p).FirstOrDefault();

                if (payment == null)
                {
                    result.ErrorMessage = "请设置支付方式";
                    result.ErrorCode    = -1;
                    return(result);
                }

                var redisdb    = RedisClient.GetDatabase();
                var orderIndex = redisdb.HashIncrementAsync("zlan.membercart.index", "OrderIndex").Result;

                string mainNo = string.Format("{0:yyMMddHHmmss}{1:D6}", DateTime.Now, orderIndex);
                //订单号
                string orderNo = string.Format("AT{0}00", mainNo);

                decimal totalFee = 0, discountFee = 0, productFee = 0;
                productFee = pSku.SalePrice;

                //开启事务
                using (var tran = context.Database.BeginTransaction())
                {
                    try
                    {
                        totalFee = productFee - discountFee;
                        //金额小于等于0创建失败
                        if (totalFee <= 0)
                        {
                            return(ErrorResult <CreateBookOrderResult> .ParameterError);
                        }
                        var order = new PayOrder()
                        {
                            OrderNo       = orderNo,
                            PaymentId     = param.PayId,
                            PayFee        = totalFee,
                            MemberAccount = param.MemberAccount,
                            TotalFee      = totalFee,
                            CreateTime    = DateTime.Now,
                            Kind          = "gift",
                            Status        = 0,
                            ProductFee    = productFee,
                            DiscountFee   = discountFee,
                            Memo          = $"【{pmodel.ProductName}】预付订单"
                        };
                        context.Add(order);

                        var bookinfo = new BookInfo()
                        {
                            Address       = param.Address,
                            City          = param.City,
                            Province      = param.Province,
                            Area          = param.Araea,
                            Phone         = param.Phone,
                            Name          = param.Name,
                            Counter       = 1,
                            ProductNo     = pmodel.ProductNo,
                            ProductSkuNo  = pSku.ProductSkuNo,
                            Status        = 0,
                            OrderNo       = orderNo,
                            ConfigId      = 1,
                            ProductConfig = JsonConvert.SerializeObject(pmodel),
                            StartTime     = book._ValidDate["Start"].Value <DateTime>(),
                            EndTime       = book._ValidDate["End"].Value <DateTime>(),
                            MemberAccount = param.MemberAccount,
                            CouponId      = pmodel.CouponId,
                            AddressId     = param.AddressId == 0 ? param.AddressId = -99 : param.AddressId
                        };
                        context.Add(bookinfo);
                        context.SaveChanges();

                        result.Data.PayId = payment.Id;
                        result.Data.PayNo = orderNo;
                        tran.Commit();
                    }
                    catch (Exception ex)
                    {
                        tran.Rollback();
                        result = ErrorResult <CreateBookOrderResult> .ParameterError;
                        result.ErrorMessage = ex.Message;
                        return(result);
                    }
                }
            }

            return(result);
        }
Ejemplo n.º 13
0
        protected override CommandResult <GetWxPaymentSignResult> OnExecute(object commandParameter)
        {
            var result = new CommandResult <GetWxPaymentSignResult>();
            var param  = commandParameter as GetWxPaymentSignParameter;

            if (string.IsNullOrEmpty(param.PayNo))
            {
                return(ErrorResult <GetWxPaymentSignResult> .ParameterError);
            }
            using (CoreContext _context = new CoreContext())
            {
                string   payno    = param.PayNo;
                PayOrder payOrder = _context.PayOrder.Where(o => o.OrderNo == payno).FirstOrDefault();
                if (payOrder == null)
                {
                    //Logger.Error("pay error,not found payconfig,payNo:" + payno);
                    LogUtil.Log("wxpay", payno, "pay error,not found payconfig,payNo:" + payno);
                    result.ErrorCode    = -1;
                    result.ErrorMessage = "找不到订单";
                    return(result);
                }
                if (payOrder.Status != 0)
                {
                    //Log.Logger.Error("pay error,order is pay,payNo:" + payno);
                    LogUtil.Log("wxpay", payno, "pay error,order is pay,payNo:" + payno);
                    result.ErrorCode    = 1;
                    result.ErrorMessage = "订单已支付,请刷新页面";
                    return(result);
                }
                PaymentConfig paymentConfig = _context.PaymentConfig.Where(c => c.Id == payOrder.PaymentId).FirstOrDefault();
                if (paymentConfig == null)
                {
                    // Log.Logger.Error("pay error,not found payconfig,payNo:" + payno);
                    LogUtil.Log("wxpay", payno, "pay error,not found payconfig,payNo:" + payno);
                    result.ErrorCode    = -1;
                    result.ErrorMessage = "支付方式不正确";
                    return(result);
                }
                MemberInfo member = _context.MemberInfo.Where(m => m.AccountId == payOrder.MemberAccount).FirstOrDefault();
                ////通过商城授权
                if (string.IsNullOrEmpty(member.ZlOpenId))
                {
                    // Log.Logger.Error("pay error,ouath faild");
                    LogUtil.Log("wxpay", payno, "pay error,ouath faild,openid is null");
                    return(ErrorResult <GetWxPaymentSignResult> .NoAuthorization);
                }

                var connectionString = ConfigurationUtil.GetSection("ConnectionStrings")["ShopConnectString"];
                var openid           = member.ZlOpenId;
                using (MySqlConnection conn = new MySqlConnection(connectionString))
                {
                    try
                    {
                        string opneidFiled = "wx_open_id";
                        switch (paymentConfig.Kind)
                        {
                        case "XCX":
                            opneidFiled = "xcx_open_id"; break;

                        case "WX": opneidFiled = "wx_open_id"; break;

                        default: break;
                        }
                        conn.Open();
                        string       sql     = $"select {opneidFiled} from member_info WHERE account_id=?acc LIMIT 1";
                        MySqlCommand command = new MySqlCommand(sql, conn);
                        command.Parameters.Add(new MySqlParameter()
                        {
                            ParameterName = "?acc",
                            Value         = member.ZlOpenId
                        });

                        MySqlDataReader reader = command.ExecuteReader();

                        while (reader.Read())
                        {
                            openid = reader[opneidFiled] as string;
                        }
                        reader.Close();
                    }
                    catch (Exception ex)
                    {
                        //Log.Logger.Error("get shop wx_openid fail#ex#" + ex.Message);
                        //LogUtil.Log("GetWxPaymentSignCommand", "GetWxPaymentSignCommand", "GetWxPaymentSignCommand", "get shop wx_openid fail#ex#" + ex.Message);
                        LogUtil.Log("wxpay", payno, ex.Message);
                        return(ErrorResult <GetWxPaymentSignResult> .NoLogin);
                    }
                }
                string productName = "";
                string ProductDesc = payOrder.Memo;
                if (ProductDesc.Length > 20)
                {
                    ProductDesc = ProductDesc.Substring(0, 20) + "...";
                }
                string    scheme    = !StringValues.IsNullOrEmpty(httpContext.Request.Headers["X-Client-Scheme"]) ? httpContext.Request.Headers["X-Client-Scheme"].ToString() : httpContext.Request.Scheme;
                Hashtable paramHash = new Hashtable
                {
                    ["appid"]            = paymentConfig.AppId,
                    ["mch_id"]           = paymentConfig.UserId, //商户号
                    ["trade_type"]       = "JSAPI",
                    ["nonce_str"]        = Guid.NewGuid().ToString("N"),
                    ["openid"]           = openid,
                    ["out_trade_no"]     = payno,
                    ["total_fee"]        = ((int)(payOrder.PayFee * 100)).ToString(),
                    ["notify_url"]       = $"{scheme}://{httpContext.Request.Host}" + "/PaymentCallBack/WeiXinPayCallBack",
                    ["body"]             = ProductDesc,
                    ["spbill_create_ip"] = httpContext.Connection.LocalIpAddress.ToString(),
                    ["time_start"]       = string.Format("{0:yyyyMMddHHmmss}", Convert.ToDateTime(payOrder.CreateTime)),
                    ["time_expire"]      = string.Format("{0:yyyyMMddHHmmss}", DateTime.Now.AddMinutes(10))
                };

                WxPayUtil.SetMD5Sign(paramHash, paymentConfig.PrivateKey);

                Hashtable responseHash = WxPayUtil.GetResponseHash("wxorder_" + payno, "https://api.mch.weixin.qq.com/pay/unifiedorder", paramHash);


                var prepayId = "";
                if (responseHash["return_code"] as string == "SUCCESS" && responseHash["result_code"] as string == "SUCCESS")
                {
                    prepayId = responseHash["prepay_id"] as string;
                }
                //调用接口出错
                else
                {
                    result.ErrorCode    = -1;
                    result.ErrorMessage = responseHash["return_msg"] + "=>" + responseHash["err_code_des"];
                    return(result);
                }
                //调用接口失败,未知错误
                if (string.IsNullOrEmpty(prepayId))
                {
                    result.ErrorCode    = -1;
                    result.ErrorMessage = "服务器忙";
                    return(result);
                }

                result.Data = new GetWxPaymentSignResult()
                {
                    AppId     = paymentConfig.AppId,
                    Timestamp = string.Format("{0}", WxPayUtil.GetTimestamp()),
                    NonceStr  = WxPayUtil.GetNoncestr(),
                    Package   = "prepay_id=" + prepayId,
                    SignType  = "MD5"
                };

                Hashtable choosePayParamHash = new Hashtable
                {
                    ["appId"]     = result.Data.AppId,
                    ["timeStamp"] = result.Data.Timestamp,
                    ["nonceStr"]  = result.Data.NonceStr,
                    ["package"]   = result.Data.Package,
                    ["signType"]  = result.Data.SignType
                };

                //签名
                result.Data.Signature = WxPayUtil.SetMD5Sign(choosePayParamHash, paymentConfig.PrivateKey);
                LogUtil.Log("wxpay", payno, "ouput=>" + JsonConvert.SerializeObject(result.Data));
            }
            return(result);
        }