/// <summary>
        /// 微信支付通知回写
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        public int UpdatePayOrder(WxOrder param)
        {
            int result = 0;

            // 当前时间
            string dateTimeNow = DateTimeHelper.convertDateTime(DateTime.Now.ToString());

            string strSql = " UPDATE WXORDER " +
                            " SET TRANSACTION_ID = '{0}' " +
                            " , CASH_FEE = {1} " +
                            " , FEE_TYPE = '{2}' " +
                            " , BANK_TYPE = '{3}' " +
                            " , TIME_END = '{4}' " +
                            " , RESULT_CODE = '{5}' " +
                            " , RETURN_CODE = '{6}' " +
                            " , NOTIFYTIME = '{7}' " +
                            " WHERE APPNAME = '{8}' " +
                            " AND OUT_TRADE_NO = '{9}' ";

            string strSqlFinal = string.Format(strSql, param.transaction_id, param.cash_fee, param.fee_type, param.bank_type, param.time_end,
                                               param.result_code, param.return_code, dateTimeNow, param.appName, param.out_trade_no);

            result = SqlServerHelper.Execute(SqlServerHelper.salesorderConn(), strSqlFinal);

            return(result);
        }
        public void DeleteTest()
        {
            WxOrder v = new WxOrder();

            using (var context = new DataContext(_seed, DBTypeEnum.Memory))
            {
                v.ID         = 16;
                v.OrderTotal = 12;
                v.UserId     = AddUser();
                context.Set <WxOrder>().Add(v);
                context.SaveChanges();
            }

            PartialViewResult rv = (PartialViewResult)_controller.Delete(v.ID.ToString());

            Assert.IsInstanceOfType(rv.Model, typeof(WxOrderVM));

            WxOrderVM vm = rv.Model as WxOrderVM;

            v         = new WxOrder();
            v.ID      = vm.Entity.ID;
            vm.Entity = v;
            _controller.Delete(v.ID.ToString(), null);

            using (var context = new DataContext(_seed, DBTypeEnum.Memory))
            {
                Assert.AreEqual(context.Set <WxOrder>().Count(), 0);
            }
        }
        public void BatchDeleteTest()
        {
            WxOrder v1 = new WxOrder();
            WxOrder v2 = new WxOrder();

            using (var context = new DataContext(_seed, DBTypeEnum.Memory))
            {
                v1.ID         = 16;
                v1.OrderTotal = 12;
                v1.UserId     = AddUser();
                v2.OrderTotal = 35;
                v2.UserId     = v1.UserId;
                context.Set <WxOrder>().Add(v1);
                context.Set <WxOrder>().Add(v2);
                context.SaveChanges();
            }

            PartialViewResult rv = (PartialViewResult)_controller.BatchDelete(new string[] { v1.ID.ToString(), v2.ID.ToString() });

            Assert.IsInstanceOfType(rv.Model, typeof(WxOrderBatchVM));

            WxOrderBatchVM vm = rv.Model as WxOrderBatchVM;

            vm.Ids = new string[] { v1.ID.ToString(), v2.ID.ToString() };
            _controller.DoBatchDelete(vm, null);

            using (var context = new DataContext(_seed, DBTypeEnum.Memory))
            {
                Assert.AreEqual(context.Set <WxOrder>().Count(), 0);
            }
        }
        /// <summary>
        /// 取得最后一笔充值成功记录
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        public static UserBalance GetLastRecharge(CardInfoParam param)
        {
            RechargeFactory factory = new RechargeFactory();

            try
            {
                if (param == null)
                {
                    throw new Exception("Param is null");
                }
                UserBalance userBalance = new UserBalance();
                WxOrder     wxOrder     = factory.GetLastRecharge(param);
                //if (wxOrder == null) throw new Exception("DAL.WeChat.RechargeFactory.GetLastRecharge()==null");
                userBalance.lastOrder = wxOrder;
                return(userBalance);
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog(new Log()
                {
                    message = ex.Message
                }, "GetLastRecharge");
                throw ex;
            }
        }
        /// <summary>
        /// 创建支付订单
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        public int CreatePayOrder(WxOrder param)
        {
            int           result = 0;
            StringBuilder sb     = new StringBuilder();

            #region 微信支付
            if (param.total_fee > 0)
            {
                // 当前时间
                string dateTimeNow = DateTimeHelper.convertDateTime(DateTime.Now.ToString());

                #region Sql定义
                string strSql = " INSERT INTO WXORDER " +
                                " ( APPNAME " +
                                " , TYPE " +
                                " , CARDID " +
                                " , OUT_TRADE_NO " +
                                " , OPENID " +
                                " , ATTACH " +
                                " , TOTAL_FEE " +
                                " , TIME_START " +
                                " , TIME_EXPIRE " +
                                " , CREATETIME ) " +
                                " VALUES " +
                                " ( '{0}' " +
                                " , '{1}' " +
                                " , '{2}' " +
                                " , '{3}' " +
                                " , '{4}' " +
                                " , '{5}' " +
                                " , {6} " +
                                " , '{7}' " +
                                " , '{8}' " +
                                " , '{9}' ); ";
                #endregion

                sb.AppendFormat(strSql, param.appName, param.type, param.cardId, param.out_trade_no, param.openid, param.attach, param.total_fee,
                                param.time_start, param.time_expire, dateTimeNow);
            }
            #endregion

            sb.Append(CreateCouponOrder(param));
            result = SqlServerHelper.Execute(SqlServerHelper.salesorderConn(), sb.ToString());

            return(result);
        }
        public void DetailsTest()
        {
            WxOrder v = new WxOrder();

            using (var context = new DataContext(_seed, DBTypeEnum.Memory))
            {
                v.ID         = 16;
                v.OrderTotal = 12;
                v.UserId     = AddUser();
                context.Set <WxOrder>().Add(v);
                context.SaveChanges();
            }
            PartialViewResult rv = (PartialViewResult)_controller.Details(v.ID.ToString());

            Assert.IsInstanceOfType(rv.Model, typeof(IBaseCRUDVM <TopBasePoco>));
            Assert.AreEqual(v.ID, (rv.Model as IBaseCRUDVM <TopBasePoco>).Entity.GetID());
        }
        private string CreateCouponOrder(WxOrder param)
        {
            if (param.coupons == null)
            {
                return("");
            }

            // 当前时间
            string dateTimeNow = DateTimeHelper.convertDateTime(DateTime.Now.ToString());

            #region Sql定义
            string strSql = " INSERT INTO WXORDER " +
                            " ( APPNAME " +
                            " , TYPE " +
                            " , CARDID " +
                            " , OUT_TRADE_NO " +
                            " , OPENID " +
                            " , ATTACH " +
                            " , COUPONPRICE,COUPONQTY " +
                            " , TIME_START " +
                            " , TIME_EXPIRE " +
                            " , CREATETIME ) " +
                            " VALUES " +
                            " ( '{0}' " +
                            " , '{1}' " +
                            " , '{2}' " +
                            " , '{3}' " +
                            " , '{4}' " +
                            " , '{5}' " +
                            " , {6} " +
                            " , {7} " +
                            " , '{8}' " +
                            " , '{9}' ); ";
            #endregion

            strSql = string.Format(strSql, param.appName, param.type, param.cardId, param.out_trade_no,
                                   param.openid, param.attach, "{0},{1}",
                                   param.time_start, param.time_expire, dateTimeNow);
            StringBuilder sb = new StringBuilder();
            foreach (Coupon coupon in param.coupons)
            {
                sb.AppendFormat(strSql, coupon.price, coupon.qty);
            }

            return(sb.ToString());
        }
示例#8
0
        /// <summary>
        /// 取得最后一笔充值成功记录
        /// </summary>
        /// <param name="wechatId"></param>
        /// <returns></returns>
        public WxOrder GetLastRecharge(CardInfoParam param)
        {
            // 最后一笔成功充值信息
            string strSql = " SELECT TOP 1 " +
                            "   CAST(TOTAL_FEE * 1.0 / 100 AS DEC(10, 2)) AS TOTAL_FEE " +
                            " , TIME_END " +
                            " FROM WXORDER " +
                            " WHERE OPENID = '{0}' " +
                            " AND TRANSFERTIME IS NOT NULL " +
                            " ORDER BY ID DESC ";

            WxOrder lastOrder = SqlServerHelper.GetEntity <WxOrder>(SqlServerHelper.salesorderConn(), string.Format(strSql, param.wechatId));

            if (lastOrder != null)
            {
                lastOrder.time_end = DateTimeHelper.convertDateTime(lastOrder.time_end, "yyyyMMddHHmmss", "yyyy-MM-dd HH:mm:ss");
            }

            return(lastOrder);
        }
示例#9
0
 public static int UpdatePayOrder(WxOrder param)
 {
     try
     {
         if (param == null)
         {
             throw new Exception("WxOrder is null");
         }
         int result = wxf.UpdatePayOrder(param);
         return(result);
     }
     catch (Exception ex)
     {
         LogHelper.WriteLog(new Log()
         {
             message = ex.Message
         }, "UpdatePayOrder");
         return(-1);
     }
 }
示例#10
0
        /**
         * 生成直接支付url,支付url有效期为2小时,模式二
         * @param productId 商品ID
         * @return 模式二URL
         */
        public string GetPayUrl(string productId, WxOrder order)
        {
            LogManager.Log(this.GetType().ToStr(), "Native pay mode 2 url is producing...");

            WxPayData data = new WxPayData(_config.AppId);

            data.SetValue("body", order.Body);                                                    //商品描述
            data.SetValue("attach", order.Attach);                                                //附加数据
            data.SetValue("out_trade_no", order.OrderNum);                                        //随机字符串
            data.SetValue("total_fee", order.TotalFee);                                           //总金额
            data.SetValue("time_start", DateTime.Now.ToString("yyyyMMddHHmmss"));                 //交易起始时间
            data.SetValue("time_expire", DateTime.Now.AddMinutes(10).ToString("yyyyMMddHHmmss")); //交易结束时间
            data.SetValue("goods_tag", order.GoodsTag);                                           //商品标记
            data.SetValue("trade_type", "NATIVE");                                                //交易类型
            data.SetValue("product_id", productId);                                               //商品ID

            WxPayData result = WxPayApi.UnifiedOrder(data, _config.AppId);                        //调用统一下单接口
            string    url    = result.GetValue("code_url").ToString();                            //获得统一下单接口返回的二维码链接

            LogManager.Log(this.GetType().ToString(), "Get native pay mode 2 url : " + url);
            return(url);
        }
        public void EditTest()
        {
            WxOrder v = new WxOrder();

            using (var context = new DataContext(_seed, DBTypeEnum.Memory))
            {
                v.ID         = 16;
                v.OrderTotal = 12;
                v.UserId     = AddUser();
                context.Set <WxOrder>().Add(v);
                context.SaveChanges();
            }

            PartialViewResult rv = (PartialViewResult)_controller.Edit(v.ID.ToString());

            Assert.IsInstanceOfType(rv.Model, typeof(WxOrderVM));

            WxOrderVM vm = rv.Model as WxOrderVM;

            v    = new WxOrder();
            v.ID = vm.Entity.ID;

            v.OrderTotal = 35;
            vm.Entity    = v;
            vm.FC        = new Dictionary <string, object>();

            vm.FC.Add("Entity.ID", "");
            vm.FC.Add("Entity.OrderTotal", "");
            vm.FC.Add("Entity.UserId", "");
            _controller.Edit(vm);

            using (var context = new DataContext(_seed, DBTypeEnum.Memory))
            {
                var data = context.Set <WxOrder>().FirstOrDefault();

                Assert.AreEqual(data.OrderTotal, 35);
            }
        }
        public void CreateTest()
        {
            PartialViewResult rv = (PartialViewResult)_controller.Create();

            Assert.IsInstanceOfType(rv.Model, typeof(WxOrderVM));

            WxOrderVM vm = rv.Model as WxOrderVM;
            WxOrder   v  = new WxOrder();

            v.ID         = 16;
            v.OrderTotal = 12;
            v.UserId     = AddUser();
            vm.Entity    = v;
            _controller.Create(vm);

            using (var context = new DataContext(_seed, DBTypeEnum.Memory))
            {
                var data = context.Set <WxOrder>().FirstOrDefault();

                Assert.AreEqual(data.ID, 16);
                Assert.AreEqual(data.OrderTotal, 12);
            }
        }
示例#13
0
文件: JsApiPay.cs 项目: ntzw/WxHelper
        /**
         * 调用统一下单,获得下单结果
         * @return 统一下单结果
         * @失败时抛异常WxPayException
         */
        public WxPayData GetUnifiedOrderResult(WxOrder order)
        {
            //统一下单
            WxPayData data = new WxPayData(_appConfig.AppId);

            data.SetValue("body", order.Body);
            data.SetValue("attach", order.Attach);
            data.SetValue("out_trade_no", order.OrderNum);
            data.SetValue("total_fee", TotalFee);
            data.SetValue("time_start", DateTime.Now.ToString("yyyyMMddHHmmss"));
            data.SetValue("time_expire", DateTime.Now.AddMinutes(10).ToString("yyyyMMddHHmmss"));
            data.SetValue("goods_tag", order.GoodsTag);
            data.SetValue("trade_type", "JSAPI");
            data.SetValue("openid", Openid);

            WxPayData result = WxPayApi.UnifiedOrder(data, _appConfig.AppId);

            if (!result.IsSet("appid") || !result.IsSet("prepay_id") || result.GetValue("prepay_id").ToString() == "")
            {
                LogManager.Error(this.GetType().ToString(), "UnifiedOrder response error!");
                throw new WxPayException("UnifiedOrder response error!");
            }
            return(result);
        }
        public IHttpActionResult PayOrder([FromBody] PayOrderParam param)
        {
            SimpleResult result = new SimpleResult();
            IRecordsOfConsumptionService _service   = new RecordsOfConsumptionService();
            ICouponService      _couponService      = new CouponService();
            IUseWalletService   _useWalletService   = new UseWalletService();
            IStoreService       _stoeservice        = new StoreService();
            IProductInfoService _productInfoService = new ProductInfoService();

            try
            {
                if (UserAuthorization)
                {
                    LogHelper.WriteLog("PayOrder接口");
                    LogHelper.WriteLog("productCode  param.userCode" + param.paytype);
                    LogHelper.WriteLog("productCode param.money " + param.money);
                    LogHelper.WriteLog("productCode param.orderCode" + param.orderCode);
                    LogHelper.WriteLog("productCode param.peopleCount" + param.peopleCount);
                    LogHelper.WriteLog("productCode param.productCode" + param.productCode);
                    LogHelper.WriteLog("productCode param.storeId" + param.storeId);
                    LogHelper.WriteLog("productCode param.userCode " + param.userCode);
                    LogHelper.WriteLog("productCode param.couponCode " + param.couponCode);
                    var isExistProduct = _productInfoService.IsExistProduct(param.productCode);
                    if (!isExistProduct)
                    {
                        result.Status   = Result.SYSTEM_ERROR;
                        result.Msg      = "商品已失效或不存在";
                        result.Resource = null;
                    }
                    if (param.paytype == 0)
                    {
                        LogHelper.WriteLog("会员支付 " + param.paytype);

                        var isPay = true;
                        if (!string.IsNullOrEmpty(param.couponCode))
                        {
                            var n = _couponService.Exist(param.couponCode);
                            if (n == 1)
                            {
                                result.Status   = Result.SYSTEM_ERROR;
                                result.Msg      = "优惠卷不存在";
                                result.Resource = null;
                                isPay           = false;
                            }
                            else if (n == 2)
                            {
                                result.Status   = Result.SYSTEM_ERROR;
                                result.Msg      = "优惠卷已经被使用";
                                result.Resource = null;
                                isPay           = false;
                            }
                        }

                        if (isPay)
                        {
                            if (_useWalletService.ExistMoney(param.userCode, param.money))
                            {
                                var re = _service.PayOrder(param.productCode, param.userCode, param.peopleCount, param.dateTime, param.money, param.storeId, param.orderCode, param.couponCode);
                                result.Resource = "SUCCEED";
                                result.Status   = Result.SUCCEED;
                                LogHelper.WriteLog("result.Status " + Result.SUCCEED);
                            }
                            else
                            {
                                result.Status   = Result.SYSTEM_ERROR;
                                result.Msg      = "账号余额不足";
                                result.Resource = null;
                                LogHelper.WriteLog("result.Status " + Result.SYSTEM_ERROR);
                            }
                        }
                    }
                    else
                    {
                        var isPay = true;
                        if (!string.IsNullOrEmpty(param.couponCode))
                        {
                            var n = _couponService.Exist(param.couponCode);
                            if (n == 1)
                            {
                                result.Status   = Result.SYSTEM_ERROR;
                                result.Msg      = "优惠卷不存在";
                                result.Resource = null;
                                isPay           = false;
                            }
                            else if (n == 2)
                            {
                                result.Status   = Result.SYSTEM_ERROR;
                                result.Msg      = "优惠卷已经被使用";
                                result.Resource = null;
                                isPay           = false;
                            }
                        }
                        if (isPay)
                        {
                            using (var scope = new TransactionScope())//创建事务
                            {
                                LogHelper.WriteLog("微信支付 " + param.userCode);
                                IUserStoreService _userStoreservice = new UserStoreService();
                                var store        = _stoeservice.GetStore(param.storeId);
                                var couponser    = _couponService.GetCouponByCode(param.couponCode);
                                var userStoreser = _userStoreservice.GetUserStorebyUserCodestoreCode(param.userCode, param.storeId);
                                if (userStoreser != null)
                                {
                                    if (param.money != 0)
                                    {
                                        //生成微信预支付订单
                                        var wxprepay = Common.wxPayOrderSomething(userStoreser.OpenID, param.money.ToString(), couponser?.CouponTypeName, store);
                                        if (wxprepay != null)
                                        {
                                            var order = _service.WxPayOrder(param.productCode, param.userCode, param.peopleCount, param.dateTime, param.money, wxprepay.prepayid, param.storeId, param.orderCode, param.couponCode);
                                            if (!string.IsNullOrEmpty(param.couponCode))
                                            {
                                                _couponService.UsedUpdate(param.couponCode, param.userCode, order.OrderCode);
                                            }
                                            WxOrder wxorder = new WxOrder();
                                            wxorder.orderCode    = order.OrderCode;
                                            wxorder.wxJsApiParam = wxprepay.wxJsApiParam;
                                            wxorder.prepayid     = wxprepay.prepayid;
                                            wxorder.IsWxPay      = true;
                                            result.Resource      = wxorder;
                                            result.Status        = Result.SUCCEED;
                                        }
                                        else
                                        {
                                            result.Msg    = "微信下单失败,重新提交订单";
                                            result.Status = Result.SYSTEM_ERROR;
                                        }
                                    }
                                    else
                                    {
                                        var order = _service.WxPayNoMoneyOrder(param.productCode, param.userCode, param.peopleCount, param.dateTime, param.money, null, param.couponCode);
                                        _couponService.UsedUpdate(param.couponCode, param.userCode, order.OrderCode);
                                        LogHelper.WriteLog("更新的钱包和优惠券couponCode: " + param.couponCode);

                                        LogHelper.WriteLog("报表写入数据开始");
                                        IFinancialStatementsService _financialStatementsService = new FinancialStatementService();
                                        LogHelper.WriteLog("报表表数据更新");
                                        financialStatements fs = _financialStatementsService.getData(param.userCode, order, "微信");
                                        LogHelper.WriteLog("报表表数据更新完成");

                                        _financialStatementsService.Insert(fs);
                                        LogHelper.WriteLog("报表写入数据结束" + fs.Code);
                                        WxOrder wxorder = new WxOrder();
                                        wxorder.orderCode = order.OrderCode;
                                        result.Resource   = "SUCCEED";
                                        result.Status     = Result.SUCCEED;
                                    }
                                }
                                else
                                {
                                    result.Resource = "";
                                    result.Status   = Result.SYSTEM_ERROR;
                                }
                                scope.Complete();//这是最后提交事务
                            }
                        }
                    }
                }
                else
                {
                    result.Status   = ResultType;
                    result.Resource = ReAccessToken;
                    result.Msg      = TokenMessage;
                }
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog("WxPayOrder PayOrder ", ex);
                result.Status = Result.FAILURE;
                result.Msg    = ex.Message;

                LogHelper.WriteLog("微信支付", ex);
            }
            LogHelper.WriteLog("PayOrder result" + Json(result));
            return(Json(result));
        }
示例#15
0
        public IHttpActionResult  Recharge(string typeCode, string userCode, string storeCode, decimal?money = 0)
        {
            LogHelper.WriteLog("Recharge typeCode" + typeCode);
            LogHelper.WriteLog("Recharge userCode" + userCode);
            LogHelper.WriteLog("Recharge storeCode" + storeCode);
            LogHelper.WriteLog("Recharge money" + money);
            ICouponService         _couponService    = new CouponService();
            IUseWalletService      _useWalletService = new UseWalletService();
            IStoreService          _stoeservice      = new StoreService();
            SimpleResult           result            = new SimpleResult();
            IRechargeRecordService _service          = new RechargeRecordService();

            try
            {
                if (UserAuthorization)
                {
                    using (var scope = new TransactionScope())//创建事务
                    {
                        IUserStoreService    _userStoreservice = new UserStoreService();
                        IRechargeTypeService s   = new RechargeTypeService();
                        ITopupOrderServrce   tos = new TopupOrderServrce();
                        var store        = _stoeservice.GetStore(storeCode);
                        var userStoreser = _userStoreservice.GetUserStorebyUserCodestoreCode(userCode, storeCode);
                        if (userStoreser != null)
                        {//生成微信预支付订单
                            string  rechargeTypeName = "充值";
                            decimal?donationAmount   = 0;
                            if (typeCode == "0")
                            {
                                donationAmount = 0;
                            }
                            else
                            {
                                var type = s.GetRechargeTypeByCode(typeCode);
                                rechargeTypeName = type.RechargeTypeName;
                                donationAmount   = type?.DonationAmount;
                                money            = type?.Money;
                            }
                            var wxprepay = Common.wxPayOrderSomething(userStoreser.OpenID, money.ToString(), rechargeTypeName, store);
                            if (wxprepay != null)
                            {
                                //更新充值预订单
                                //给TopupOrder写数据
                                tos.InsertTopupOrder(userCode, wxprepay.prepayid, typeCode, money);

                                WxOrder wxorder = new WxOrder();
                                wxorder.orderCode    = null;
                                wxorder.wxJsApiParam = wxprepay.wxJsApiParam;
                                wxorder.prepayid     = wxprepay.prepayid;
                                result.Resource      = wxorder;
                                wxorder.IsWxPay      = true;
                                result.Status        = Result.SUCCEED;
                            }
                            else
                            {
                                result.Resource = "微信充值失败,重新充值";
                                result.Status   = Result.SYSTEM_ERROR;
                            }
                        }
                        scope.Complete();//这是最后提交事务
                    }
                }
                else
                {
                    result.Status   = ResultType;
                    result.Resource = ReAccessToken;
                    result.Msg      = TokenMessage;
                }
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog("wxPrePay typeCode" + typeCode + " userCode" + userCode + " storeCode" + storeCode + " money" + money, ex);
                result.Status = Result.FAILURE;
                result.Msg    = ex.Message;
            }
            LogHelper.WriteLog("Recharge result" + Json(result));
            return(Json(result));
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            //LogHelper.WriteLog(typeof(NativeNotifyPage), "可以运行1-1");

            String xmlData = getPostStr();//获取请求数据

            if (!string.IsNullOrWhiteSpace(xmlData))
            {
                #region Step1.先创建回执XML start
                var dic = new Dictionary <string, string>
                {
                    { "return_code", "SUCCESS" },
                    { "return_msg", "OK" }
                };
                var sb = new StringBuilder();
                sb.Append("<xml>");

                foreach (var d in dic)
                {
                    sb.Append("<" + d.Key + ">" + d.Value + "</" + d.Key + ">");
                }
                sb.Append("</xml>");
                #endregion

                /***将xml转换成实体类***/
                WxPayNotifyData wxData = WeChatPayHelper.GetWxPayNotifyData(xmlData);

                #region step2.检查XML是否合法
                if (WeChatPayHelper.CheckSign(xmlData, wxData.attch))
                {
                    // 创建回写订单的实体类
                    WxOrder order = new WxOrder();
                    // 取得PaymentCode长度
                    int          len = 0;
                    WeChatConfig wxc = WxMastDataHelper.GetWeChatConfig(wxData.attch);
                    if (wxc != null && !string.IsNullOrWhiteSpace(wxc.paymentCode))
                    {
                        len = wxc.paymentCode.Length;
                    }

                    order.appName        = wxData.attch;
                    order.out_trade_no   = wxData.out_trade_no.Substring(len, wxData.out_trade_no.Length - len);
                    order.transaction_id = wxData.transaction_id;
                    order.cash_fee       = wxData.cash_fee;
                    order.fee_type       = wxData.fee_type;
                    order.bank_type      = wxData.bank_type;
                    order.time_end       = wxData.time_end;
                    order.result_code    = wxData.result_code;
                    order.return_code    = wxData.return_code;

                    // 执行回写
                    if (WxOrderHelper.UpdatePayOrder(order) > 0)
                    {
                        // 调用数据导入Exe
                        this.DoExe();
                        // 回写成功时返回SUCCESS
                        return_result = sb.ToString();
                    }
                }
                #endregion
            }
            Response.Write(return_result);
            Response.End();
        }
        /// <summary>
        /// 创建预支付订单
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        public WeChatResult UnifiedOrder(WeChatInfo param)
        {
            WeChatResult wxResult = new WeChatResult();
            // 回调地址
            string notifyUrl = System.Web.Configuration.WebConfigurationManager.AppSettings["notifyUrl"].ToString();

            try
            {
                // 检查服务端是否处于调整中
                if (CheckServerMantain(param.costCenterCode))
                {
                    wxResult.isMantain = true;
                    return(wxResult);
                }

                // 检查充值金额和设置是否符合
                wxResult.matched = true;
                if (!CheckRechargeMatched(param))
                {
                    wxResult.matched = false;
                    return(wxResult);
                }

                string openid     = param.openId;
                string ordertime  = SalesOrder.Common.convertDateTime(DateTime.Now.ToString());
                bool   isTestUser = (new RechargeFactory()).GetUserInfo(openid).isTestUser;
                // 本地交易号前三位(用于在商户平台上区分支付场景,回调时手动去除不存数据库)
                string fcode = wcf.paymentCode;
                int    len   = fcode.Length;
                /***统一下单1***/
                WxPayData data = new WxPayData(wcf);
                data.SetValue("body", param.costCenterCode + "-餐卡充值");
                data.SetValue("attach", param.appName);
                data.SetValue("out_trade_no", fcode + WxPayApi.GenerateOutTradeNo(param.costCenterCode));
                //data.SetValue("total_fee", param.total_fee);
                data.SetValue("total_fee", isTestUser ? 1 : param.total_fee);
                data.SetValue("time_start", DateTime.Now.ToString("yyyyMMddHHmmss"));
                data.SetValue("time_expire", DateTime.Now.AddMinutes(5).ToString("yyyyMMddHHmmss"));
                //data.SetValue("goods_tag", "test");
                data.SetValue("trade_type", "JSAPI");
                data.SetValue("openid", openid);
                data.SetValue("notify_url", notifyUrl);

                WriteLog(data.ToJson().ToString());

                if (param.total_fee > 0)
                {
                    WxPayData result = WxPayApi.UnifiedOrder(wcf, data);

                    WriteLog(result.ToJson().ToString());

                    if (!result.IsSet("appid") || !result.IsSet("prepay_id") || result.GetValue("prepay_id").ToString() == "")
                    {
                        Log.Error(this.GetType().ToString(), "UnifiedOrder response error!");
                        throw new WxPayException("UnifiedOrder response error!");
                    }

                    wxResult.prepay_id = result.GetValue("prepay_id").ToString();
                    wxResult.paySign   = result.GetValue("sign").ToString();
                    wxResult.nonceStr  = result.GetValue("nonce_str").ToString();
                }
                /***订单写入本地***/
                string  st    = data.GetValue("out_trade_no").ToString();
                WxOrder order = new WxOrder
                {
                    appName      = param.appName,
                    type         = param.type,
                    cardId       = param.cardId,
                    out_trade_no = st.Substring(len, st.Length - len),
                    openid       = data.GetValue("openid").ToString(),
                    attach       = data.GetValue("attach").ToString(),
                    coupons      = param.coupons == null || !param.coupons.Any() ? null :
                                   param.coupons.SelectMany(q => q).Where(q => !string.IsNullOrWhiteSpace(q)).GroupBy(q => q)
                                   .Select(q => new Coupon
                    {
                        price = int.Parse(q.Key),
                        qty   = q.Count()
                    }).ToList(),
                    total_fee   = int.Parse(data.GetValue("total_fee").ToString()),
                    time_start  = data.GetValue("time_start").ToString(),
                    time_expire = data.GetValue("time_expire").ToString()
                };

                WxOrderFactory wof = new WxOrderFactory();

                /***本地没有写成功的话直接返回NULL***/
                if (wof.CreatePayOrder(order) <= 0)
                {
                    return(null);
                }

                return(wxResult);
            }
            catch (Exception e)
            {
                throw e;
            }
        }
示例#18
0
 /// <summary>微信扫码支付方式2
 /// </summary>
 /// <param name="productId"></param>
 /// <param name="order"></param>
 /// <returns></returns>
 public string GetPayUrl(string productId, WxOrder order)
 {
     return(new NativePay(_appConfig).GetPayUrl(productId, order));
 }
示例#19
0
        /// <summary>获取公众号支付JSON字符串
        /// </summary>
        /// <param name="openId">微信用户OpenId</param>
        /// <param name="order"></param>
        /// <returns></returns>
        public string GetJsApiParameters(string openId, WxOrder order)
        {
            JsApiPay jsApiPay = new JsApiPay(_context, _appConfig);

            return(jsApiPay.GetJsApiParameters(jsApiPay.GetUnifiedOrderResult(order)));
        }