Example #1
0
        /// <summary>
        /// 获取OrgCode
        /// </summary>
        /// <param name="websiteInfo"></param>
        /// <returns></returns>
        private string GetOrgCode(WebsiteInfo websiteInfo)
        {
            if (websiteInfo.IsUnionHongware == 1)
            {
                if (!string.IsNullOrEmpty(websiteInfo.OrgCode))
                {
                    return(websiteInfo.OrgCode);
                }
                else
                {
                    try
                    {
                        Open.HongWareSDK.Client client = new Open.HongWareSDK.Client(websiteInfo.WebsiteOwner);
                        var result = client.GetOrgCode();
                        if (result.isSuccess)
                        {
                            websiteInfo.OrgCode = result.orgCode.orgCode;
                            if (bll.Update(websiteInfo))
                            {
                                return(websiteInfo.OrgCode);
                            }
                        }
                    }
                    catch (Exception)
                    {
                    }

                    return("");
                }
            }
            return("");
        }
Example #2
0
        public void ProcessRequest(HttpContext context)
        {
            var websiteInfo = bllUser.GetWebsiteInfoModelFromDataBase();

            string ids = context.Request["ids"];

            if (string.IsNullOrEmpty(ids))
            {
                apiResp.msg  = "ids为必填参数,请检查";
                apiResp.code = (int)BLLJIMP.Enums.APIErrCode.IsNotFound;
                context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(apiResp));
                return;
            }
            string[] strIds = ids.Split(',');
            for (int i = 0; i < strIds.Length; i++)
            {
                UserInfo userModel = bllUser.GetUserInfoByAutoID(int.Parse(strIds[i]));
                if (websiteInfo.IsUnionHongware == 1)
                {
                    Open.HongWareSDK.Client hongWareClient = new Open.HongWareSDK.Client(websiteInfo.WebsiteOwner);
                    var memberInfo = hongWareClient.GetMemberInfo(userModel.WXOpenId);
                    if (memberInfo.member == null)
                    {
                        apiResp.msg = "宏巍会员不存在";
                        context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(apiResp));
                        return;
                    }
                    if (!hongWareClient.UpdateMemberScore(memberInfo.member.mobile, userModel.WXOpenId, -memberInfo.member.point))
                    {
                        apiResp.msg = "清空宏巍会员积分失败";
                        context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(apiResp));
                        return;
                    }
                }

                if (userModel.TotalScore == 0)
                {
                    continue;
                }
                double score = userModel.TotalScore;
                bllUser.Update(new UserInfo(), string.Format(" TotalScore=0"), string.Format("  AutoId={0} ", userModel.AutoID));

                UserScoreDetailsInfo scoreRecord = new UserScoreDetailsInfo();
                scoreRecord.UserID       = userModel.UserID;
                scoreRecord.AddTime      = DateTime.Now;
                scoreRecord.TotalScore   = 0;
                scoreRecord.Score        = -score;
                scoreRecord.ScoreType    = "AdminSubmit";
                scoreRecord.AddNote      = "积分清零";
                scoreRecord.RelationID   = bllUser.GetCurrUserID();
                scoreRecord.WebSiteOwner = bllUser.WebsiteOwner;
                bllUser.Add(scoreRecord);
            }
            apiResp.msg    = "操作完成";
            apiResp.status = true;
            context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(apiResp));
        }
Example #3
0
        public void ProcessRequest(HttpContext context)
        {
            string orderId = context.Request["order_id"];

            if (string.IsNullOrEmpty(orderId))
            {
                apiResp.code = 1;
                apiResp.msg  = "order_id 必传";
                bllMall.ContextResponse(context, apiResp);
                return;
            }
            var orderInfo = bllMall.GetOrderInfo(orderId);

            if (orderInfo == null)
            {
                apiResp.code = 1;
                apiResp.msg  = "order_id 不存在";
                bllMall.ContextResponse(context, apiResp);
                return;
            }
            if (orderInfo.PaymentStatus == 1)
            {
                apiResp.code = 1;
                apiResp.msg  = "订单已经支付";
                bllMall.ContextResponse(context, apiResp);
                return;
            }
            Open.HongWareSDK.Client cl = new Open.HongWareSDK.Client(bllMall.WebsiteOwner);
            string callBackUrl         = string.Format("http://{0}/customize/shop/?v=1.0&ngroute=/orderList#/orderDetail/{1}", context.Request.Url.Host, orderInfo.OrderID);

            callBackUrl = HttpUtility.UrlEncode(callBackUrl);
            string payUrl    = "";
            string errMsg    = "";
            bool   payResult = cl.OrderPay(orderInfo.OrderID, (orderInfo.TotalAmount * 100).ToString("F0"), callBackUrl, out payUrl, out errMsg);

            if (payResult && (!string.IsNullOrEmpty(payUrl)))
            {
                apiResp.status = true;
                apiResp.result = new
                {
                    pay_url = payUrl
                };
            }
            else
            {
                apiResp.msg = errMsg;
            }
            bllMall.ContextResponse(context, apiResp);
        }
Example #4
0
        /// <summary>
        /// 插入中奖记录
        /// </summary>
        /// <returns></returns>
        public bool AddWXLotteryRecordV1(WXLotteryRecordV1 model)
        {
            WebsiteInfo websiteInfo = GetWebsiteInfoModelFromDataBase();
            var         award       = model.WXAward;

            switch (award.AwardsType)
            {
            case 1:    //给用户增加积分
                var isSyncYike = new BLLJIMP.BLLCommRelation().ExistRelation(BLLJIMP.Enums.CommRelationType.SyncYike, WebsiteOwner, "");
                Open.EZRproSDK.Client zrClient = new Open.EZRproSDK.Client();
                if (isSyncYike)
                {
                    var resp = zrClient.BonusUpdate(GetCurrentUserInfo().Ex2, Convert.ToInt32(award.Value), "中奖加积分");
                }
                else if (websiteInfo.IsUnionHongware == 1)
                {
                    Open.HongWareSDK.Client hongWareClient = new Open.HongWareSDK.Client(GetCurrentUserInfo().WebsiteOwner);
                    var hongWareMemberInfo = hongWareClient.GetMemberInfo(GetCurrentUserInfo().WXOpenId);
                    if (hongWareMemberInfo.member != null)
                    {
                        hongWareClient.UpdateMemberScore(hongWareMemberInfo.member.mobile, GetCurrentUserInfo().WXOpenId, float.Parse(award.Value));
                    }
                }
                //else
                //{
                string tempMsg = "";
                new BLLUser().AddUserScoreDetail(GetCurrUserID(), CommonPlatform.Helper.EnumStringHelper.ToString(Enums.ScoreDefineType.Lottery), WebsiteOwner
                                                 , out tempMsg, Convert.ToInt32(award.Value), "中奖加积分", "", false);
                //}
                break;

            case 2:    //给用户增加优惠券

                new BLLCardCoupon().SendCardCoupon(int.Parse(model.WXAward.Value), model.UserId);

                break;

            default:
                break;
            }


            return(Add(model));
        }
Example #5
0
        /// <summary>
        /// 获取当前用户信息
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        private string currentuserinfo(HttpContext context)
        {
            try
            {
                currentUserInfo = bllUser.GetUserInfo(bllUser.GetCurrUserID(), bllUser.WebsiteOwner);
                var websiteInfo = bllUser.GetWebsiteInfoModelFromDataBase();
                Open.HongWareSDK.Client hongWareClient = new Open.HongWareSDK.Client(websiteInfo.WebsiteOwner);
                //double totalScore =CurrentUserInfo.TotalScore;
                #region 使用yike积分
                if (bllCommRelation.ExistRelation(BLLJIMP.Enums.CommRelationType.SyncYike, bllCommRelation.WebsiteOwner, ""))
                {
                    if ((!string.IsNullOrEmpty(currentUserInfo.Ex2)) && (!string.IsNullOrEmpty(currentUserInfo.Phone)))
                    {
                        Open.EZRproSDK.Entity.BonusGetResp yikeUser = yiKeClient.GetBonus(currentUserInfo.Ex1, currentUserInfo.Ex2, currentUserInfo.Phone);
                        if (yikeUser != null)
                        {
                            currentUserInfo.TotalScore = yikeUser.Bonus;
                        }
                        else
                        {
                            currentUserInfo.TotalScore = 0;
                        }
                    }
                }
                #endregion

                #region 使用宏巍积分余额
                if (websiteInfo.IsUnionHongware == 1)
                {
                    var hongWareMemberInfo = hongWareClient.GetMemberInfo(currentUserInfo.WXOpenId);
                    if (hongWareMemberInfo.member != null)
                    {
                        currentUserInfo.TotalScore    = Convert.ToInt32(hongWareMemberInfo.member.point);
                        currentUserInfo.AccountAmount = (decimal)hongWareMemberInfo.member.balance;
                    }
                    else
                    {
                        currentUserInfo.TotalScore    = 0;
                        currentUserInfo.AccountAmount = 0;
                    }
                }
                #endregion


                //var carOwnerInfo = bllUserEx.GetCurrUserCarOwnerInfo();
                //var bankcard = bllUser.Get<BindBankCard>(string.Format("UserId='{0}'", currentUserInfo.UserID));

                var hasidentitycardphoto = !string.IsNullOrWhiteSpace(currentUserInfo.IdentityCardPhotoFront + currentUserInfo.IdentityCardPhotoBehind + currentUserInfo.IdentityCardPhotoHandheld);
                var hasbusinessintelligencecertificatephoto = !string.IsNullOrWhiteSpace(currentUserInfo.BusinessIntelligenceCertificatePhoto1 + currentUserInfo.BusinessIntelligenceCertificatePhoto2
                                                                                         + currentUserInfo.BusinessIntelligenceCertificatePhoto3 + currentUserInfo.BusinessIntelligenceCertificatePhoto4 + currentUserInfo.BusinessIntelligenceCertificatePhoto5);
                var hasinvoicinginformation = bllUserEx.ExistUserExpand(UserExpandType.InvoicingInformation, currentUserInfo.UserID);

                var data = new
                {
                    id                 = currentUserInfo.AutoID,
                    userid             = currentUserInfo.UserID,
                    head_img_url       = bllUser.GetUserDispalyAvatar(currentUserInfo), //GetHeadImgUrl(context,CurrentUserInfo),
                    nickname           = bllUser.GetUserDispalyName(currentUserInfo),   //CurrentUserInfo.WXNickname,
                    wx_nickname        = currentUserInfo.WXNickname,
                    phone              = currentUserInfo.Phone,
                    username           = currentUserInfo.UserID,
                    unionid            = currentUserInfo.WXUnionID,
                    totalscore         = currentUserInfo.TotalScore,
                    history_totalscore = currentUserInfo.HistoryTotalScore,
                    company_name       = currentUserInfo.Company,
                    position           = currentUserInfo.Postion,
                    email              = currentUserInfo.Email,
                    truename           = currentUserInfo.TrueName,
                    ex1                = currentUserInfo.Ex1,
                    ex2                = currentUserInfo.Ex2,
                    ex3                = currentUserInfo.Ex3,
                    ex4                = currentUserInfo.Ex4,
                    ex5                = currentUserInfo.Ex5,
                    wxOpenId           = currentUserInfo.WXOpenId,
                    //carServerType = CurrentUserInfo.CarServerType,
                    //carOwnerInfo = carOwnerInfo == null ? null : new
                    //{

                    //    carModel = carOwnerInfo.CarModel == null ? null : new
                    //    {
                    //        carModelId = carOwnerInfo.CarModel.CarModelId,
                    //        carBrandId = carOwnerInfo.CarModel.CarBrandId,
                    //        carBrandName = bllCar.GetBrand(carOwnerInfo.CarModel.CarBrandId).CarBrandName,
                    //        carSeriesCateId = carOwnerInfo.CarModel.CarSeriesCateId,
                    //        carSeriesId = carOwnerInfo.CarModel.CarSeriesId,
                    //        carSeriesName = bllCar.GetSeriesInfo(carOwnerInfo.CarModel.CarSeriesId).CarSeriesName,
                    //        carModelName = carOwnerInfo.CarModel.CarModelName,
                    //        showName = carOwnerInfo.CarModel.ShowName,
                    //        allName = carOwnerInfo.CarModel.AllName,
                    //        year = carOwnerInfo.CarModel.Year,
                    //        img = carOwnerInfo.CarModel.Img,
                    //        guidePrice = carOwnerInfo.CarModel.GuidePrice,
                    //        colors = string.IsNullOrWhiteSpace(carOwnerInfo.CarModel.Colors) ? null : JsonConvert.DeserializeObject<List<BLLJIMP.Model.CarModelColorInfo>>(carOwnerInfo.CarModel.Colors).Select(c => new { name = c.Name, value = c.Value })
                    //    },
                    //    carNumber = carOwnerInfo.CarNumber,
                    //    carNumberTime = carOwnerInfo.CarNumberTime == null ? "" : carOwnerInfo.CarNumberTime.Value.ToString("yyyy-MM-dd HH:mm"),
                    //    drivingLicenseTime = carOwnerInfo.DrivingLicenseTime == null ? "" : carOwnerInfo.DrivingLicenseTime.Value.ToString("yyyy-MM-dd HH:mm"),
                    //    drivingLicenseType = carOwnerInfo.DrivingLicenseType,
                    //    vin = carOwnerInfo.VIN
                    //},
                    address        = currentUserInfo.Address,
                    imgs           = currentUserInfo.Images,
                    province       = currentUserInfo.Province,
                    province_code  = currentUserInfo.ProvinceCode,
                    city           = currentUserInfo.City,
                    city_code      = currentUserInfo.CityCode,
                    district       = currentUserInfo.District,
                    district_code  = currentUserInfo.DistrictCode,
                    identification = currentUserInfo.Ex5,
                    salary         = currentUserInfo.Salary,
                    birthday       = DateTimeHelper.DateTimeToUnixTimestamp(currentUserInfo.Birthday),
                    birthday_str   = DateTimeHelper.DateTimeToString(currentUserInfo.Birthday),
                    gender         = currentUserInfo.Gender,
                    sex            = currentUserInfo.WXSex.HasValue ? currentUserInfo.WXSex.Value : 0,
                    member_level   = currentUserInfo.MemberLevel,
                    hasqrcode      = bllUser.IsDistributionMember(currentUserInfo),
                    describe       = currentUserInfo.Description,
                    avatar         = currentUserInfo.Avatar,
                    credit_acount  = currentUserInfo.CreditAcount,
                    //hasbankcard = bankcard == null ? false : true,
                    hasidentitycardphoto                     = hasidentitycardphoto,
                    identity_card_photo_front                = currentUserInfo.IdentityCardPhotoFront,
                    identity_card_photo_behind               = currentUserInfo.IdentityCardPhotoBehind,
                    identity_card_photo_handheld             = currentUserInfo.IdentityCardPhotoHandheld,
                    hasbusinessintelligencecertificatephoto  = hasbusinessintelligencecertificatephoto,
                    intelligence_certificate_business        = currentUserInfo.IntelligenceCertificateBusiness,
                    business_intelligence_certificate_photo1 = currentUserInfo.BusinessIntelligenceCertificatePhoto1,
                    business_intelligence_certificate_photo2 = currentUserInfo.BusinessIntelligenceCertificatePhoto2,
                    business_intelligence_certificate_photo3 = currentUserInfo.BusinessIntelligenceCertificatePhoto3,
                    business_intelligence_certificate_photo4 = currentUserInfo.BusinessIntelligenceCertificatePhoto4,
                    business_intelligence_certificate_photo5 = currentUserInfo.BusinessIntelligenceCertificatePhoto5,
                    hasinvoicinginformation                  = hasinvoicinginformation,
                    websiteowner       = bllUser.WebsiteOwner,
                    account_amount     = currentUserInfo.AccountAmount,                        //账户余额
                    is_bind_hongware   = bllUser.IsBindHongWare(currentUserInfo, websiteInfo), //是否已经绑定宏巍
                    memberattribution  = currentUserInfo.MemberAttribution,
                    distribution_owner = currentUserInfo.DistributionOwner
                                         //is_attention_weixin = bllWeiXin.IsWeixinFollower(bllWeiXin.GetAccessToken(), CurrentUserInfo.WXOpenId)
                };
                return(ZentCloud.Common.JSONHelper.ObjectToJson(data));
            }
            catch (Exception ex)
            {
                return(ex.ToString());
            }
        }
Example #6
0
        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                //Tolog("进入支付回调");
                XmlDocument xmlDoc = new XmlDocument();
                xmlDoc.Load(Request.InputStream);
                xmlDoc.Save(string.Format("C:\\WXPay\\Notify{0}.xml", DateTime.Now.ToString("yyyyMMddHHmmssfff")));//写入日志
                //全部参数
                Dictionary <string, string> parametersAll = new Dictionary <string, string>();
                foreach (XmlElement item in xmlDoc.DocumentElement.ChildNodes)
                {
                    string key   = item.Name;
                    string value = item.InnerText;
                    if ((!string.IsNullOrEmpty(key)) && (!string.IsNullOrEmpty(value)))
                    {
                        parametersAll.Add(key, value);
                    }
                }
                parametersAll = (from entry in parametersAll
                                 orderby entry.Key ascending
                                 select entry).ToDictionary(pair => pair.Key, pair => pair.Value);//全部参数排序
                orderInfo = bllMall.GetOrderInfo(parametersAll["out_trade_no"]);
                PayConfig payConfig = bllPay.GetPayConfig();
                if (!bllPay.VerifySignatureWx(parametersAll, payConfig.WXPartnerKey))//验证签名
                {
                    Tolog("验证签名出错");
                    Response.Write(failXml);
                    return;
                }
                if (orderInfo == null)
                {
                    Tolog("订单未找到");
                    Response.Write(failXml);
                    return;
                }
                if (orderInfo.PaymentStatus.Equals(1))
                {
                    //Tolog("已支付");
                    Response.Write(successXml);
                    return;
                }
                orderInfo.PaymentType = 2;

                //更新订单状态
                WXMallProductInfo tProductInfo = new WXMallProductInfo();
                if (parametersAll["return_code"].Equals("SUCCESS") && parametersAll["result_code"].Equals("SUCCESS")) //交易成功
                {
                    UserInfo orderUserInfo = bllUser.GetUserInfo(orderInfo.OrderUserID, bllUser.WebsiteOwner);        //下单用户信息
                    string   hasOrderIDs   = "";
                    int      maxCount      = 1;
                    //Tolog("准备检查更新订单状态");
                    if (BLLJIMP.BLLMall.bookingList.Contains(orderInfo.ArticleCategoryType))
                    {
                        //Tolog("预订类型");
                        #region 预约订单修改状态
                        orderInfo.PaymentStatus = 1;
                        orderInfo.PayTime       = DateTime.Now;
                        orderInfo.Status        = "预约成功";

                        #region 检查是否有预约成功的订单
                        List <WXMallOrderDetailsInfo> tDetailList = bllMall.GetOrderDetailsList(orderInfo.OrderID, null, orderInfo.ArticleCategoryType, null, null);
                        List <WXMallOrderDetailsInfo> oDetailList = bllMall.GetOrderDetailsList(null, tDetailList[0].PID, orderInfo.ArticleCategoryType, tDetailList.Min(p => p.StartDate), tDetailList.Max(p => p.EndDate));
                        tProductInfo = bllMall.GetByKey <WXMallProductInfo>("PID", tDetailList[0].PID);
                        maxCount     = tProductInfo.Stock;
                        List <string> hasOrderIDList = new List <string>();
                        foreach (var item in tDetailList)
                        {
                            List <WXMallOrderDetailsInfo> hasOrderDetailList = oDetailList.Where(p => !((item.StartDate >= p.EndDate && item.EndDate > p.EndDate) || (item.StartDate < p.StartDate && item.EndDate <= p.StartDate))).ToList();
                            if (hasOrderDetailList.Count >= maxCount)
                            {
                                hasOrderIDList.AddRange(hasOrderDetailList.Select(p => p.OrderID).Distinct());
                            }
                        }
                        hasOrderIDList = hasOrderIDList.Where(p => !p.Contains(orderInfo.OrderID)).ToList();
                        if (hasOrderIDList.Count > 0)
                        {
                            hasOrderIDList = hasOrderIDList.Distinct().ToList();
                            hasOrderIDs    = MyStringHelper.ListToStr(hasOrderIDList, "'", ",");
                        }
                        #endregion 检查是否有预约成功的订单

                        #endregion 预约订单修改状态
                    }
                    else
                    {
                        //Tolog("普通类型");
                        #region 原订单修改状态
                        orderInfo.PaymentStatus = 1;
                        orderInfo.Status        = "待发货";
                        orderInfo.PayTime       = DateTime.Now;
                        if (orderInfo.DeliveryType == 1)
                        {
                            orderInfo.Status = "待自提";
                        }
                        Tolog("更改状态start");
                        //if (bllMall.GetWebsiteInfoModelFromDataBase().IsDistributionMall.Equals(1))
                        //{
                        orderInfo.GroupBuyStatus     = "0";
                        orderInfo.DistributionStatus = 1;

                        //if (orderInfo.IsMain==1)
                        //{
                        //    bllMall.Update(orderInfo,string.Format(" DistributionStatus=1"),string.Format("ParentOrderId='{0}'",orderInfo.OrderID));
                        //}



                        #region 活动订单
                        if (orderInfo.OrderType == 4)
                        {
                            ActivityDataInfo data = bllMall.Get <ActivityDataInfo>(string.Format(" OrderId='{0}'", orderInfo.OrderID));
                            if (data != null)
                            {
                                bllMall.Update(data, string.Format(" PaymentStatus=1"), string.Format("  OrderId='{0}'", orderInfo.OrderID));
                            }
                        }
                        #endregion


                        bllMall.Update(orderInfo, string.Format("PaymentStatus=1,Status='待发货',PayTime=GETDATE(),DistributionStatus=1"), string.Format("ParentOrderId='{0}'", orderInfo.OrderID));


                        //}
                        #endregion 原订单修改状态

                        try
                        {
                            //设置交易流水号
                            orderInfo.PayTranNo = parametersAll["transaction_id"];
                        }
                        catch (Exception ex)
                        {
                            Tolog("设置交易流水号失败:" + ex.Message);
                        }
                    }
                    bool result = false;

                    if (BLLJIMP.BLLMall.bookingList.Contains(orderInfo.ArticleCategoryType))
                    {
                        if (string.IsNullOrWhiteSpace(hasOrderIDs))
                        {
                            hasOrderIDs = "'0'";
                        }
                        result = bllMall.Update(new WXMallOrderInfo(),
                                                string.Format("PaymentStatus={0},PayTime=GetDate(),Status='{1}'", 1, "预约成功"),
                                                string.Format("OrderID='{0}' and WebsiteOwner='{4}' AND (select count(1) from [ZCJ_WXMallOrderInfo] where Status='{3}' and WebsiteOwner='{4}' and  OrderID IN({1}))<{2}",
                                                              orderInfo.OrderID, hasOrderIDs, maxCount, "预约成功", bllMall.WebsiteOwner)
                                                ) > 0;
                        if (result)
                        {
                            // #region 交易成功加积分
                            //增加积分 (慧聚不需要)
                            //if (orderInfo.TotalAmount > 0)
                            //{
                            //    ScoreConfig scoreConfig = bllScore.GetScoreConfig();
                            //    int addScore = 0;
                            //    if (scoreConfig != null && scoreConfig.OrderAmount > 0 && scoreConfig.OrderScore > 0)
                            //    {
                            //        addScore = (int)(orderInfo.PayableAmount / (scoreConfig.OrderAmount / scoreConfig.OrderScore));
                            //    }
                            //    if (addScore > 0)
                            //    {
                            //        if (bllUser.Update(new UserInfo(),
                            //            string.Format(" TotalScore+={0},HistoryTotalScore+={0}", addScore),
                            //            string.Format(" UserID='{0}'", orderInfo.OrderUserID)) > 0)
                            //        {
                            //            UserScoreDetailsInfo scoreRecord = new UserScoreDetailsInfo();
                            //            scoreRecord.AddTime = DateTime.Now;
                            //            scoreRecord.Score = addScore;
                            //            scoreRecord.ScoreType = "OrderSuccess";
                            //            scoreRecord.UserID = orderInfo.OrderUserID;
                            //            scoreRecord.AddNote = "预约-交易成功获得积分";
                            //            bllMall.Add(scoreRecord);
                            //        }
                            //    }
                            //}
                            // #endregion

                            #region 修改其他预约订单为预约失败 返还积分

                            if (BLLJIMP.BLLMall.bookingList.Contains(orderInfo.ArticleCategoryType) && !string.IsNullOrWhiteSpace(hasOrderIDs))
                            {
                                int tempCount = 0;
                                List <WXMallOrderInfo> tempList = bllMall.GetOrderList(0, 1, "", out tempCount, "预约成功", null, null, null,
                                                                                       null, null, null, null, null, null, null, orderInfo.ArticleCategoryType, hasOrderIDs);
                                tempCount = tempCount + 1; //加上当前订单的数量
                                if (tempCount >= maxCount)
                                {
                                    tempList = bllMall.GetColOrderListInStatus("'待付款','待审核'", hasOrderIDs, "OrderID,OrderUserID,UseScore", bllMall.WebsiteOwner);
                                    if (tempList.Count > 0)
                                    {
                                        string stopOrderIds = MyStringHelper.ListToStr(tempList.Select(p => p.OrderID).ToList(), "'", ",");
                                        tempList = tempList.Where(p => p.UseScore > 0).ToList();
                                        foreach (var item in tempList)
                                        {
                                            orderUserInfo.TotalScore += item.UseScore;
                                            if (bllUser.Update(new UserInfo(), string.Format(" TotalScore+={0}", item.UseScore),
                                                               string.Format(" UserID='{0}'", item.OrderUserID)) > 0)
                                            {
                                                UserScoreDetailsInfo scoreRecord = new UserScoreDetailsInfo();
                                                scoreRecord.AddTime      = DateTime.Now;
                                                scoreRecord.Score        = item.UseScore;
                                                scoreRecord.TotalScore   = orderUserInfo.TotalScore;
                                                scoreRecord.ScoreType    = "OrderCancel";
                                                scoreRecord.UserID       = item.OrderUserID;
                                                scoreRecord.RelationID   = item.OrderID;
                                                scoreRecord.AddNote      = "预约-订单失败返还积分";
                                                scoreRecord.WebSiteOwner = item.WebsiteOwner;
                                                bllMall.Add(scoreRecord);
                                            }
                                        }
                                        bllMall.Update(new WXMallOrderInfo(),
                                                       string.Format("Status='{0}'", "预约失败"),
                                                       string.Format("OrderID In ({0}) and WebsiteOwner='{1}'", stopOrderIds, bllMall.WebsiteOwner));
                                    }
                                }
                                //Tolog("更改修改其他预约为预约失败");
                            }
                            #endregion
                        }
                    }
                    else
                    {
                        result = bllMall.Update(orderInfo);
                    }
                    if (result)
                    {
                        #region 拼团订单
                        if (orderInfo.OrderType == 2)
                        {
                            try
                            {
                                if (!string.IsNullOrEmpty(orderInfo.GroupBuyParentOrderId))
                                {
                                    var parentOrderInfo = bllMall.GetOrderInfo(orderInfo.GroupBuyParentOrderId);

                                    if (parentOrderInfo.Ex10 == "1")
                                    {
                                        if (bllMall.GetCount <WXMallOrderInfo>(string.Format("PaymentStatus=1 And GroupBuyParentOrderId='{0}' ", parentOrderInfo.OrderID)) >= parentOrderInfo.PeopleCount)
                                        {
                                            bllMall.Update(new WXMallOrderInfo(), string.Format("Status='已取消'"), string.Format("  GroupBuyParentOrderId='{0}' And PaymentStatus=0", parentOrderInfo.OrderID));
                                            parentOrderInfo.GroupBuyStatus = "1";
                                            bllMall.Update(parentOrderInfo);
                                        }
                                    }
                                    else
                                    {
                                        if (bllMall.GetCount <WXMallOrderInfo>(string.Format("PaymentStatus=1 And GroupBuyParentOrderId='{0}' Or OrderId='{0}'", parentOrderInfo.OrderID)) >= parentOrderInfo.PeopleCount)
                                        {
                                            bllMall.Update(new WXMallOrderInfo(), string.Format("Status='已取消'"), string.Format("  GroupBuyParentOrderId='{0}' And PaymentStatus=0", parentOrderInfo.OrderID));
                                            parentOrderInfo.GroupBuyStatus = "1";
                                            bllMall.Update(parentOrderInfo);
                                        }
                                    }
                                }
                            }
                            catch (Exception)
                            {
                            }
                        }
                        #endregion
                        Open.HongWareSDK.Client hongWareClient = new Open.HongWareSDK.Client(orderInfo.WebsiteOwner);

                        //Tolog("更改状态true");

                        #region Efast同步
                        //判读当前站点是否需要同步到驿氪和efast
                        if (bllCommRelation.ExistRelation(BLLJIMP.Enums.CommRelationType.SyncEfast, bllCommRelation.WebsiteOwner, ""))
                        {
                            try
                            {
                                Tolog("开始同步efast");

                                string outOrderId = string.Empty, msg = string.Empty;
                                var    syncResult = bllEfast.CreateOrder(orderInfo.OrderID, out outOrderId, out msg);
                                if (syncResult)
                                {
                                    orderInfo.OutOrderId = outOrderId;
                                    bllMall.Update(orderInfo);
                                }
                                Tolog(string.Format("efast订单同步结果:{0},订单号:{1},提示信息:{2}", syncResult, outOrderId, msg));
                            }
                            catch (Exception ex)
                            {
                                Tolog("efast订单同步异常:" + ex.Message);
                            }
                        }
                        #endregion

                        #region 驿氪同步
                        if (bllCommRelation.ExistRelation(BLLJIMP.Enums.CommRelationType.SyncYike, bllCommRelation.WebsiteOwner, ""))
                        {
                            try
                            {
                                Tolog("开始同步驿氪");
                                //同步成功订单到驿氪

                                //UserInfo orderUserInfo = bllUser.GetUserInfo(orderInfo.OrderUserID);
                                //if ((!string.IsNullOrEmpty(orderUserInfo.Ex1)) && (!string.IsNullOrEmpty(orderUserInfo.Ex2)) && (!string.IsNullOrEmpty(orderUserInfo.Phone)))
                                //{
                                //    client.BonusUpdate(orderUserInfo.Ex2, -(orderInfo.UseScore), "商城下单使用积分" + orderInfo.UseScore);

                                //}
                                var uploadOrderResult = yikeClient.OrderUpload(orderInfo);

                                Tolog(string.Format("驿氪订单同步结果:{0}", Common.JSONHelper.ObjectToJson(uploadOrderResult)));
                            }
                            catch (Exception ex)
                            {
                                Tolog("驿氪订单同步异常:" + ex.Message);
                            }
                        }
                        #endregion

                        #region 付款加积分
                        try
                        {
                            bllUser.AddUserScoreDetail(orderInfo.OrderUserID, CommonPlatform.Helper.EnumStringHelper.ToString(ZentCloud.BLLJIMP.Enums.ScoreDefineType.OrderPay), bllMall.WebsiteOwner, null, null);
                        }
                        catch (Exception)
                        { }

                        #endregion


                        #region 消息通知
                        if (!BLLJIMP.BLLMall.bookingList.Contains(orderInfo.ArticleCategoryType))
                        {
                            try
                            {
                                var    productName = bllMall.GetOrderDetailsList(orderInfo.OrderID)[0].ProductName;
                                string remark      = "";
                                if (!string.IsNullOrEmpty(orderInfo.OrderMemo))
                                {
                                    remark = string.Format("客户留言:{0}", orderInfo.OrderMemo);
                                }
                                bllWeiXin.SendTemplateMessageToKefu("有新的订单", string.Format("订单号:{0}\\n订单金额:{1}元\\n收货人:{2}\\n电话:{3}\\n商品:{4}\\n{5}", orderInfo.OrderID, Math.Round(orderInfo.TotalAmount, 2), orderInfo.Consignee, orderInfo.Phone, productName, remark));
                                if (orderInfo.OrderType != 4)//付费的活动不发消息
                                {
                                    if (orderInfo.WebsiteOwner != "jikuwifi")
                                    {
                                        string url = string.Format("http://{0}/customize/shop/?v=1.0&ngroute=/orderDetail/{1}#/orderDetail/{1}", Request.Url.Host, orderInfo.OrderID);
                                        if (orderInfo.IsMain == 1)
                                        {
                                            url = string.Format("http://{0}/customize/shop/?v=1.0&ngroute=/orderList#/orderList", Request.Url.Host);
                                        }
                                        bllWeiXin.SendTemplateMessageNotifyComm(orderUserInfo, "订单已成功支付,我们将尽快发货,请保持手机畅通等待物流送达!", string.Format("订单号:{0}\\n订单金额:{1}元\\n收货人:{2}\\n电话:{3}\\n商品:{4}...\\n查看详情", orderInfo.OrderID, Math.Round(orderInfo.TotalAmount, 2), orderInfo.Consignee, orderInfo.Phone, productName), url);
                                    }
                                }
                            }
                            catch (Exception)
                            {
                            }
                        }
                        else
                        {
                            try
                            {
                                bllWeiXin.SendTemplateMessageToKefu(orderInfo.Status, string.Format("预约:{2}\\n订单号:{0}\\n订单金额:{1}元\\n预约人:{3}\\n预约人手机:{4}", orderInfo.OrderID, orderInfo.TotalAmount, tProductInfo.PName, orderUserInfo.TrueName, orderUserInfo.Phone));
                                bllWeiXin.SendTemplateMessageNotifyComm(orderUserInfo, orderInfo.Status, string.Format("预约:{2}\\n订单号:{0}\\n订单金额:{1}元", orderInfo.OrderID, orderInfo.TotalAmount, tProductInfo.PName));
                            }
                            catch (Exception)
                            {
                            }
                        }
                        #endregion
                        WebsiteInfo websiteInfo = bllMall.Get <WebsiteInfo>(string.Format(" WebsiteOwner='{0}'", orderInfo.WebsiteOwner));
                        #region 分销相关
                        try
                        {
                            if (bllMenuPermission.CheckUserAndPmsKey(websiteInfo.WebsiteOwner, BLLPermission.Enums.PermissionSysKey.OnlineDistribution, websiteInfo.WebsiteOwner))
                            {
                                if (string.IsNullOrWhiteSpace(orderUserInfo.DistributionOwner))
                                {
                                    if (websiteInfo.DistributionRelationBuildMallOrder == 1)
                                    {
                                        orderUserInfo.DistributionOwner = orderInfo.WebsiteOwner;
                                        bllMall.Update(orderUserInfo);
                                    }
                                }
                                bllDis.AutoUpdateLevel(orderInfo);
                                bllDis.TransfersEstimate(orderInfo);
                                bllDis.SendMessageToUser(orderInfo);
                                bllDis.UpdateDistributionSaleAmountUp(orderInfo);
                            }
                        }
                        catch (Exception ex)
                        {
                            Tolog("设置分销员异常:" + ex.Message + " 用户id:" + orderUserInfo.UserID);
                        }
                        #endregion


                        #region 宏巍通知
                        try
                        {
                            if (websiteInfo.IsUnionHongware == 1)
                            {
                                hongWareClient.OrderNotice(orderUserInfo.WXOpenId, orderInfo.OrderID);
                            }
                        }
                        catch (Exception)
                        {
                        }

                        #endregion

                        bllCard.Give(orderInfo.TotalAmount, orderUserInfo);


                        string v1ProductId = Common.ConfigHelper.GetConfigString("YGBV1ProductId");
                        string v2ProductId = Common.ConfigHelper.GetConfigString("YGBV2ProductId");
                        string v1CouponId  = Common.ConfigHelper.GetConfigString("YGBV1CouponId");
                        string v2CouponId  = Common.ConfigHelper.GetConfigString("YGBV2CouponId");

                        List <WXMallOrderDetailsInfo> orderDetailList = bllMall.GetOrderDetailsList(orderInfo.OrderID);
                        foreach (var item in orderDetailList)
                        {
                            item.IsComplete = 1;
                            bllMall.Update(item);

                            #region 购买指定商品发送指定的优惠券
                            if (!string.IsNullOrEmpty(v1ProductId) && !string.IsNullOrEmpty(v1CouponId) && item.PID == v1ProductId)
                            {
                                bllCard.SendCardCouponsByCurrUserInfo(orderUserInfo, v1CouponId);
                            }

                            if (!string.IsNullOrEmpty(v2ProductId) && !string.IsNullOrEmpty(v2CouponId) && item.PID == v2ProductId)
                            {
                                bllCard.SendCardCouponsByCurrUserInfo(orderUserInfo, v2CouponId);
                            }
                            #endregion
                        }

                        //更新销量
                        bllMall.UpdateProductSaleCount(orderInfo);
                        Response.Write(successXml);
                        return;
                    }
                    else
                    {
                        Tolog("更改状态false");
                        Response.Write(failXml);
                        return;
                    }
                }
                Tolog("返回信息有误");
                Response.Write(failXml);
            }
            catch (Exception ex)
            {
                Tolog("出错了:" + ex.Message);
                Response.Write(failXml);
            }
        }
Example #7
0
        public void ProcessRequest(HttpContext context)
        {
            WebsiteInfo websiteInfo = bllMall.GetWebsiteInfoModelFromDataBase();

            Open.HongWareSDK.Client     hongWareClient        = new Open.HongWareSDK.Client(websiteInfo.WebsiteOwner);
            Open.HongWareSDK.MemberInfo hongWeiWareMemberInfo = null;
            if (websiteInfo.IsUnionHongware == 1)
            {
                hongWeiWareMemberInfo = hongWareClient.GetMemberInfo(CurrentUserInfo.WXOpenId);
                if (hongWeiWareMemberInfo.member == null)
                {
                    apiResp.code = (int)APIErrCode.OperateFail;
                    apiResp.msg  = "您尚未绑定宏巍账号,请先绑定";
                    context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(apiResp));
                    return;
                }
            }
            string data = context.Request["data"];

            if (string.IsNullOrEmpty(data))
            {
                apiResp.code = (int)APIErrCode.OperateFail;
                apiResp.msg  = "data 参数必传";
                context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(apiResp));
                return;
            }
            decimal    productFee = 0;    //商品总价格 不包含邮费
            OrderModel orderRequestModel; //订单模型

            try
            {
                orderRequestModel = ZentCloud.Common.JSONHelper.JsonToModel <OrderModel>(data);
            }
            catch (Exception ex)
            {
                apiResp.code = (int)APIErrCode.OperateFail;
                apiResp.msg  = "JSON格式错误,请检查。错误信息:" + ex.Message;
                context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(apiResp));
                return;
            }
            if (string.IsNullOrEmpty(orderRequestModel.order_id))
            {
                apiResp.code = (int)APIErrCode.OperateFail;
                apiResp.msg  = "order_id 必传";
                context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(apiResp));
                return;
            }



            WXMallOrderInfo parentOrderInfo = bllMall.GetOrderInfo(orderRequestModel.order_id);//父订单

            if (parentOrderInfo == null)
            {
                apiResp.code = (int)APIErrCode.OperateFail;
                apiResp.msg  = "订单不存在";
                context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(apiResp));
                return;
            }
            if (parentOrderInfo.OrderUserID == CurrentUserInfo.UserID)
            {
                apiResp.code = (int)APIErrCode.OperateFail;
                apiResp.msg  = "团长不可以参加";
                context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(apiResp));
                return;
            }
            if (parentOrderInfo.OrderType != 2)
            {
                apiResp.code = (int)APIErrCode.OperateFail;
                apiResp.msg  = "不是拼团订单";
                context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(apiResp));
                return;
            }
            if (!string.IsNullOrEmpty(parentOrderInfo.GroupBuyParentOrderId))
            {
                apiResp.code = (int)APIErrCode.OperateFail;
                apiResp.msg  = "订单无效";
                context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(apiResp));
                return;
            }
            if (parentOrderInfo.PaymentStatus == 0)
            {
                apiResp.code = (int)APIErrCode.OperateFail;
                apiResp.msg  = "团长订单未付款";
                context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(apiResp));
                return;
            }
            if (bllMall.GetCount <WXMallOrderInfo>(string.Format("PaymentStatus=1 And GroupBuyParentOrderId='{0}' Or OrderId='{0}'", parentOrderInfo.OrderID)) >= parentOrderInfo.PeopleCount)
            {
                apiResp.code = (int)APIErrCode.OperateFail;
                apiResp.msg  = "团购人数已满";
                context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(apiResp));
                return;
            }
            if (bllMall.GetCount <WXMallOrderInfo>(string.Format("GroupBuyParentOrderId='{0}' And OrderUserId='{1}' And PaymentStatus=0", parentOrderInfo.OrderID, CurrentUserInfo.UserID)) > 0)
            {
                apiResp.code = (int)APIErrCode.OperateFail;
                apiResp.msg  = "您还有未支付的订单,请先支付";
                context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(apiResp));
                return;
            }
            if (DateTime.Now >= (((DateTime)parentOrderInfo.PayTime).AddDays(parentOrderInfo.ExpireDay)))
            {
                parentOrderInfo.GroupBuyStatus = "2";
                bllMall.Update(parentOrderInfo);
                apiResp.code = (int)APIErrCode.OperateFail;
                apiResp.msg  = "拼团已过期";
                context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(apiResp));
                return;
            }

            #region 分销关系建立
            if (websiteInfo.DistributionRelationBuildMallOrder == 1)
            {
                UserInfo orderUserInfo = bllUser.GetUserInfo(parentOrderInfo.OrderUserID, parentOrderInfo.WebsiteOwner);
                if (bllUser.IsDistributionMember(orderUserInfo))
                {
                    if (string.IsNullOrEmpty(CurrentUserInfo.DistributionOwner))
                    {
                        var setUserDistributionOwnerResult = bllDis.SetUserDistributionOwner(CurrentUserInfo.UserID, orderUserInfo.UserID, CurrentUserInfo.WebsiteOwner);
                        if (setUserDistributionOwnerResult)
                        {
                            CurrentUserInfo.DistributionOwner = orderUserInfo.UserID;
                            CurrentUserInfo.Channel           = orderUserInfo.Channel;
                        }
                    }
                }
            }
            #endregion


            WXMallOrderInfo orderInfo = new WXMallOrderInfo();//订单表
            orderInfo.Address       = orderRequestModel.receiver_address;
            orderInfo.Consignee     = orderRequestModel.receiver_name;
            orderInfo.InsertDate    = DateTime.Now;
            orderInfo.OrderUserID   = CurrentUserInfo.UserID;
            orderInfo.Phone         = orderRequestModel.receiver_phone;
            orderInfo.WebsiteOwner  = bllMall.WebsiteOwner;
            orderInfo.Transport_Fee = 0;
            orderInfo.OrderID       = bllMall.GetGUID(BLLJIMP.TransacType.AddMallOrder);
            if (bllMall.WebsiteOwner != "mixblu")
            {
                orderInfo.OutOrderId = orderInfo.OrderID;
            }
            orderInfo.OrderMemo            = orderRequestModel.buyer_memo;
            orderInfo.ReceiverProvince     = orderRequestModel.receiver_province;
            orderInfo.ReceiverProvinceCode = orderRequestModel.receiver_province_code.ToString();
            orderInfo.ReceiverCity         = orderRequestModel.receiver_city;
            orderInfo.ReceiverCityCode     = orderRequestModel.receiver_city_code.ToString();
            orderInfo.ReceiverDist         = orderRequestModel.receiver_dist;
            orderInfo.ReceiverDistCode     = orderRequestModel.receiver_dist_code.ToString();
            orderInfo.ZipCode               = orderRequestModel.receiver_zip;
            orderInfo.Status                = "待付款";
            orderInfo.OrderType             = 2;
            orderInfo.GroupBuyParentOrderId = parentOrderInfo.OrderID;
            orderInfo.MyCouponCardId        = orderRequestModel.cardcoupon_id.ToString();
            orderInfo.UseScore              = orderRequestModel.use_score;
            orderInfo.UseAmount             = orderRequestModel.use_amount;
            orderInfo.LastUpdateTime        = DateTime.Now;

            if (orderRequestModel.pay_type == "WEIXIN")//微信支付
            {
                orderInfo.PaymentType = 2;
            }
            else if (orderRequestModel.pay_type == "ALIPAY")//支付宝支付
            {
                orderInfo.PaymentType = 1;
            }

            #region 格式检查

            if (string.IsNullOrEmpty(orderInfo.Consignee))
            {
                apiResp.code = (int)APIErrCode.OperateFail;
                apiResp.msg  = "收货人姓名不能为空";
                context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(apiResp));
                return;
            }
            if (string.IsNullOrEmpty(orderInfo.Phone))
            {
                apiResp.code = (int)APIErrCode.OperateFail;
                apiResp.msg  = "收货人联系电话不能为空";
                context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(apiResp));
                return;
            }
            if (string.IsNullOrEmpty(orderInfo.ReceiverProvince))
            {
                apiResp.code = (int)APIErrCode.OperateFail;
                apiResp.msg  = "省份名称不能为空";
                context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(apiResp));
                return;
            }
            if (string.IsNullOrEmpty(orderInfo.ReceiverProvinceCode))
            {
                apiResp.code = (int)APIErrCode.OperateFail;
                apiResp.msg  = "省份代码不能为空";
                context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(apiResp));
                return;
            }
            if (string.IsNullOrEmpty(orderInfo.ReceiverCity))
            {
                apiResp.code = (int)APIErrCode.OperateFail;
                apiResp.msg  = "城市名称不能为空";
                context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(apiResp));
                return;
            }
            if (string.IsNullOrEmpty(orderInfo.ReceiverCityCode))
            {
                apiResp.code = (int)APIErrCode.OperateFail;
                apiResp.msg  = "城市代码不能为空";
                context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(apiResp));
                return;
            }
            if (string.IsNullOrEmpty(orderInfo.ReceiverDist))
            {
                apiResp.code = (int)APIErrCode.OperateFail;
                apiResp.msg  = "城市区域名称不能为空";
                context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(apiResp));
                return;
            }
            if (string.IsNullOrEmpty(orderInfo.ReceiverCityCode))
            {
                apiResp.code = (int)APIErrCode.OperateFail;
                apiResp.msg  = "城市区域代码不能为空";
                context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(apiResp));
                return;
            }
            if (string.IsNullOrEmpty(orderInfo.Address))
            {
                apiResp.code = (int)APIErrCode.OperateFail;
                apiResp.msg  = "收货地址不能为空";
                context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(apiResp));
                return;
            }



            //相关检查
            #endregion


            #region 商品检查 订单详情生成


            var     needUseScore = 0; //必须使用的积分
            decimal needUseCash  = 0; //必须使用的现金

            var parentOrderDetailList = bllMall.GetOrderDetailsList(parentOrderInfo.OrderID);

            //先检查库存
            ProductSku productSku = bllMall.GetProductSku((int)parentOrderDetailList[0].SkuId);
            if (productSku == null)
            {
                apiResp.code = (int)APIErrCode.OperateFail;
                apiResp.msg  = "SKU不存在";
                context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(apiResp));
                return;
            }

            WXMallProductInfo productInfo    = bllMall.GetProduct(productSku.ProductId.ToString());
            string            cardCouponType = "";//优惠券类型

            #region 检查优惠券是否可用
            if (orderRequestModel.cardcoupon_id > 0)
            {
                var mycardCoupon = bllCardCoupon.GetMyCardCoupon(orderRequestModel.cardcoupon_id, CurrentUserInfo.UserID);
                if (mycardCoupon == null)
                {
                    apiResp.code = (int)APIErrCode.OperateFail;
                    apiResp.msg  = "无效的优惠券";
                    context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(apiResp));
                    return;
                }
                var cardCoupon = bllCardCoupon.GetCardCoupon(mycardCoupon.CardId);
                if (cardCoupon == null)
                {
                    apiResp.code = (int)APIErrCode.OperateFail;
                    apiResp.msg  = "无效的优惠券";
                    context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(apiResp));
                    return;
                }
                cardCouponType = cardCoupon.CardCouponType;
                #region 需要购买指定商品
                if ((!string.IsNullOrEmpty(cardCoupon.Ex2)) && (cardCoupon.Ex2 != "0"))
                {
                    if (productInfo.PID != cardCoupon.Ex2)
                    {
                        var productInfoCard = bllMall.GetProduct(cardCoupon.Ex2);
                        apiResp.code = (int)APIErrCode.OperateFail;
                        apiResp.msg  = string.Format("此优惠券需要购买{0}时才可以使用", productInfoCard.PName);
                        context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(apiResp));
                        return;
                    }
                }
                #endregion

                #region 需要购买指定标签商品
                if (!string.IsNullOrEmpty(cardCoupon.Ex8))
                {
                    if (string.IsNullOrEmpty(productInfo.Tags))//全部商品都没有标签
                    {
                        apiResp.code = (int)APIErrCode.OperateFail;
                        apiResp.msg  = string.Format("使用此优惠券需要购买标签为{0}的商品", cardCoupon.Ex8);
                        context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(apiResp));
                        return;
                    }
                    bool checkResult = true;

                    if (!string.IsNullOrEmpty(productInfo.Tags))
                    {
                        bool tempResult = false;
                        foreach (string tag in productInfo.Tags.Split(','))
                        {
                            if (cardCoupon.Ex8.Contains(tag))
                            {
                                tempResult = true;
                                break;
                            }
                        }
                        if (!tempResult)
                        {
                            checkResult = false;
                        }
                    }
                    else//商品不包含标签
                    {
                        checkResult = false;
                    }
                    if (!checkResult)
                    {
                        apiResp.code = (int)APIErrCode.OperateFail;
                        apiResp.msg  = string.Format("使用此优惠券需要购买标签为{0}的商品", cardCoupon.Ex8);
                        context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(apiResp));
                        return;
                    }
                }
                #endregion
            }
            #endregion


            if (productInfo.IsOnSale == "0")
            {
                apiResp.code = (int)APIErrCode.OperateFail;
                apiResp.msg  = string.Format("{0}已下架", productInfo.PName);
                context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(apiResp));
                return;
            }
            if (productSku.Stock < 1)
            {
                apiResp.code = (int)APIErrCode.OperateFail;
                apiResp.msg  = string.Format("{0}{1}库存余量为{2},库存不足", productInfo.PName, bllMall.GetProductShowProperties(productSku.SkuId), productSku.Stock);
                context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(apiResp));
                return;
            }

            if (productInfo.Score > 0)//必须使用的积分
            {
                needUseScore = productInfo.Score;
            }
            if (productInfo.IsCashPayOnly == 1)                                                                            //必须使用的现金
            {
                needUseCash = Math.Round((decimal)(productSku.Price * (decimal)(parentOrderInfo.MemberDiscount / 10)), 2); //四舍五入
            }

            WXMallOrderDetailsInfo detailModel = new WXMallOrderDetailsInfo();
            detailModel.OrderID     = orderInfo.OrderID;
            detailModel.PID         = productInfo.PID;
            detailModel.TotalCount  = 1;
            detailModel.OrderPrice  = Math.Round((decimal)(productSku.Price * (decimal)(parentOrderInfo.MemberDiscount / 10)), 2);//四舍五入
            detailModel.ProductName = productInfo.PName;
            detailModel.SkuId       = productSku.SkuId;
            detailModel.SkuShowProp = bllMall.GetProductShowProperties(productSku.SkuId);
            detailModel.IsComplete  = 1;//拼团的只要下单就算销量


            #endregion
            #region 纯积分购买
            if (needUseScore > 0)
            {
                if ((CurrentUserInfo.TotalScore < needUseScore) || (orderRequestModel.use_score < needUseScore))
                {
                    apiResp.code = (int)APIErrCode.OperateFail;
                    apiResp.msg  = string.Format("您需要使用{0}积分来兑换, 可用积分不足", needUseScore);
                    context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(apiResp));
                    return;
                }
            }
            #endregion



            productFee = (decimal)detailModel.OrderPrice;
            //物流费用
            #region 运费计算

            List <SkuModel> skus = new List <SkuModel>();
            skus.Add(new SkuModel
            {
                sku_id = productSku.SkuId,
                count  = 1
            });
            FreightModel freightModel = new FreightModel();
            freightModel.receiver_province_code = orderRequestModel.receiver_province_code;
            freightModel.receiver_city_code     = orderRequestModel.receiver_city_code;
            freightModel.receiver_dist_code     = orderRequestModel.receiver_dist_code;
            freightModel.skus = skus;
            decimal freight    = 0;//运费
            string  freightMsg = "";
            if (!bllMall.CalcFreight(freightModel, out freight, out freightMsg))
            {
                apiResp.code = (int)APIErrCode.OperateFail;
                apiResp.msg  = freightMsg;
                context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(apiResp)); return;
            }
            orderInfo.Transport_Fee = freight;
            #endregion

            #region 优惠券计算

            decimal discountAmount   = 0;//优惠金额
            bool    canUseCardCoupon = false;
            string  msg = "";
            if (orderRequestModel.cardcoupon_id > 0)//有优惠券
            {
                discountAmount = bllMall.CalcDiscountAmount(orderRequestModel.cardcoupon_id.ToString(), data, CurrentUserInfo.UserID, out canUseCardCoupon, out msg);
                if (!canUseCardCoupon)
                {
                    apiResp.code = (int)APIErrCode.OperateFail;
                    apiResp.msg  = msg;
                    context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(apiResp));
                    return;
                }
                if (cardCouponType == "MallCardCoupon_FreeFreight")//免邮券
                {
                    orderInfo.Transport_Fee = 0;
                }
            }
            //优惠券计算
            #endregion


            #region 积分计算
            decimal scoreExchangeAmount = 0;///积分抵扣的金额
            //积分计算
            if (orderRequestModel.use_score > 0)
            {
                #region 使用宏巍积分
                if (websiteInfo.IsUnionHongware == 1)
                {
                    CurrentUserInfo.TotalScore = hongWeiWareMemberInfo.member.point;
                }
                #endregion
                orderInfo.UseScore = orderRequestModel.use_score;
                if (CurrentUserInfo.TotalScore < orderRequestModel.use_score)
                {
                    apiResp.code = (int)APIErrCode.OperateFail;
                    apiResp.msg  = "积分不足";
                    context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(apiResp)); return;
                }

                ScoreConfig scoreConfig = bllScore.GetScoreConfig();
                if (scoreConfig != null && scoreConfig.ExchangeAmount > 0)
                {
                    scoreExchangeAmount = Math.Round(orderRequestModel.use_score / (scoreConfig.ExchangeScore / scoreConfig.ExchangeAmount), 2);
                }
                //scoreExchangeAmount = Math.Round(orderRequestModel.use_score / (scoreConfig.ExchangeScore / scoreConfig.ExchangeAmount), 2);
            }



            //积分计算
            #endregion

            #region 使用账户余额
            if (orderRequestModel.use_amount > 0)
            {
                if (!bllMall.IsEnableAccountAmountPay())
                {
                    apiResp.msg = "尚未启用余额支付功能";
                    context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(apiResp));
                    return;
                }
                #region 使用宏巍余额
                if (websiteInfo.IsUnionHongware == 1)
                {
                    CurrentUserInfo.AccountAmount = (decimal)hongWeiWareMemberInfo.member.balance;
                }
                #endregion
                if (CurrentUserInfo.AccountAmount < orderRequestModel.use_amount)
                {
                    apiResp.code = (int)APIErrCode.OperateFail;
                    apiResp.msg  = "您的账户余额不足";
                    context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(apiResp));
                    return;
                }
            }
            #endregion

            //合计计算
            orderInfo.Product_Fee   = productFee;
            orderInfo.TotalAmount   = orderInfo.Product_Fee + orderInfo.Transport_Fee;
            orderInfo.TotalAmount  -= discountAmount;                  //优惠券优惠金额
            orderInfo.TotalAmount  -= scoreExchangeAmount;             //积分优惠金额
            orderInfo.TotalAmount  -= orderRequestModel.use_amount;    //余额
            orderInfo.PayableAmount = orderInfo.TotalAmount - freight; //应付金额

            orderInfo.HeadDiscount          = parentOrderInfo.HeadDiscount;
            orderInfo.MemberDiscount        = parentOrderInfo.MemberDiscount;
            orderInfo.PeopleCount           = parentOrderInfo.PeopleCount;
            orderInfo.ExpireDay             = parentOrderInfo.ExpireDay;
            orderInfo.GroupBuyParentOrderId = parentOrderInfo.OrderID;

            orderInfo.ScoreExchangAmount  = scoreExchangeAmount; //优惠券抵扣金额
            orderInfo.CardcouponDisAmount = discountAmount;      //卡券抵扣金额

            if (orderInfo.TotalAmount <= 0)
            {
                orderInfo.TotalAmount   = 0;
                orderInfo.PaymentStatus = 1;
                orderInfo.PayTime       = DateTime.Now;
                orderInfo.Status        = "待发货";
            }
            if (orderInfo.TotalAmount < needUseCash)
            {
                apiResp.code = (int)APIErrCode.OperateFail;
                apiResp.msg  = string.Format("最少需要支付{0}元" + needUseCash);
                context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(apiResp));
                return;
            }
            ZentCloud.ZCBLLEngine.BLLTransaction tran = new ZCBLLEngine.BLLTransaction();
            try
            {
                if (!this.bllMall.Add(orderInfo, tran))
                {
                    tran.Rollback();
                    apiResp.code = (int)APIErrCode.OperateFail;
                    apiResp.msg  = "提交失败";
                    context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(apiResp));
                    return;
                }

                #region 更新优惠券使用状态
                //优惠券
                if (orderRequestModel.cardcoupon_id > 0 && (canUseCardCoupon == true))//有优惠券且已经成功使用
                {
                    MyCardCoupons myCardCoupon = bllCardCoupon.GetMyCardCoupon(orderRequestModel.cardcoupon_id, CurrentUserInfo.UserID);
                    myCardCoupon.UseDate = DateTime.Now;
                    myCardCoupon.Status  = 1;
                    if (!bllCardCoupon.Update(myCardCoupon, tran))
                    {
                        tran.Rollback();
                        apiResp.code = (int)APIErrCode.OperateFail;
                        apiResp.msg  = "更新优惠券状态失败";
                        context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(apiResp));
                        return;
                    }
                }
                //优惠券
                #endregion

                #region 积分抵扣
                //积分扣除
                if (orderRequestModel.use_score > 0)
                {
                    CurrentUserInfo.TotalScore -= orderRequestModel.use_score;
                    if (bllMall.Update(CurrentUserInfo, string.Format(" TotalScore-={0}", orderRequestModel.use_score), string.Format(" AutoID={0}", CurrentUserInfo.AutoID), tran) < 0)
                    {
                        tran.Rollback();
                        apiResp.code = (int)APIErrCode.OperateFail;
                        apiResp.msg  = "更新用户积分失败";
                        context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(apiResp));
                        return;
                    }

                    //积分记录
                    UserScoreDetailsInfo scoreRecord = new UserScoreDetailsInfo();
                    scoreRecord.AddTime      = DateTime.Now;
                    scoreRecord.Score        = -orderRequestModel.use_score;
                    scoreRecord.TotalScore   = CurrentUserInfo.TotalScore;
                    scoreRecord.ScoreType    = "OrderSubmit";
                    scoreRecord.UserID       = CurrentUserInfo.UserID;
                    scoreRecord.AddNote      = "微商城-参加团购使用积分";
                    scoreRecord.WebSiteOwner = CurrentUserInfo.WebsiteOwner;
                    if (!bllMall.Add(scoreRecord, tran))
                    {
                        tran.Rollback();
                        apiResp.code = (int)APIErrCode.OperateFail;
                        apiResp.msg  = "插入积分记录失败";
                        context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(apiResp));
                        return;
                    }
                    #region 更新宏巍积分
                    if (websiteInfo.IsUnionHongware == 1)
                    {
                        if (!hongWareClient.UpdateMemberScore(hongWeiWareMemberInfo.member.mobile, CurrentUserInfo.WXOpenId, -orderRequestModel.use_score))
                        {
                            tran.Rollback();
                            apiResp.code = (int)APIErrCode.OperateFail;
                            apiResp.msg  = "更新宏巍积分失败";
                            context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(apiResp));
                            return;
                        }
                    }
                    #endregion
                }

                //积分扣除
                #endregion

                #region 余额抵扣

                if (orderRequestModel.use_amount > 0 && bllMall.IsEnableAccountAmountPay())
                {
                    CurrentUserInfo.AccountAmount -= orderRequestModel.use_amount;
                    if (bllMall.Update(CurrentUserInfo, string.Format(" AccountAmount={0}", CurrentUserInfo.AccountAmount), string.Format(" AutoID={0}", CurrentUserInfo.AutoID)) < 0)
                    {
                        tran.Rollback();
                        apiResp.code = (int)APIErrCode.OperateFail;
                        apiResp.msg  = "更新用户余额失败";
                        context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(apiResp));
                        return;
                    }


                    UserScoreDetailsInfo scoreRecord = new UserScoreDetailsInfo();
                    scoreRecord.AddTime      = DateTime.Now;
                    scoreRecord.Score        = -(double)orderRequestModel.use_amount;
                    scoreRecord.TotalScore   = (double)CurrentUserInfo.AccountAmount;
                    scoreRecord.UserID       = CurrentUserInfo.UserID;
                    scoreRecord.AddNote      = "拼团-参团使用余额";
                    scoreRecord.RelationID   = orderInfo.OrderID;
                    scoreRecord.WebSiteOwner = bllUser.WebsiteOwner;
                    scoreRecord.ScoreType    = "AccountAmount";
                    if (!bllMall.Add(scoreRecord))
                    {
                        tran.Rollback();
                        apiResp.code = (int)APIErrCode.OperateFail;
                        apiResp.msg  = "插入余额记录失败";
                        context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(apiResp));
                        return;
                    }

                    UserCreditAcountDetails record = new UserCreditAcountDetails();
                    record.WebsiteOwner = bllUser.WebsiteOwner;
                    record.Operator     = CurrentUserInfo.UserID;
                    record.UserID       = CurrentUserInfo.UserID;
                    record.CreditAcount = -orderRequestModel.use_amount;
                    record.SysType      = "AccountAmount";
                    record.AddTime      = DateTime.Now;
                    record.AddNote      = "账户余额变动-" + orderRequestModel.use_amount;
                    if (!bllMall.Add(record))
                    {
                        tran.Rollback();
                        apiResp.code = (int)APIErrCode.OperateFail;
                        apiResp.msg  = "插入余额记录失败";
                        context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(apiResp));
                        return;
                    }
                    #region 更新宏巍余额
                    if (websiteInfo.IsUnionHongware == 1)
                    {
                        if (!hongWareClient.UpdateMemberBlance(hongWeiWareMemberInfo.member.mobile, CurrentUserInfo.WXOpenId, -(float)orderRequestModel.use_amount))
                        {
                            tran.Rollback();
                            apiResp.code = (int)APIErrCode.OperateFail;
                            apiResp.msg  = "更新宏巍余额失败";
                            context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(resp));
                            return;
                        }
                    }
                    #endregion
                }


                #endregion

                #region 插入订单详情表及更新库存

                if (!this.bllMall.Add(detailModel, tran))
                {
                    tran.Rollback();
                    apiResp.code = (int)APIErrCode.OperateFail;
                    apiResp.msg  = "提交失败";
                    context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(apiResp));
                    return;
                }
                //更新 SKU库存
                System.Text.StringBuilder sbUpdateStock = new StringBuilder();//更新库存sql
                sbUpdateStock.AppendFormat(" Update ZCJ_ProductSku Set Stock-={0} ", 1);
                sbUpdateStock.AppendFormat(" Where SkuId={0} And Stock>0 ", productSku.SkuId);
                if (ZentCloud.ZCBLLEngine.BLLBase.ExecuteSql(sbUpdateStock.ToString(), tran) <= 0)
                {
                    tran.Rollback();
                    apiResp.code = (int)APIErrCode.OperateFail;
                    apiResp.msg  = "提交订单失败,库存不足";
                    context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(apiResp));
                    return;
                }

                #endregion

                tran.Commit();//提交订单事务
                #region 宏巍通知
                if (websiteInfo.IsUnionHongware == 1)
                {
                    hongWareClient.OrderNotice(CurrentUserInfo.WXOpenId, orderInfo.OrderID);
                }
                #endregion
                try
                {
                    //团购完成取消其它未付款订单
                    if (parentOrderInfo.Ex10 == "1")
                    {
                        if (bllMall.GetCount <WXMallOrderInfo>(string.Format("PaymentStatus=1 And  (GroupBuyParentOrderId='{0}')", parentOrderInfo.OrderID)) >= parentOrderInfo.PeopleCount)
                        {
                            bllMall.Update(new WXMallOrderInfo(), string.Format("Status='已取消'"), string.Format("  GroupBuyParentOrderId='{0}' And PaymentStatus=0", parentOrderInfo.OrderID));
                            parentOrderInfo.GroupBuyStatus = "1";
                            bllMall.Update(parentOrderInfo);
                        }
                    }
                    else
                    {
                        if (bllMall.GetCount <WXMallOrderInfo>(string.Format("PaymentStatus=1 And  (GroupBuyParentOrderId='{0}' Or OrderId='{0}')", parentOrderInfo.OrderID)) >= parentOrderInfo.PeopleCount)
                        {
                            bllMall.Update(new WXMallOrderInfo(), string.Format("Status='已取消'"), string.Format("  GroupBuyParentOrderId='{0}' And PaymentStatus=0", parentOrderInfo.OrderID));
                            parentOrderInfo.GroupBuyStatus = "1";
                            bllMall.Update(parentOrderInfo);
                        }
                    }

                    #region 微信模板消息
                    string title = "订单已成功提交";
                    if (orderInfo.TotalAmount > 0)
                    {
                        title += ",请尽快付款";
                    }
                    bllWeiXin.SendTemplateMessageNotifyComm(CurrentUserInfo, title, string.Format("订单号:{0}\\n订单金额:{1}元\\n收货人:{2}\\n电话:{3}", orderInfo.OrderID, orderInfo.TotalAmount, orderInfo.Consignee, orderInfo.Phone));
                    #endregion
                }
                catch
                {
                }
            }
            catch (Exception ex)
            {
                //回滚事物
                tran.Rollback();
                apiResp.code = (int)APIErrCode.OperateFail;
                apiResp.msg  = "提交订单失败";
                context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(apiResp));
                return;
            }
            apiResp.status = true;
            apiResp.msg    = "ok";
            apiResp.result = new
            {
                order_id = orderInfo.OrderID
            };
            context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(apiResp));
        }
Example #8
0
        /// <summary>
        /// 冻结积分结算
        /// </summary>
        /// <param name="orderInfo"></param>
        /// <returns></returns>
        public bool SettlementOrderLockScore(WXMallOrderInfo orderInfo, out string msg)
        {
            BLLMall bllMall = new BLLMall();
            BLLWebsiteDomainInfo bllWebsiteDomain = new BLLWebsiteDomainInfo();
            BLLWeixin            bllWeixin        = new BLLWeixin();

            msg = "";
            var lockModel = GetLockScoreByOrder(orderInfo.OrderID);

            int addScore = (int)lockModel.Score;

            if (addScore > 0)
            {
                UserInfo orderUserInfo = bllUser.GetUserInfo(orderInfo.OrderUserID, orderInfo.WebsiteOwner);
                if (orderUserInfo == null)
                {
                    return(false);
                }
                WebsiteInfo websiteInfo = bllMall.Get <WebsiteInfo>(string.Format(" WebsiteOwner='{0}'", orderInfo.WebsiteOwner));

                ZentCloud.ZCBLLEngine.BLLTransaction tran = new ZentCloud.ZCBLLEngine.BLLTransaction();
                try
                {
                    UserScoreDetailsInfo scoreRecord = new UserScoreDetailsInfo();
                    scoreRecord.AddTime      = DateTime.Now;
                    scoreRecord.Score        = addScore;
                    scoreRecord.TotalScore   = orderUserInfo.TotalScore;
                    scoreRecord.ScoreType    = "OrderSuccess";
                    scoreRecord.UserID       = orderInfo.OrderUserID;
                    scoreRecord.AddNote      = "微商城-交易成功获得积分";
                    scoreRecord.WebSiteOwner = orderInfo.WebsiteOwner;
                    scoreRecord.RelationID   = orderInfo.OrderID;

                    if (!bllMall.Add(scoreRecord, tran))
                    {
                        tran.Rollback();
                        return(false);
                    }
                    if (bllUser.Update(orderUserInfo, string.Format(" TotalScore+={0},HistoryTotalScore+={0}", addScore), string.Format(" AutoID={0}", orderUserInfo.AutoID), tran) <= 0)
                    {
                        tran.Rollback();
                        return(false);
                    }

                    #region 宏巍加积分
                    if (websiteInfo.IsUnionHongware == 1)
                    {
                        Open.HongWareSDK.Client hongWareClient = new Open.HongWareSDK.Client(orderInfo.WebsiteOwner);
                        var hongWareMemberInfo = hongWareClient.GetMemberInfo(orderUserInfo.WXOpenId);
                        if (hongWareMemberInfo.member != null)
                        {
                            if (!hongWareClient.UpdateMemberScore(hongWareMemberInfo.member.mobile, orderUserInfo.WXOpenId, addScore))
                            {
                                tran.Rollback();
                                return(false);
                            }
                        }
                    }
                    #endregion

                    //积分解冻
                    if (!string.IsNullOrWhiteSpace(lockModel.Memo))
                    {
                        lockModel.Memo += ";交易成功获得积分解冻";
                    }
                    else
                    {
                        lockModel.Memo = "交易成功获得积分解冻";
                    }

                    if (Update(
                            new ScoreLockInfo(),
                            string.Format(" Memo+='{0}',LockStatus=1,UnLockTime=GETDATE() ", lockModel.Memo),
                            string.Format(" ForeignkeyId='{0}' AND LockType = 1 ", orderInfo.OrderID),
                            tran
                            ) > 0)
                    {
                        #region 微信通知
                        try
                        {
                            string url = string.Format("http://{0}/customize/shop/?v=1.0&ngroute=/myscores#/myscores", bllWebsiteDomain.GetWebsiteDoMain(orderInfo.WebsiteOwner));
                            bllWeixin.SendTemplateMessageNotifyCommTask(orderUserInfo.WXOpenId, "您有一笔积分已经到账", string.Format("积分:{0}分", (int)lockModel.Score), url, "", "", "", orderInfo.WebsiteOwner);
                        }
                        catch
                        {
                        }
                        #endregion
                    }
                    else
                    {
                        msg = string.Format("处理即将到账积分失败!订单号:{0}", orderInfo.OrderID);
                        tran.Rollback();
                        return(false);
                    }
                }
                catch (Exception ex)
                {
                    msg = ex.Message;
                    tran.Rollback();
                    return(false);
                }

                tran.Commit();
            }

            return(true);
        }
Example #9
0
        /// <summary>
        /// 查询我的卡券
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        private string List(HttpContext context)
        {
            int pageIndex = !string.IsNullOrEmpty(context.Request["pageindex"]) ? int.Parse(context.Request["pageindex"]) : 1;
            int pageSize  = !string.IsNullOrEmpty(context.Request["pagesize"]) ? int.Parse(context.Request["pagesize"]) : 20;

            pageSize = int.MaxValue;
            string cardcouponStatus    = context.Request["cardcoupon_status"];
            string isCanUse            = context.Request["is_can_use"];            //可以正常使用的标识
            string amount              = context.Request["amount"];                //订单金额
            string isNotShowStoreValue = context.Request["is_notshow_storevalue"]; //是否不显示储值卡
            // string skuIds = context.Request["sku_ids"];
            bool               isSuccess  = false;
            string             msg        = "";
            string             couponName = "";
            int                totalCount = 0;
            List <MyCardModel> list       = new List <MyCardModel>();

            #region 优惠券
            var sourceData = bllCardCoupon.GetMyCardCoupons(currentUserInfo.UserID, pageIndex, pageSize, out totalCount, cardcouponStatus);

            foreach (var item in sourceData)
            {
                BLLJIMP.Model.CardCoupons cardCoupon = bllCardCoupon.GetCardCoupon(item.CardId);
                cardCoupon = bllCardCoupon.ConvertExpireTime(cardCoupon, item);
                MyCardModel model = new MyCardModel();
                model.cardcoupon_id      = item.AutoId;
                model.cardcoupon_number  = item.CardCouponNumber;
                model.main_cardcoupon_id = item.CardId;

                model.cardcoupon_name      = cardCoupon.Name;
                model.cardcoupon_type      = ConvertCardCouponType(cardCoupon.CardCouponType);
                model.valid_from           = cardCoupon.ValidFrom.ToString();
                model.valid_to             = cardCoupon.ValidTo.ToString();
                model.img_url              = bllMall.GetImgUrl(cardCoupon.Logo);
                model.cardcoupon_status    = item.Status;
                model.cardcoupon_gettime   = bllCardCoupon.GetTimeStamp(item.InsertDate);
                model.product_id           = cardCoupon.Ex2;
                model.valid_from_timestamp = bllCardCoupon.GetTimeStamp((DateTime)cardCoupon.ValidFrom);
                model.valid_to_timestamp   = bllCardCoupon.GetTimeStamp((DateTime)cardCoupon.ValidTo);
                model.discount             = cardCoupon.Ex1;
                model.deductible_amount    = cardCoupon.Ex3;
                model.freefreight_amount   = cardCoupon.Ex4;
                model.buckle_amount        = cardCoupon.Ex5;
                model.buckle_sub_amount    = cardCoupon.Ex6;
                model.limit_type           = cardCoupon.Ex7;
                model.product_tags         = cardCoupon.Ex8;
                model.hexiao_channel       = item.HexiaoChannel;
                model.is_can_use_shop      = cardCoupon.IsCanUseShop;
                model.is_can_use_groupbuy  = cardCoupon.IsCanUseGroupbuy;

                if (model.cardcoupon_type == 4)//满减券直接转成现金券
                {
                    model.buckle_amount     = "";
                    model.buckle_sub_amount = "";
                    model.cardcoupon_type   = 1;
                    model.deductible_amount = cardCoupon.Ex6;
                }

                #region 转赠信息
                model.is_can_give = bllCardCoupon.IsCanGiveCoupon(item, out msg);
                if (!string.IsNullOrEmpty(item.FromUserId))//赠送人信息
                {
                    model.from_user_info = new UserInfoModel();
                    UserInfo fromUserInfo = bllUser.GetUserInfo(item.FromUserId);
                    if (fromUserInfo != null)
                    {
                        model.from_user_info.head_img_url = bllUser.GetUserDispalyAvatar(fromUserInfo);
                        model.from_user_info.nick_name    = bllUser.GetUserDispalyName(fromUserInfo);
                    }
                }
                if (!string.IsNullOrEmpty(item.ToUserId))//被赠送人信息
                {
                    model.to_user_info = new UserInfoModel();
                    UserInfo toUserInfo = bllUser.GetUserInfo(item.ToUserId);
                    if (toUserInfo != null)
                    {
                        model.to_user_info.head_img_url = bllUser.GetUserDispalyAvatar(toUserInfo);
                        model.to_user_info.nick_name    = bllUser.GetUserDispalyName(toUserInfo);
                    }
                }
                #endregion

                if (isCanUse == "1")//可以使用
                {
                    if (model.cardcoupon_status == 0)
                    {
                        if (cardCoupon.ValidFrom != null && cardCoupon.ValidTo != null)
                        {
                            DateTime dtNow = DateTime.Now;
                            if (dtNow >= (DateTime)(cardCoupon.ValidFrom) && (dtNow <= (DateTime)(cardCoupon.ValidTo)))
                            {
                                list.Add(model);
                                //if (!string.IsNullOrEmpty(amount))
                                //{
                                //    if (bllMall.CalcDiscountAmount(item.AutoId.ToString(), decimal.Parse(amount), CurrentUserInfo.UserID, out isSuccess, out msg, out couponName) > 0)
                                //    {
                                //        list.Add(model);
                                //    }
                                //}
                                //else
                                //{
                                //    list.Add(model);
                                //}
                            }
                        }
                    }
                }
                else
                {
                    if (!string.IsNullOrEmpty(amount))
                    {
                        if (bllMall.CalcDiscountAmount(item.AutoId.ToString(), decimal.Parse(amount), currentUserInfo.UserID, out isSuccess, out msg, out couponName) > 0)
                        {
                            list.Add(model);
                        }
                    }
                    else
                    {
                        list.Add(model);
                    }
                }
            }
            #endregion



            #region 储值卡转换成现金券
            if (string.IsNullOrEmpty(isNotShowStoreValue))
            {
                var storeValueCardList = bllStoredValue.GetCanUseStoredValueCardList(currentUserInfo.UserID);
                foreach (var item in storeValueCardList)
                {
                    try
                    {
                        BLLJIMP.Model.StoredValueCard cardCoupon = bllStoredValue.Get <StoredValueCard>(string.Format(" AutoId={0}", item.CardId));
                        MyCardModel model = new MyCardModel();
                        model.cardcoupon_id      = item.AutoId;
                        model.main_cardcoupon_id = item.CardId;
                        model.cardcoupon_name    = string.Format("{0}(储值卡余额{1}元)", cardCoupon.Name, bllMall.GetStoreValueCardCanUseAmount(item.AutoId.ToString(), item.UserId));
                        model.valid_from         = DateTime.Now.ToString();
                        model.valid_to           = cardCoupon.ValidTo.ToString();
                        // model.img_url = bllMall.GetImgUrl(cardCoupon.Logo);
                        model.cardcoupon_status = 0;
                        //model.cardcoupon_gettime = bllCardCoupon.GetTimeStamp(item.InsertDate);
                        //model.product_id = cardCoupon.Ex2;
                        model.valid_from_timestamp = bllCardCoupon.GetTimeStamp(DateTime.Now);
                        model.valid_to_timestamp   = bllCardCoupon.GetTimeStamp((DateTime)cardCoupon.ValidTo);
                        model.discount             = "";
                        //model.deductible_amount = cardCoupon.Ex3;
                        model.freefreight_amount = "";
                        model.buckle_amount      = "";
                        model.buckle_sub_amount  = "";
                        model.limit_type         = "";
                        model.product_tags       = "";
                        //model.hexiao_channel = item.HexiaoChannel;
                        model.is_can_use_shop     = 1;
                        model.is_can_use_groupbuy = 1;
                        model.product_id          = "";
                        model.buckle_amount       = "";
                        model.buckle_sub_amount   = "";
                        model.cardcoupon_type     = 1;
                        model.deductible_amount   = (item.Amount - bllStoredValue.GetUseRecordList(item.AutoId, item.UserId).Sum(p => p.UseAmount)).ToString();
                        model.is_store_card       = 1;
                        list.Add(model);
                        totalCount++;
                    }
                    catch (Exception ex)
                    {
                        continue;
                    }
                }
                #endregion

                #region 海澜处理

                if (bllCardCoupon.WebsiteOwner.Contains("hailan"))
                {
                    Open.HongWareSDK.Client client = new Open.HongWareSDK.Client(bllCardCoupon.WebsiteOwner);
                    Open.HongWareSDK.Entity.YimaVerifyCard yimaCard = new Open.HongWareSDK.Entity.YimaVerifyCard();
                    yimaCard.pos_seq = DateTime.Now.ToString("yyyyMMddHHmmss");

                    List <string> cardCodes = new List <string>();
                    client.YimaCardVerify(yimaCard, out cardCodes, out msg);
                    if (cardCodes.Count > 0)
                    {
                        foreach (var item in list)
                        {
                            if (cardCodes.Contains(item.yima_cardcode))
                            {
                                list.Remove(item);
                            }
                        }
                    }
                    else
                    {
                        list = new List <MyCardModel>();//无卡券可用
                    }
                }
                #endregion
            }
            return(ZentCloud.Common.JSONHelper.ObjectToJson(new
            {
                totalcount = list.Count,
                list = list
            }));
        }
Example #10
0
        public void ProcessRequest(HttpContext context)
        {
            WebsiteInfo websiteInfo = bllMall.GetWebsiteInfoModelFromDataBase();

            Open.HongWareSDK.Client     hongWareClient        = new Open.HongWareSDK.Client(websiteInfo.WebsiteOwner);
            Open.HongWareSDK.MemberInfo hongWeiWareMemberInfo = null;
            if (websiteInfo.IsUnionHongware == 1)
            {
                hongWeiWareMemberInfo = hongWareClient.GetMemberInfo(CurrentUserInfo.WXOpenId);
            }
            string            data              = context.Request["data"];
            decimal           productFee        = 0;                       //商品总价格 不包含邮费
            OrderRequestModel orderRequestModel = new OrderRequestModel(); //订单模型

            try
            {
                orderRequestModel = ZentCloud.Common.JSONHelper.JsonToModel <OrderRequestModel>(data);
            }
            catch (Exception ex)
            {
                resp.errcode = 1;
                resp.errmsg  = "JSON格式错误,请检查。错误信息:" + ex.Message;
                context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(resp));
                return;
            }

            //父订单
            WXMallOrderInfo parentOrderInfo = bllMall.GetOrderInfo(orderRequestModel.order_id);

            if (parentOrderInfo == null)
            {
                resp.errcode = 1;
                resp.errmsg  = "父订单不存在";
                context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(resp));
                return;
            }
            //检查是否可以生成订单
            if (parentOrderInfo.PaymentStatus == 0)
            {
                resp.errcode = 1;
                resp.errmsg  = "父订单未付款";
                context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(resp));
                return;
            }
            if (bllMall.GetCount <WXMallOrderInfo>(string.Format("  ParentOrderId='{0}'  And OrderType=1 And OrderUserId='{1}'", parentOrderInfo.OrderID, CurrentUserInfo.UserID)) > 0)
            {
                resp.errcode = 1;
                resp.errmsg  = "您已经领取过了";
                context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(resp));
                return;
            }
            var parentOrderDetail = bllMall.Get <WXMallOrderDetailsInfo>(string.Format(" OrderID='{0}'", parentOrderInfo.OrderID));

            if (bllMall.GetCount <WXMallOrderInfo>(string.Format(" ParentOrderId='{0}' And OrderID !='{0}' And OrderType=1", parentOrderInfo.OrderID)) >= parentOrderDetail.TotalCount)
            {
                resp.errcode = 1;
                resp.errmsg  = "礼品已经领完";
                context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(resp));
                return;
            }

            #region 格式检查
            //相关检查
            if (string.IsNullOrEmpty(orderRequestModel.receiver_name))
            {
                resp.errcode = 1;
                resp.errmsg  = "收货人姓名不能为空";
                context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(resp));
                return;
            }
            if (string.IsNullOrEmpty(orderRequestModel.receiver_phone))
            {
                resp.errcode = 1;
                resp.errmsg  = "收货人联系电话不能为空";
                context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(resp));
                return;
            }
            if (string.IsNullOrEmpty(orderRequestModel.receiver_province))
            {
                resp.errcode = 1;
                resp.errmsg  = "省份名称不能为空";
                context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(resp));
                return;
            }
            if (string.IsNullOrEmpty(orderRequestModel.receiver_province_code))
            {
                resp.errcode = 1;
                resp.errmsg  = "省份代码不能为空";
                context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(resp));
                return;
            }
            if (string.IsNullOrEmpty(orderRequestModel.receiver_city))
            {
                resp.errcode = 1;
                resp.errmsg  = "城市名称不能为空";
                context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(resp));
                return;
            }
            if (string.IsNullOrEmpty(orderRequestModel.receiver_city_code))
            {
                resp.errcode = 1;
                resp.errmsg  = "城市代码不能为空";
                context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(resp));
                return;
            }
            if (string.IsNullOrEmpty(orderRequestModel.receiver_dist))
            {
                resp.errcode = 1;
                resp.errmsg  = "城市区域名称不能为空";
                context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(resp));
                return;
            }
            if (string.IsNullOrEmpty(orderRequestModel.receiver_dist_code))
            {
                resp.errcode = 1;
                resp.errmsg  = "城市区域代码不能为空";
                context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(resp));
                return;
            }
            if (string.IsNullOrEmpty(orderRequestModel.receiver_address))
            {
                resp.errcode = 1;
                resp.errmsg  = "收货地址不能为空";
                context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(resp));
                return;
            }

            #endregion


            //检查是否可以生成订单

            WXMallOrderInfo orderInfo = new WXMallOrderInfo();//订单表
            orderInfo.Address       = orderRequestModel.receiver_address;
            orderInfo.Consignee     = orderRequestModel.receiver_name;
            orderInfo.InsertDate    = DateTime.Now;
            orderInfo.OrderUserID   = CurrentUserInfo.UserID;
            orderInfo.Phone         = orderRequestModel.receiver_phone;
            orderInfo.WebsiteOwner  = bllMall.WebsiteOwner;
            orderInfo.Transport_Fee = 0;
            orderInfo.OrderID       = bllMall.GetGUID(BLLJIMP.TransacType.AddMallOrder);
            if (bllMall.WebsiteOwner != "mixblu")
            {
                orderInfo.OutOrderId = orderInfo.OrderID;
            }
            orderInfo.OrderMemo            = orderRequestModel.buyer_memo;
            orderInfo.ReceiverProvince     = orderRequestModel.receiver_province;
            orderInfo.ReceiverProvinceCode = orderRequestModel.receiver_province_code.ToString();
            orderInfo.ReceiverCity         = orderRequestModel.receiver_city;
            orderInfo.ReceiverCityCode     = orderRequestModel.receiver_city_code.ToString();
            orderInfo.ReceiverDist         = orderRequestModel.receiver_dist;
            orderInfo.ReceiverDistCode     = orderRequestModel.receiver_dist_code.ToString();
            orderInfo.ZipCode            = orderRequestModel.receiver_zip;
            orderInfo.Status             = "待发货";
            orderInfo.PaymentStatus      = 1;
            orderInfo.PayTime            = DateTime.Now;
            orderInfo.LastUpdateTime     = DateTime.Now;
            orderInfo.ParentOrderId      = parentOrderInfo.OrderID;
            orderInfo.OrderType          = 1;
            orderInfo.PaymentType        = parentOrderInfo.PaymentType;
            orderInfo.LastUpdateTime     = DateTime.Now;
            orderInfo.DistributionStatus = 1;
            #region 订单详情生成
            ///订单详情
            WXMallOrderDetailsInfo detailModel = new WXMallOrderDetailsInfo();
            detailModel.OrderID     = orderInfo.OrderID;
            detailModel.PID         = parentOrderDetail.PID;
            detailModel.TotalCount  = 1;
            detailModel.OrderPrice  = parentOrderDetail.OrderPrice;
            detailModel.ProductName = parentOrderDetail.ProductName;
            detailModel.SkuId       = parentOrderDetail.SkuId;
            detailModel.SkuShowProp = parentOrderDetail.SkuShowProp;

            #endregion

            productFee = (decimal)detailModel.OrderPrice;

            //物流费用


            //合计计算
            orderInfo.Product_Fee       = productFee;
            orderInfo.TotalAmount       = orderInfo.Product_Fee;
            detailModel.MaxRefundAmount = orderInfo.TotalAmount;
            ZentCloud.ZCBLLEngine.BLLTransaction tran = new ZCBLLEngine.BLLTransaction();
            try
            {
                if (!this.bllMall.Add(orderInfo, tran))
                {
                    tran.Rollback();
                    resp.errcode = 1;
                    resp.errmsg  = "提交失败";
                    context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(resp));
                    return;
                }
                #region 插入订单详情
                if (!this.bllMall.Add(detailModel, tran))
                {
                    tran.Rollback();
                    resp.errcode = 1;
                    resp.errmsg  = "提交失败";
                    context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(resp));
                    return;
                }

                #endregion
                tran.Commit();//提交订单事务

                #region 宏巍通知
                if (websiteInfo.IsUnionHongware == 1)
                {
                    hongWareClient.OrderNotice(CurrentUserInfo.WXOpenId, orderInfo.OrderID);
                }
                #endregion

                #region 微信模板消息
                try
                {
                    UserInfo parentUserInfo = bllUser.GetUserInfo(parentOrderInfo.OrderUserID);
                    string   name           = CurrentUserInfo.WXNickname;
                    if (string.IsNullOrEmpty(name))
                    {
                        name = orderInfo.Consignee;
                    }
                    bllWeixin.SendTemplateMessageNotifyComm(parentUserInfo, "礼品领取通知", string.Format("{0}已领取了您赠送的礼品{1}", name, parentOrderDetail.ProductName));
                }
                catch
                {
                }
                #endregion
            }
            catch (Exception ex)
            {
                //回滚事物
                tran.Rollback();
                resp.errcode = 1;
                resp.errmsg  = ex.Message;
                context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(resp));
                return;
            }
            context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(new
            {
                errcode = 0,
                errmsg  = "ok"
            }));
        }
Example #11
0
        /// <summary>
        ///   获取实际SKu信息
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        private string GetTrueSkuInfo(HttpContext context)
        {
            string disType = context.Request["dis_type"];//折扣类型 0 商品折扣 1 会员折扣 2生日折扣

            if (string.IsNullOrEmpty(disType))
            {
                disType = "0";
            }
            string data = context.Request["data"];
            List <RequestSkuModel> requestSkuList = ZentCloud.Common.JSONHelper.JsonToModel <List <RequestSkuModel> >(data);

            Open.HongWareSDK.Client client = new Open.HongWareSDK.Client(bllMall.WebsiteOwner);

            List <BLLJIMP.Model.API.Mall.SkuModel> skuList = new List <BLLJIMP.Model.API.Mall.SkuModel>();

            foreach (var item in requestSkuList)
            {
                var sku = bllMall.GetProductSku(item.sku_id, true);
                BLLJIMP.Model.API.Mall.SkuModel model = new BLLJIMP.Model.API.Mall.SkuModel();
                model.price  = item.price;
                model.count  = item.num;
                model.sku_id = item.sku_id;
                model.sku_sn = sku.SkuSN;
                skuList.Add(model);
            }
            List <ResponseSkuModel> respSkuList = new List <ResponseSkuModel>();
            var result = client.MemberRight(skuList);

            if (result.isSuccess)
            {
                foreach (var orderItem in result.orders[0].orderItems)
                {
                    ResponseSkuModel model = new ResponseSkuModel();
                    var sku = skuList.Single(p => p.sku_sn == orderItem.sku);
                    model.sku_id    = sku.sku_id;
                    model.num       = sku.count;
                    model.pre_price = (decimal)sku.price;

                    switch (disType)
                    {
                    case "0":   //商品折扣
                        model.price    = Convert.ToDecimal(orderItem.pro_RealPrice);
                        model.discount = orderItem.pro_dis;
                        break;

                    case "1":   //会员折扣
                        model.price    = Convert.ToDecimal(orderItem.mem_realPrice);
                        model.discount = orderItem.mem_dis;
                        break;

                    case "2":   //生日折扣
                        model.price    = Convert.ToDecimal(orderItem.birth_realPrice);
                        model.discount = orderItem.birth_dis;
                        break;

                    default:
                        break;
                    }

                    respSkuList.Add(model);
                }
            }


            return(ZentCloud.Common.JSONHelper.ObjectToJson(respSkuList));
        }
Example #12
0
        /// <summary>
        /// 抽奖
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        private string Scratch(HttpContext context)
        {
            try
            {
                if (!bll.IsLogin)
                {
                    return("请先登录");
                }
                string id = context.Request["id"];
                if (string.IsNullOrEmpty(id))
                {
                    return("id必传");
                }

                /*
                 * 检查是否是签到抽奖,是则:
                 * 1.当前是否是在周日,不在周日则不能抽奖
                 * 2.如果在周日,检查是否一周内有签到记录,否则不能抽奖
                 *
                 */

                var signInModel = new BLLJIMP.BLLSignIn().Get <SignInAddress>(string.Format(" WebsiteOwner='{0}' AND Type='Sign' ", currentUserInfo.WebsiteOwner));
                if (signInModel != null && signInModel.LotteryId == id)
                {
                    var dt = DateTime.Now;

                    if (dt.DayOfWeek != DayOfWeek.Sunday)
                    {
                        return("周日才可以抽奖");
                    }

                    //获取本周签到记录,倒退七天是否有七条
                    var signInCount = bll.GetCount <SignInLog>(string.Format("  cast(SignInDate as date) between '{0}' and '{1}' and  WebsiteOwner = '{2}' and UserID = '{3}' ",
                                                                             dt.AddDays(-6).ToString("yyyy-MM-dd"),
                                                                             dt.ToString("yyyy-MM-dd"),
                                                                             currentUserInfo.WebsiteOwner,
                                                                             currentUserInfo.UserID
                                                                             ));

                    if (signInCount < 7)
                    {
                        return("一周连续签到才可以抽奖");
                    }
                }

                #region 检查是否可以继续
                ScratchJsonModel apiResult = new ScratchJsonModel();
                apiResult.awardName = "谢谢参与";
                WXLotteryV1 model = bll.Get <WXLotteryV1>(string.Format("LotteryID={0}", id));
                if (model == null)
                {
                    goto outoff;
                }
                apiResult.awardId = model.LotteryID;
                apiResult.isStart = model.Status == 1 ? true : false;
                if (model.StartTime != null)
                {
                    apiResult.startTime = model.StartTime.Value.ToString("yyyy/MM/dd HH:mm:ss");
                    if (model.StartTime <= DateTime.Now)//已经到了开奖时间了
                    {
                        if (model.Status == 1)
                        {
                            apiResult.isStart = true;
                        }
                        else
                        {
                            apiResult.errorCode = (int)BLLJIMP.Enums.APIErrCode.NotStart;
                            apiResult.awardName = "刮奖未开启";
                            apiResult.isStart   = false;
                        }
                    }
                    else//开奖时间还没到
                    {
                        apiResult.errorCode = (int)BLLJIMP.Enums.APIErrCode.NotStart;
                        apiResult.awardName = "未到刮奖时间";
                        apiResult.isStart   = false;
                        goto outoff;
                    }
                }

                //检查结束时间
                if (model.EndTime != null)
                {
                    apiResult.startTime = model.EndTime.Value.ToString("yyyy/MM/dd HH:mm:ss");
                    if (model.EndTime.Value <= DateTime.Now)
                    {
                        apiResult.errorCode = (int)BLLJIMP.Enums.APIErrCode.IsEnd;
                        apiResult.awardName = "已结束";
                        apiResult.isStart   = false;
                        goto outoff;
                    }
                }

                if (context.Request["hideAward"] != "1")
                {
                    apiResult.winRecord = bll.GetWXLotteryRecordList(model.LotteryID, currentUserInfo.UserID);
                }
                if (model.WinLimitType.Equals(0))
                {
                    var lotteryRecord = bll.GetWXLotteryRecordV1(currentUserInfo.UserID, model.LotteryID);
                    if (lotteryRecord != null)
                    {
                        if (context.Request["hideAward"] != "1")
                        {
                            WXLotteryLogV1 logWinLimit = new WXLotteryLogV1();
                            logWinLimit.LotteryId  = model.LotteryID;
                            logWinLimit.UserId     = currentUserInfo.UserID;
                            logWinLimit.InsertDate = DateTime.Now;
                            logWinLimit.IP         = Common.MySpider.GetClientIP();
                            if (bll.AddWXLotteryLogV1(logWinLimit))//下一步
                            {
                            }

                            apiResult.awardName = string.Format("{0}", lotteryRecord.WXAwardName);
                            apiResult.isAward   = true;

                            //告诉前端你已经中过奖了
                            apiResult.errorCode = (int)BLLJIMP.Enums.APIErrCode.LotteryHaveRecord;; //LotteryHaveRecord
                        }
                        goto outoff;
                    }
                }

                if (!apiResult.isStart)
                {
                    apiResult.errorCode = (int)BLLJIMP.Enums.APIErrCode.NotStart;
                    apiResult.awardName = "刮奖未开启";
                    apiResult.isStart   = false;
                    goto outoff;
                }
                #endregion

                #region 内定中奖
                List <WXLotteryWinningDataV1> winData = bll.GetList <WXLotteryWinningDataV1>(string.Format("LotteryId={0}", model.LotteryID));
                if (winData.SingleOrDefault(p => p.UserId.Equals(currentUserInfo.UserID)) != null)
                {
                    //给默认中奖者中奖
                    WXLotteryRecordV1 record = new WXLotteryRecordV1();
                    record.InsertDate = DateTime.Now;
                    record.LotteryId  = model.LotteryID;
                    record.Token      = "0";
                    record.WXAwardsId = winData.Single(p => p.UserId.Equals(currentUserInfo.UserID)).WXAwardsId;
                    record.UserId     = currentUserInfo.UserID;
                    record.IsGetPrize = 0;
                    if (bll.AddWXLotteryRecordV1(record))
                    {
                        apiResult.awardName = string.Format("{0}", winData.Single(p => p.UserId.Equals(currentUserInfo.UserID)).WXAwardName);
                        apiResult.isAward   = true;
                    }

                    goto outoff;
                }
                //设置默认中奖
                #endregion

                #region 外部积分读取
                var isSyncYike = new BLLJIMP.BLLCommRelation().ExistRelation(BLLJIMP.Enums.CommRelationType.SyncYike, currentUserInfo.WebsiteOwner, "");

                Open.EZRproSDK.Client zrClient = new Open.EZRproSDK.Client();

                if (isSyncYike)
                {
                    var getBonusResp = zrClient.GetBonus(currentUserInfo.Ex1, currentUserInfo.Ex2, currentUserInfo.Phone);
                    if (getBonusResp != null)
                    {
                        currentUserInfo.TotalScore = getBonusResp.Bonus;
                    }
                    else
                    {
                        currentUserInfo.TotalScore = 0;
                    }
                }
                #endregion


                #region 使用宏巍积分

                Open.HongWareSDK.Client hongWareClient = new Open.HongWareSDK.Client(websiteInfo.WebsiteOwner);
                if (websiteInfo.IsUnionHongware == 1)
                {
                    var hongWareMemberInfo = hongWareClient.GetMemberInfo(currentUserInfo.WXOpenId);
                    if (hongWareMemberInfo.member != null)
                    {
                        currentUserInfo.TotalScore = hongWareMemberInfo.member.point;
                    }
                    else
                    {
                        currentUserInfo.TotalScore = 0;
                    }
                }
                #endregion

                string tempMsg = "";
                #region 抽奖限制 总共多少次或每天几次  用购买的刮奖次数除外

                #region 总共多少次
                if (model.LuckLimitType.Equals(0))//总共多少次
                {
                    int count = bll.GetWXLotteryLogCountV1(model.LotteryID, currentUserInfo.UserID);
                    if (count >= model.MaxCount)
                    {
                        //判读是否够积分
                        if (model.UsePoints > 0)
                        {
                            if (currentUserInfo.TotalScore >= model.UsePoints)
                            {
                                //扣积分
                                if (isSyncYike)
                                {
                                    var resp = zrClient.BonusUpdate(currentUserInfo.Ex2, -model.UsePoints, "抽奖减少积分");
                                }
                                else
                                {
                                    bllUser.AddUserScoreDetail(currentUserInfo.UserID, EnumStringHelper.ToString(ScoreDefineType.Lottery), bllUser.WebsiteOwner, out tempMsg, -model.UsePoints, "抽奖减少积分", "", false);
                                }
                            }
                            else
                            {
                                if (currentUserInfo.LotteryCount == 0)
                                {
                                    apiResult.errorCode = (int)BLLJIMP.Enums.APIErrCode.IntegralProblem;
                                    apiResult.awardName = "积分不足";
                                    apiResult.isStart   = false;
                                    goto outoff;
                                }
                                else
                                {
                                    //剩余刮奖次数减1
                                    if (bll.Update(currentUserInfo, string.Format(" LotteryCount-=1"), string.Format("AutoId={0}", currentUserInfo.AutoID)) <= 0)
                                    {
                                        apiResult.errorCode = (int)BLLJIMP.Enums.APIErrCode.IntegralProblem;
                                        apiResult.awardName = "谢谢参与";
                                        apiResult.isStart   = false;
                                        goto outoff;
                                    }
                                }
                            }
                        }
                        else
                        {
                            apiResult.errorCode = (int)BLLJIMP.Enums.APIErrCode.CountIsOver;
                            apiResult.awardName = "谢谢参与";
                            goto outoff;
                        }
                    }
                }
                #endregion

                #region 每天多少次
                else
                {
                    //判读一天有没有超出
                    int count = bll.GetWXLotteryLogCountV1(model.LotteryID, currentUserInfo.UserID, DateTime.Now);
                    if (count >= model.MaxCount)
                    {
                        //判读是否够积分
                        if (model.UsePoints > 0)
                        {
                            if (currentUserInfo.TotalScore >= model.UsePoints)
                            {
                                if (isSyncYike)
                                {
                                    var resp = zrClient.BonusUpdate(currentUserInfo.Ex2, -model.UsePoints, "抽奖减少积分");
                                }
                                else
                                {
                                    //扣积分
                                    bllUser.AddUserScoreDetail(currentUserInfo.UserID, EnumStringHelper.ToString(ScoreDefineType.Lottery), bllUser.WebsiteOwner, out tempMsg, -model.UsePoints, "抽奖减少积分", "", false);
                                }
                            }
                            else
                            {
                                if (currentUserInfo.LotteryCount == 0)
                                {
                                    apiResult.errorCode = (int)BLLJIMP.Enums.APIErrCode.IntegralProblem;
                                    apiResult.awardName = "积分不足";
                                    apiResult.isStart   = false;
                                    goto outoff;
                                }
                                else
                                {
                                    //剩余刮奖次数减1
                                    if (bll.Update(currentUserInfo, string.Format(" LotteryCount-=1"), string.Format("AutoId={0}", currentUserInfo.AutoID)) <= 0)
                                    {
                                        apiResult.errorCode = (int)BLLJIMP.Enums.APIErrCode.IntegralProblem;
                                        apiResult.awardName = "谢谢参与";
                                        apiResult.isStart   = false;
                                        goto outoff;
                                    }
                                }
                            }
                        }
                        else
                        {
                            apiResult.errorCode = (int)BLLJIMP.Enums.APIErrCode.CountIsOver;
                            apiResult.awardName = "谢谢参与";
                            goto outoff;
                        }
                    }
                }
                #endregion

                #endregion

                WXLotteryLogV1 log = new WXLotteryLogV1();
                log.LotteryId  = model.LotteryID;
                log.UserId     = currentUserInfo.UserID;
                log.InsertDate = DateTime.Now;
                log.IP         = Common.MySpider.GetClientIP();
                if (bll.AddWXLotteryLogV1(log))//下一步
                {
                    #region 奖池生成
                    List <AwardModel> awardModelList = new List <AwardModel>();                                                             //奖池
                    List <WXAwardsV1> awardsList     = bll.GetAwardsListV1(model.LotteryID).Where(p => p.WinCount < p.PrizeCount).ToList(); //奖品列表 //已经中完的不参与
                    foreach (var item in awardsList)
                    {
                        for (int i = 1; i <= item.Probability; i++)
                        {
                            AwardModel m = new AwardModel();
                            m.AwardID    = item.AutoID;
                            m.PrizeName  = item.PrizeName;
                            m.AwardsType = item.AwardsType;
                            m.Img        = item.Img;
                            m.Value      = item.Value;
                            awardModelList.Add(m);
                        }
                    }
                    if (awardsList.Sum(p => p.Probability) < 100)//总中奖概率小于100 补足
                    {
                        for (int i = 1; i <= (100 - (awardsList.Sum(p => p.Probability))); i++)
                        {
                            AwardModel m = new AwardModel();
                            m.AwardID   = 0;
                            m.PrizeName = "谢谢参与";
                            awardModelList.Add(m);
                        }
                    }
                    #endregion
                    //打乱数组顺序
                    awardModelList = GetRandomList <AwardModel>(awardModelList);
                    Random rand  = new Random();
                    int    index = rand.Next(0, awardModelList.Count);

                    #region 抽奖
                    if (awardModelList[index].AwardID > 0)//随机数中奖
                    {
                        string sqlUpdate = string.Format(" Update ZCJ_WXAwardsV1  Set WinCount+=1  where AutoID={0} And WinCount<PrizeCount ", awardModelList[index].AwardID);
                        if (ZentCloud.ZCBLLEngine.BLLBase.ExecuteSql(sqlUpdate) > 0)
                        {
                            int token = rand.Next(1111, 9999);
                            //插入中奖记录
                            WXLotteryRecordV1 record = new WXLotteryRecordV1();
                            record.InsertDate = DateTime.Now;
                            record.LotteryId  = model.LotteryID;
                            record.Token      = token.ToString();
                            record.WXAwardsId = awardModelList[index].AwardID;
                            record.UserId     = currentUserInfo.UserID;
                            record.IsGetPrize = 0;
                            if (bll.AddWXLotteryRecordV1(record))
                            {
                                apiResult.awardName  = string.Format("{0}", awardModelList[index].PrizeName);
                                apiResult.isAward    = true;
                                apiResult.awardsType = awardModelList[index].AwardsType;
                                apiResult.img        = awardModelList[index].Img;
                                apiResult.value      = awardModelList[index].Value;

                                if (apiResult.awardsType == 2)
                                {
                                    BLLJIMP.BLLCardCoupon bllCardCoupon = new BLLJIMP.BLLCardCoupon();

                                    var coupon = bllCardCoupon.GetCardCoupon(int.Parse(apiResult.value));
                                    apiResult.cardcoupon_name  = coupon.Name;
                                    apiResult.cardcoupon_type  = coupon.CardCouponType;
                                    apiResult.cardcoupon_start = coupon.ValidFrom == null ? "" : coupon.ValidFrom.Value.ToShortDateString();
                                    apiResult.cardcoupon_end   = coupon.ValidTo == null ? "" : coupon.ValidTo.Value.ToShortDateString();
                                    if (coupon.ExpireTimeType == "1")
                                    {
                                        apiResult.cardcoupon_start = DateTime.Now.ToShortDateString();
                                        apiResult.cardcoupon_end   = DateTime.Now.AddDays(Convert.ToInt32(coupon.ExpireDay)).ToShortDateString();
                                    }
                                }
                                if (apiResult.awardsType == 1 || apiResult.awardsType == 2)
                                {
                                    //中奖记录标记为已经领奖
                                    WXLotteryRecordV1 rec = bll.Get <WXLotteryRecordV1>(string.Format(" UserId='{0}' And LotteryId={1} And WXAwardsId={2} And Token='{3}'", record.UserId, record.LotteryId, record.WXAwardsId, record.Token));
                                    if (rec != null)
                                    {
                                        rec.IsGetPrize = 1;
                                        bll.Update(rec);
                                    }
                                }

                                goto outoff;
                            }
                            else
                            {
                                goto outoff;
                            }
                        }
                        else
                        {
                            goto outoff;
                        }

                        //}
                        //else
                        //{   //#region 虽然随机数中奖,但是奖项数量已经达到上限,重新随机抽奖
                        //    //if (reCount >= 5)
                        //    //{
                        //    goto outoff;
                        //    //}
                        //    //reCount++;
                        //    //goto start;
                        //}
                    }
                    else
                    {
                        //随机数未中奖
                    }
                    #endregion
                }
outoff:
                if (!string.IsNullOrEmpty(context.Request["callback"]))
                {
                    return(string.Format("{0}({1})", context.Request["callback"], Common.JSONHelper.ObjectToJson(apiResult)));
                }
                return(Common.JSONHelper.ObjectToJson(apiResult));
            }
            catch (Exception ex)
            {
                return(ex.ToString());
            }
        }
Example #13
0
File: Add.ashx.cs Project: uvbs/mmp
        public void ProcessRequest(HttpContext context)
        {
            WebsiteInfo websiteInfo = bllMall.GetWebsiteInfoModelFromDataBase();

            Open.HongWareSDK.Client     hongWareClient        = new Open.HongWareSDK.Client(websiteInfo.WebsiteOwner);
            Open.HongWareSDK.MemberInfo hongWeiWareMemberInfo = null;
            if (websiteInfo.IsUnionHongware == 1)
            {
                hongWeiWareMemberInfo = hongWareClient.GetMemberInfo(CurrentUserInfo.WXOpenId);
                if (hongWeiWareMemberInfo.member == null)
                {
                    apiResp.code = (int)APIErrCode.OperateFail;
                    apiResp.msg  = "您尚未绑定宏巍账号,请先绑定";
                    context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(apiResp));
                    return;
                }
            }
            string data = context.Request["data"];

            if (string.IsNullOrEmpty(data))
            {
                apiResp.code = (int)APIErrCode.OperateFail;
                apiResp.msg  = "data 参数必传";
                context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(apiResp));
                return;
            }
            decimal    productFee = 0;    //商品总价格 不包含邮费
            OrderModel orderRequestModel; //订单模型

            try
            {
                orderRequestModel = ZentCloud.Common.JSONHelper.JsonToModel <OrderModel>(data);
            }
            catch (Exception ex)
            {
                apiResp.code = (int)APIErrCode.OperateFail;
                apiResp.msg  = "JSON格式错误,请检查。错误信息:" + ex.Message;
                context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(apiResp));
                return;
            }
            WXMallOrderInfo orderInfo = new WXMallOrderInfo();//订单表

            orderInfo.Address   = orderRequestModel.receiver_address;
            orderInfo.Consignee = orderRequestModel.receiver_name;
            //orderInfo.ExpressCompanyName = orderRequestModel.express_company;
            orderInfo.InsertDate    = DateTime.Now;
            orderInfo.OrderUserID   = CurrentUserInfo.UserID;
            orderInfo.Phone         = orderRequestModel.receiver_phone;
            orderInfo.WebsiteOwner  = bllMall.WebsiteOwner;
            orderInfo.Transport_Fee = 0;
            orderInfo.OrderID       = bllMall.GetGUID(BLLJIMP.TransacType.AddMallOrder);
            if (bllMall.WebsiteOwner != "mixblu")
            {
                orderInfo.OutOrderId = orderInfo.OrderID;
            }
            orderInfo.OrderMemo            = orderRequestModel.buyer_memo;
            orderInfo.ReceiverProvince     = orderRequestModel.receiver_province;
            orderInfo.ReceiverProvinceCode = orderRequestModel.receiver_province_code.ToString();
            orderInfo.ReceiverCity         = orderRequestModel.receiver_city;
            orderInfo.ReceiverCityCode     = orderRequestModel.receiver_city_code.ToString();
            orderInfo.ReceiverDist         = orderRequestModel.receiver_dist;
            orderInfo.ReceiverDistCode     = orderRequestModel.receiver_dist_code.ToString();
            orderInfo.ZipCode        = orderRequestModel.receiver_zip;
            orderInfo.MyCouponCardId = orderRequestModel.cardcoupon_id.ToString();
            orderInfo.UseScore       = orderRequestModel.use_score;
            orderInfo.UseAmount      = orderRequestModel.use_amount;
            orderInfo.Status         = "待付款";
            orderInfo.OrderType      = 2;
            orderInfo.LastUpdateTime = DateTime.Now;

            //if (!string.IsNullOrEmpty(orderRequestModel.sale_id))
            //{
            //    long saleId = 0;
            //    if (long.TryParse(orderRequestModel.sale_id, out saleId))
            //    {
            //        orderInfo.SellerId = saleId;
            //    }
            //    else
            //    {

            //    }


            //}
            if (orderRequestModel.pay_type == "WEIXIN")//微信支付
            {
                orderInfo.PaymentType = 2;
            }
            else if (orderRequestModel.pay_type == "ALIPAY")//支付宝支付
            {
                orderInfo.PaymentType = 1;
            }

            #region 格式检查


            //相关检查
            if (string.IsNullOrEmpty(orderRequestModel.rule_id))
            {
                apiResp.code = (int)APIErrCode.OperateFail;
                apiResp.msg  = "rule_id 必传";
                context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(apiResp));
                return;
            }
            if (string.IsNullOrEmpty(orderInfo.Consignee))
            {
                apiResp.code = (int)APIErrCode.OperateFail;
                apiResp.msg  = "收货人姓名不能为空";
                context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(apiResp));
                return;
            }
            if (string.IsNullOrEmpty(orderInfo.Phone))
            {
                apiResp.code = (int)APIErrCode.OperateFail;
                apiResp.msg  = "收货人联系电话不能为空";
                context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(apiResp));
                return;
            }
            if (string.IsNullOrEmpty(orderInfo.ReceiverProvince))
            {
                apiResp.code = (int)APIErrCode.OperateFail;
                apiResp.msg  = "省份名称不能为空";
                context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(apiResp));
                return;
            }
            if (string.IsNullOrEmpty(orderInfo.ReceiverProvinceCode))
            {
                apiResp.code = (int)APIErrCode.OperateFail;
                apiResp.msg  = "省份代码不能为空";
                context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(apiResp));
                return;
            }
            if (string.IsNullOrEmpty(orderInfo.ReceiverCity))
            {
                apiResp.code = (int)APIErrCode.OperateFail;
                apiResp.msg  = "城市名称不能为空";
                context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(apiResp));
                return;
            }
            if (string.IsNullOrEmpty(orderInfo.ReceiverCityCode))
            {
                apiResp.code = (int)APIErrCode.OperateFail;
                apiResp.msg  = "城市代码不能为空";
                context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(apiResp));
                return;
            }
            if (string.IsNullOrEmpty(orderInfo.ReceiverDist))
            {
                apiResp.code = (int)APIErrCode.OperateFail;
                apiResp.msg  = "城市区域名称不能为空";
                context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(apiResp));
                return;
            }
            if (string.IsNullOrEmpty(orderInfo.ReceiverCityCode))
            {
                apiResp.code = (int)APIErrCode.OperateFail;
                apiResp.msg  = "城市区域代码不能为空";
                context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(apiResp));
                return;
            }
            if (string.IsNullOrEmpty(orderInfo.Address))
            {
                apiResp.code = (int)APIErrCode.OperateFail;
                apiResp.msg  = "收货地址不能为空";
                context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(apiResp));
                return;
            }
            if (orderRequestModel.skus == null)
            {
                apiResp.code = (int)APIErrCode.OperateFail;
                apiResp.msg  = "参数skus 不能为空";
                context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(apiResp));
                return;
            }


            //相关检查
            #endregion

            #region 分销关系建立
            if (websiteInfo.DistributionRelationBuildMallOrder == 1)
            {
                if (!string.IsNullOrEmpty(orderRequestModel.sale_id))
                {
                    int saleId = 0;
                    if (int.TryParse(orderRequestModel.sale_id, out saleId))
                    {
                        orderInfo.SellerId = saleId;
                        if (string.IsNullOrEmpty(CurrentUserInfo.DistributionOwner))
                        {
                            var recommendUserInfo = bllUser.GetUserInfoByAutoID(saleId);
                            if (recommendUserInfo != null)
                            {
                                var setUserDistributionOwnerResult = bllDis.SetUserDistributionOwner(CurrentUserInfo.UserID, recommendUserInfo.UserID, CurrentUserInfo.WebsiteOwner);

                                if (setUserDistributionOwnerResult)
                                {
                                    CurrentUserInfo.DistributionOwner = recommendUserInfo.UserID;
                                    CurrentUserInfo.Channel           = recommendUserInfo.Channel;
                                }
                            }
                        }
                    }
                    else
                    {
                    }
                }
                else
                {
                    if (string.IsNullOrEmpty(CurrentUserInfo.DistributionOwner))
                    {
                        CurrentUserInfo.DistributionOwner = bllUser.WebsiteOwner;
                        bllUser.Update(CurrentUserInfo);
                    }
                }
            }
            #endregion

            if (orderRequestModel.skus.Count > 1)
            {
                apiResp.code = (int)APIErrCode.OperateFail;
                apiResp.msg  = "只能购买一种商品";
                context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(apiResp));
                return;
            }
            if (orderRequestModel.skus.Sum(p => p.count) > 1)
            {
                apiResp.code = (int)APIErrCode.OperateFail;
                apiResp.msg  = "团购商品只能购买一件";
                context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(apiResp));
                return;
            }


            List <ProductGroupBuyRule> groupBuyList = new List <ProductGroupBuyRule>();//此商品的团购规则列表

            #region 购买的商品
            List <WXMallProductInfo> productList = new List <WXMallProductInfo>();
            foreach (var sku in orderRequestModel.skus)
            {
                ProductSku productSku = bllMall.GetProductSku(sku.sku_id);
                if (productSku == null)
                {
                    apiResp.code = (int)APIErrCode.OperateFail;
                    apiResp.msg  = "sku_id 无效";
                    context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(apiResp));
                    return;
                }
                // WXMallProductInfo productInfo = bllMall.GetProduct(productSku.ProductId.ToString());
                //productList.Add(productInfo);

                //ProductSku productSku = bllMall.GetProductSku(sku.sku_id);

                //if (productSku == null) continue;
                if (productList.Count(p => p.PID == productSku.ProductId.ToString()) > 0)
                {
                    continue;
                }

                WXMallProductInfo productInfo = bllMall.GetProduct(productSku.ProductId.ToString());
                productList.Add(productInfo);
                groupBuyList = bllMall.GetProductGroupBuyRuleList(productSku.ProductId.ToString());
            }

            if (groupBuyList.Count == 0)
            {
                apiResp.code = (int)APIErrCode.OperateFail;
                apiResp.msg  = "此商品不能团购";
                context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(apiResp));
                return;
            }
            if (groupBuyList.SingleOrDefault(p => p.RuleId == int.Parse(orderRequestModel.rule_id)) == null)
            {
                apiResp.code = (int)APIErrCode.OperateFail;
                apiResp.msg  = "rule_id 错误,请检查";
                context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(apiResp));
                return;
            }

            ProductGroupBuyRule groupBuyRule = groupBuyList.SingleOrDefault(p => p.RuleId == int.Parse(orderRequestModel.rule_id));//团购规则

            // productList = productList.Distinct().ToList();
            #endregion

            string cardCouponType = "";//优惠券类型
            #region 检查优惠券是否可用
            if (orderRequestModel.cardcoupon_id > 0)
            {
                var mycardCoupon = bllCardCoupon.GetMyCardCoupon(orderRequestModel.cardcoupon_id, CurrentUserInfo.UserID);
                if (mycardCoupon == null)
                {
                    apiResp.code = 1;
                    apiResp.msg  = "无效的优惠券";
                    context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(apiResp));
                    return;
                }
                var cardCoupon = bllCardCoupon.GetCardCoupon(mycardCoupon.CardId);
                if (cardCoupon == null)
                {
                    apiResp.code = 1;
                    apiResp.msg  = "无效的优惠券";
                    context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(apiResp));
                    return;
                }
                cardCouponType = cardCoupon.CardCouponType;
                #region 需要购买指定商品
                if ((!string.IsNullOrEmpty(cardCoupon.Ex2)) && (cardCoupon.Ex2 != "0"))
                {
                    if (productList.Count(p => p.PID == cardCoupon.Ex2) == 0)
                    {
                        var productInfo = bllMall.GetProduct(cardCoupon.Ex2);
                        apiResp.code = 1;
                        apiResp.msg  = string.Format("此优惠券需要购买{0}时才可以使用", productInfo.PName);
                        context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(apiResp));
                        return;
                    }
                }
                #endregion

                #region 需要购买指定标签商品
                if (!string.IsNullOrEmpty(cardCoupon.Ex8))
                {
                    if (productList.Where(p => p.Tags == "" || p.Tags == null).Count() == productList.Count)//全部商品都没有标签
                    {
                        apiResp.code = 1;
                        apiResp.msg  = string.Format("使用此优惠券需要购买标签为{0}的商品", cardCoupon.Ex8);
                        context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(apiResp));
                        return;
                    }
                    bool checkResult = true;
                    foreach (var product in productList)
                    {
                        if (!string.IsNullOrEmpty(product.Tags))
                        {
                            bool tempResult = false;
                            foreach (string tag in product.Tags.Split(','))
                            {
                                if (cardCoupon.Ex8.Contains(tag))
                                {
                                    tempResult = true;
                                    break;
                                }
                            }
                            if (!tempResult)
                            {
                                checkResult = false;
                                break;
                            }
                        }
                        else//商品不包含标签
                        {
                            checkResult = false;
                            break;
                        }
                    }
                    if (!checkResult)
                    {
                        apiResp.code = 1;
                        apiResp.msg  = string.Format("使用此优惠券需要购买标签为{0}的商品", cardCoupon.Ex8);
                        context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(apiResp));
                        return;
                    }
                }
                #endregion
            }
            #endregion

            var     needUseScore = 0; //必须使用的积分
            decimal needUseCash  = 0; //必须使用的现金
            #region 商品检查 订单详情生成
            ///订单详情
            List <WXMallOrderDetailsInfo> detailList = new List <WXMallOrderDetailsInfo>();//订单详情
            orderRequestModel.skus = orderRequestModel.skus.Distinct().ToList();
            foreach (var sku in orderRequestModel.skus)
            {
                //先检查库存
                ProductSku productSku = bllMall.GetProductSku(sku.sku_id);
                if (productSku == null)
                {
                    apiResp.code = (int)APIErrCode.OperateFail;
                    apiResp.msg  = "SKU不存在";
                    context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(apiResp));
                    return;
                }

                WXMallProductInfo productInfo = productList.Single(p => p.PID == productSku.ProductId.ToString());
                if (productInfo.IsOnSale == "0")
                {
                    apiResp.code = (int)APIErrCode.OperateFail;
                    apiResp.msg  = string.Format("{0}已下架", productInfo.PName);
                    context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(apiResp));
                    return;
                }
                if (productSku.Stock < sku.count)
                {
                    apiResp.code = (int)APIErrCode.OperateFail;
                    apiResp.msg  = string.Format("{0}{1}库存余量为{2},库存不足,请减少购买数量", productInfo.PName, bllMall.GetProductShowProperties(productSku.SkuId), productSku.Stock);
                    context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(apiResp));
                    return;
                }
                if (productInfo.Score > 0)//必须使用的积分
                {
                    needUseScore += sku.count * productInfo.Score;
                }
                if (productInfo.IsCashPayOnly == 1)//必须使用的现金
                {
                    needUseCash += (Math.Round((decimal)(productSku.Price * (decimal)(groupBuyRule.HeadDiscount / 10)), 2)) * sku.count;
                }
                WXMallOrderDetailsInfo detailModel = new WXMallOrderDetailsInfo();
                detailModel.OrderID     = orderInfo.OrderID;
                detailModel.PID         = productInfo.PID;
                detailModel.TotalCount  = sku.count;
                detailModel.OrderPrice  = Math.Round((decimal)(productSku.Price * (decimal)(groupBuyRule.HeadDiscount / 10)), 2);//四舍五入
                detailModel.ProductName = productInfo.PName;
                detailModel.SkuId       = productSku.SkuId;
                detailModel.SkuShowProp = bllMall.GetProductShowProperties(productSku.SkuId);
                detailModel.IsComplete  = 1;//拼团的只要下单就算销量
                detailList.Add(detailModel);
            }
            #endregion

            #region 纯积分购买
            if (needUseScore > 0)
            {
                if ((CurrentUserInfo.TotalScore < needUseScore) || (orderRequestModel.use_score < needUseScore))
                {
                    apiResp.code = (int)APIErrCode.OperateFail;
                    apiResp.msg  = string.Format("您需要使用{0}积分来兑换, 可用积分不足", needUseScore);
                    context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(apiResp));
                    return;
                }
            }
            #endregion

            productFee = detailList.Sum(p => p.OrderPrice * p.TotalCount).Value;//商品费用
            //物流费用
            #region 运费计算
            FreightModel freightModel = new FreightModel();
            freightModel.receiver_province_code = orderRequestModel.receiver_province_code;
            freightModel.receiver_city_code     = orderRequestModel.receiver_city_code;
            freightModel.receiver_dist_code     = orderRequestModel.receiver_dist_code;
            freightModel.skus = orderRequestModel.skus;
            decimal freight    = 0;//运费
            string  freightMsg = "";
            if (!bllMall.CalcFreight(freightModel, out freight, out freightMsg))
            {
                apiResp.code = (int)APIErrCode.OperateFail;
                apiResp.msg  = freightMsg;
                context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(apiResp));
                return;
            }
            orderInfo.Transport_Fee = freight;
            #endregion

            #region 优惠券计算

            decimal discountAmount   = 0;//优惠金额
            bool    canUseCardCoupon = false;
            string  msg = "";
            if (orderRequestModel.cardcoupon_id > 0)//有优惠券
            {
                discountAmount = bllMall.CalcDiscountAmount(orderRequestModel.cardcoupon_id.ToString(), data, CurrentUserInfo.UserID, out canUseCardCoupon, out msg);
                if (!canUseCardCoupon)
                {
                    apiResp.code = (int)APIErrCode.OperateFail;
                    apiResp.msg  = msg;
                    context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(apiResp));
                    return;
                }
                if (cardCouponType == "MallCardCoupon_FreeFreight")//免邮券
                {
                    orderInfo.Transport_Fee = 0;
                }
            }
            //优惠券计算
            #endregion

            #region 积分计算
            decimal scoreExchangeAmount = 0;///积分抵扣的金额
            //积分计算
            if (orderRequestModel.use_score > 0)
            {
                #region 使用宏巍积分
                if (websiteInfo.IsUnionHongware == 1)
                {
                    CurrentUserInfo.TotalScore = hongWeiWareMemberInfo.member.point;
                }
                #endregion
                if (CurrentUserInfo.TotalScore < orderRequestModel.use_score)
                {
                    apiResp.code = (int)APIErrCode.OperateFail;
                    apiResp.msg  = "积分不足";
                    context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(apiResp)); return;
                }

                ScoreConfig scoreConfig = bllScore.GetScoreConfig();
                if (scoreConfig != null && scoreConfig.ExchangeAmount > 0)
                {
                    scoreExchangeAmount = Math.Round(orderRequestModel.use_score / (scoreConfig.ExchangeScore / scoreConfig.ExchangeAmount), 2);
                }
                //scoreExchangeAmount = Math.Round(orderRequestModel.use_score / (scoreConfig.ExchangeScore / scoreConfig.ExchangeAmount), 2);
            }



            //积分计算
            #endregion

            #region 使用账户余额
            if (orderRequestModel.use_amount > 0)
            {
                if (!bllMall.IsEnableAccountAmountPay())
                {
                    apiResp.msg = "尚未启用余额支付功能";
                    context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(apiResp));
                    return;
                }
                #region 使用宏巍余额
                if (websiteInfo.IsUnionHongware == 1)
                {
                    CurrentUserInfo.AccountAmount = (decimal)hongWeiWareMemberInfo.member.balance;
                }
                #endregion

                if (CurrentUserInfo.AccountAmount < orderRequestModel.use_amount)
                {
                    apiResp.code = (int)APIErrCode.OperateFail;
                    apiResp.msg  = "您的账户余额不足";
                    context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(apiResp));
                    return;
                }
            }
            #endregion

            //合计计算
            orderInfo.Product_Fee         = productFee;
            orderInfo.TotalAmount         = orderInfo.Product_Fee + orderInfo.Transport_Fee;
            orderInfo.TotalAmount        -= discountAmount;                  //优惠券优惠金额
            orderInfo.TotalAmount        -= scoreExchangeAmount;             //积分优惠金额
            orderInfo.TotalAmount        -= orderRequestModel.use_amount;    //余额
            orderInfo.PayableAmount       = orderInfo.TotalAmount - freight; //应付金额
            orderInfo.ScoreExchangAmount  = scoreExchangeAmount;             //优惠券抵扣金额
            orderInfo.CardcouponDisAmount = discountAmount;                  //卡券抵扣金额
            if ((productFee + orderInfo.Transport_Fee - discountAmount - scoreExchangeAmount) < orderInfo.TotalAmount)
            {
                apiResp.code = (int)APIErrCode.OperateFail;
                apiResp.msg  = "积分兑换金额不能大于订单总金额,请减少积分兑换";
                context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(apiResp));
                return;
            }

            if (orderInfo.TotalAmount < 0)
            {
                orderInfo.TotalAmount = 0;
            }
            if (orderInfo.TotalAmount == 0)
            {
                orderInfo.PaymentStatus = 1;
                orderInfo.PayTime       = DateTime.Now;
                orderInfo.Status        = "待发货";
            }
            orderInfo.HeadDiscount   = groupBuyRule.HeadDiscount;
            orderInfo.MemberDiscount = groupBuyRule.MemberDiscount;
            orderInfo.PeopleCount    = groupBuyRule.PeopleCount;
            orderInfo.ExpireDay      = groupBuyRule.ExpireDay;

            if (orderInfo.TotalAmount < needUseCash)
            {
                apiResp.code = (int)APIErrCode.OperateFail;
                apiResp.msg  = string.Format("最少需要支付{0}元" + needUseCash);
                context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(apiResp));
                return;
            }
            ZentCloud.ZCBLLEngine.BLLTransaction tran = new ZCBLLEngine.BLLTransaction();
            try
            {
                if (!this.bllMall.Add(orderInfo, tran))
                {
                    tran.Rollback();
                    apiResp.code = (int)APIErrCode.OperateFail;
                    apiResp.msg  = "提交失败";
                    context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(apiResp));
                    return;
                }

                #region 更新优惠券使用状态
                //优惠券
                if (orderRequestModel.cardcoupon_id > 0 && (canUseCardCoupon == true))//有优惠券且已经成功使用
                {
                    MyCardCoupons myCardCoupon = bllCardCoupon.GetMyCardCoupon(orderRequestModel.cardcoupon_id, CurrentUserInfo.UserID);
                    myCardCoupon.UseDate = DateTime.Now;
                    myCardCoupon.Status  = 1;
                    if (!bllCardCoupon.Update(myCardCoupon, tran))
                    {
                        tran.Rollback();
                        apiResp.code = (int)APIErrCode.OperateFail;
                        apiResp.msg  = "更新优惠券状态失败";
                        context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(apiResp));
                        return;
                    }
                }
                //优惠券
                #endregion

                #region 积分抵扣
                //积分扣除
                if (orderRequestModel.use_score > 0)
                {
                    CurrentUserInfo.TotalScore -= orderRequestModel.use_score;
                    if (bllMall.Update(CurrentUserInfo, string.Format(" TotalScore-={0}", orderRequestModel.use_score), string.Format(" AutoID={0}", CurrentUserInfo.AutoID), tran) < 0)
                    {
                        tran.Rollback();
                        apiResp.code = (int)APIErrCode.OperateFail;
                        apiResp.msg  = "更新用户积分失败";
                        context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(apiResp));
                        return;
                    }

                    //积分记录
                    UserScoreDetailsInfo scoreRecord = new UserScoreDetailsInfo();
                    scoreRecord.AddTime      = DateTime.Now;
                    scoreRecord.Score        = -orderRequestModel.use_score;
                    scoreRecord.TotalScore   = CurrentUserInfo.TotalScore;
                    scoreRecord.ScoreType    = "OrderSubmit";
                    scoreRecord.UserID       = CurrentUserInfo.UserID;
                    scoreRecord.AddNote      = "微商城-开团使用积分";
                    scoreRecord.WebSiteOwner = CurrentUserInfo.WebsiteOwner;
                    if (!bllMall.Add(scoreRecord, tran))
                    {
                        tran.Rollback();
                        apiResp.code = (int)APIErrCode.OperateFail;
                        apiResp.msg  = "插入积分记录失败";
                        context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(apiResp));
                        return;
                    }

                    #region 更新宏巍积分
                    if (websiteInfo.IsUnionHongware == 1)
                    {
                        if (!hongWareClient.UpdateMemberScore(hongWeiWareMemberInfo.member.mobile, CurrentUserInfo.WXOpenId, -orderRequestModel.use_score))
                        {
                            tran.Rollback();
                            apiResp.code = (int)APIErrCode.OperateFail;
                            apiResp.msg  = "更新宏巍积分失败";
                            context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(apiResp));
                            return;
                        }
                    }
                    #endregion
                }

                //积分扣除
                #endregion

                #region 余额抵扣

                if (orderRequestModel.use_amount > 0 && bllMall.IsEnableAccountAmountPay())
                {
                    CurrentUserInfo.AccountAmount -= orderRequestModel.use_amount;
                    if (bllMall.Update(CurrentUserInfo, string.Format(" AccountAmount={0}", CurrentUserInfo.AccountAmount), string.Format(" AutoID={0}", CurrentUserInfo.AutoID)) < 0)
                    {
                        tran.Rollback();
                        apiResp.code = (int)APIErrCode.OperateFail;
                        apiResp.msg  = "更新用户余额失败";
                        context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(apiResp));
                        return;
                    }


                    UserScoreDetailsInfo scoreRecord = new UserScoreDetailsInfo();
                    scoreRecord.AddTime      = DateTime.Now;
                    scoreRecord.Score        = -(double)orderRequestModel.use_amount;
                    scoreRecord.TotalScore   = (double)CurrentUserInfo.AccountAmount;
                    scoreRecord.UserID       = CurrentUserInfo.UserID;
                    scoreRecord.AddNote      = "拼团-开团使用余额";
                    scoreRecord.RelationID   = orderInfo.OrderID;
                    scoreRecord.WebSiteOwner = bllUser.WebsiteOwner;
                    scoreRecord.ScoreType    = "AccountAmount";
                    if (!bllMall.Add(scoreRecord))
                    {
                        tran.Rollback();
                        apiResp.code = (int)APIErrCode.OperateFail;
                        apiResp.msg  = "插入余额记录失败";
                        context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(apiResp));
                        return;
                    }

                    UserCreditAcountDetails record = new UserCreditAcountDetails();
                    record.WebsiteOwner = bllUser.WebsiteOwner;
                    record.Operator     = CurrentUserInfo.UserID;
                    record.UserID       = CurrentUserInfo.UserID;
                    record.CreditAcount = -orderRequestModel.use_amount;
                    record.SysType      = "AccountAmount";
                    record.AddTime      = DateTime.Now;
                    record.AddNote      = "账户余额变动-" + orderRequestModel.use_amount;
                    if (!bllMall.Add(record))
                    {
                        tran.Rollback();
                        apiResp.code = (int)APIErrCode.OperateFail;
                        apiResp.msg  = "插入余额记录失败";
                        context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(apiResp));
                        return;
                    }

                    #region 更新宏巍余额
                    if (websiteInfo.IsUnionHongware == 1)
                    {
                        if (!hongWareClient.UpdateMemberBlance(hongWeiWareMemberInfo.member.mobile, CurrentUserInfo.WXOpenId, -(float)orderRequestModel.use_amount))
                        {
                            tran.Rollback();
                            apiResp.code = (int)APIErrCode.OperateFail;
                            apiResp.msg  = "更新宏巍余额失败";
                            context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(resp));
                            return;
                        }
                    }
                    #endregion
                }


                #endregion

                #region 插入订单详情表及更新库存
                foreach (var item in detailList)
                {
                    ProductSku        productSku  = bllMall.GetProductSku((int)(item.SkuId));
                    WXMallProductInfo productInfo = bllMall.GetProduct(productSku.ProductId.ToString());
                    if (!this.bllMall.Add(item, tran))
                    {
                        tran.Rollback();

                        apiResp.code = (int)APIErrCode.OperateFail;
                        apiResp.msg  = "提交失败";
                        context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(apiResp));
                        return;
                    }
                    //更新 SKU库存
                    System.Text.StringBuilder sbUpdateStock = new StringBuilder();//更新库存sql
                    sbUpdateStock.AppendFormat(" Update ZCJ_ProductSku Set Stock-={0} ", item.TotalCount);

                    sbUpdateStock.AppendFormat(" Where SkuId={0} And Stock>0 ", productSku.SkuId);

                    if (ZentCloud.ZCBLLEngine.BLLBase.ExecuteSql(sbUpdateStock.ToString(), tran) <= 0)
                    {
                        tran.Rollback();

                        apiResp.code = (int)APIErrCode.OperateFail;
                        apiResp.msg  = "提交订单失败,库存不足";
                        context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(apiResp));
                        return;
                    }
                }
                #endregion



                bllMall.DeleteShoppingCart(CurrentUserInfo.UserID, orderRequestModel.skus);
                tran.Commit();//提交订单事务
                #region 宏巍通知
                if (websiteInfo.IsUnionHongware == 1)
                {
                    hongWareClient.OrderNotice(CurrentUserInfo.WXOpenId, orderInfo.OrderID);
                }
                #endregion


                #region 微信模板消息
                try
                {
                    string title = "订单已成功提交";
                    if (orderInfo.TotalAmount > 0)
                    {
                        title += ",请尽快付款";
                    }
                    bllWeiXin.SendTemplateMessageNotifyComm(CurrentUserInfo, title, string.Format("订单号:{0}\\n订单金额:{1}元\\n收货人:{2}\\n电话:{3}", orderInfo.OrderID, orderInfo.TotalAmount, orderInfo.Consignee, orderInfo.Phone));
                }
                catch
                {
                }
                #endregion
            }
            catch (Exception ex)
            {
                //回滚事物
                tran.Rollback();
                apiResp.code = (int)APIErrCode.OperateFail;
                apiResp.msg  = "提交订单失败";
                context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(apiResp));
                return;
            }
            apiResp.status = true;
            apiResp.msg    = "ok";
            apiResp.result = new
            {
                order_id = orderInfo.OrderID
            };

            context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(apiResp));
        }
Example #14
0
        public void ProcessRequest(HttpContext context)
        {
            try
            {
                Tolog("京东支付通知start");
                var    payConfig = bllPay.GetPayConfig();
                byte[] byts      = new byte[context.Request.InputStream.Length];
                context.Request.InputStream.Read(byts, 0, byts.Length);
                string req = Encoding.UTF8.GetString(byts);
                Tolog("通知参数" + req);

                //var jdPubKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCKE5N2xm3NIrXON8Zj19GNtLZ8xwEQ6uDIyrS3S03UhgBJMkGl4msfq4Xuxv6XUAN7oU1XhV3/xtabr9rXto4Ke3d6WwNbxwXnK5LSgsQc1BhT5NcXHXpGBdt7P8NMez5qGieOKqHGvT0qvjyYnYA29a8Z4wzNR7vAVHp36uD5RwIDAQAB";

                //req = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?><jdpay><version>V2.0</version><merchant>110226843002</merchant><result><code>000000</code><desc>success</desc></result><encrypt>MDIxZjNkNjI1YjU1NzQ4MWE5N2ExMTg3YjkxNmQ4NzkxYzQyMmFjZjM4YTM1MjZjY2JjNzM1ZDkxY2Q5ZDNmMTMzMGFjYTBkNTI0MzYzNjc3MTVhODI3OWUzZTAxMmY5ODEyOTVmNDNiNWY5MDZhZGJiYTcwYTYyOTFlYzVmYTU2Y2EyN2U1YzhkNzllMGE3ZTUyNDE4NWU4OWMxNjIwNDFkODcyYzJiZDA4ZWY4YWEyMmY5ZWUxNDk3YTg3MTI3YmU1NTMxNjc5NWJiOTlmN2ZmNGU1MTc1YWJhNjNkYjUzYWUwZDQzOTk4ZjIzMjBiYmVkNGJkMDcxOWUzOThjZjU1ODUwNzM4Y2RiNzM2Njc1N2U2ZTcxN2Q0N2ZiYTZmN2M1YzBiYzRmMjc4ZThiZDNhYTkxZTExNzBiYjg2ZDNjNmQ3OWUyZTBlYjUzZWNlZjFjODQ2MzdiN2E5MTQxN2Y3NmRhZmNkNDdiMzMwNjc1MGRhYjhiYzg0NTFkOWNiY2QyMDZhOTJiYzU2YTFiOWEwMjRmNTZhMWZhNTVhNjlmYTA1ZDFlMmI0YTI4MGE1YTU0N2NlMjc3ZWMwM2QyNWE4ODdlOTA0ZGM3YTY2MDViY2I1OTI5MDBlYWU4MGU0Mzc4MmEwOWY3ZjEwZTk5MGZkOGUzYTA4MzNkNGMyZGZkNWM3MDhkOGU4N2NhMmQyZGM1MDgwYzUyOTg3OGNkMzFhZWRkMTE1NDM5ZjExYTM2OGM2OGE4MGZjZTYyMjJkNzlmODcwNGYyNDMzMTYyZThhZTBkODM2ODBjYzg5ZGRjMWY3ZGVmYzQzYjc4MDZiMDNhMTBmZTc2YjI3MThjYjQ0YjQwZDkyY2E3OGUzYmYzZmFlNjBlOTI4OGU1ODVkNjBjMWZiNDBmMjFjNzVmNDkxYmRkYWFlNzQ0YjZkYmU1ODNkOWQ4OGYwN2EyMDViOWQ5MGNjMzViMTE3MDQ4NWVlNTdlN2Y5MTRhZDM3YzFlODY1NDFiZmQyNDg1MzhlZGZiNDNiZWZmZjY3YmE3NWQ5YjI0MzE4ZDMzMDE5NTE3YWM4ZTJiMDZhZWYyM2NhNjMwODc3MDhkNTdkZWI3MWVhMmY2MzA2ZDliZjBmZGFlNzQ3ODgzODg0ZjVhOWFkODIxYWM0NGQ1ZDlmMGRlNDhkMjBiYTJjYmQ4NTlkMmU3NDMxZDExZmRjMzkxMDU3ZmE3NGE0Yzg2OThkMmY0ZWQ1ZjE3MjIwOWQ1ZTBmZGIzZjFhNGYwOTllZWY5YzRiMWYyZDAxZjlhNzhlYWY5ZjU0YmIyZjczNmUxMjJkNWY2NzhlMDFmYjU0YjY3NWRlYTc1ZWZkNmMwNTJhZmY3ZGVhMGM5NjAyMWQwMGQyMjI2NzdhM2RlNDdhMTdkMWI4ZWQxYmEyYWZlZDg1ZjI4NDk2ZmI2MGVjOTc5OTc4MjgzZTEyNzY2ZmI1OWUzZjY1MWI4OTVlMmQ4OGNlNGRhODg0NzJiNTFiN2RmZDc5NzdkNDk4NTY0NGU4ZjBmNGZjMTM3MmUzMGNhMTUwOTFkNDFhODIzMjZiODU0YjMzNmI1N2EwZDVjMjZjOWNjMzBlMjFjZjNkMDA0NjQ4Zjk0NjQzZWRhOTU1MmIyZjJkYzZjNGJmOTU5MDIzNTBlODlmOTNhZDRhYmEyMzZiY2E1OWE4NzY5Mjc0ZTcwN2MyNGFjNGJmOTU5MDIzNTBlODlmNDNlZGE5NTUyYjJmMmRjNjU0MTNlZjYxZTNlODc4MDk3MmNiYjg3NTVjNmU1NWNlZDljNWU0ZDE5ZTRmZjJjZTAxNmJiMGIzYWFlOTdlYTQzYmM5NWVmMGU0ZjUyNzY4NDNlZGE5NTUyYjJmMmRjNmMyOWRiYWZkYTNjYzQ1M2E3ZGJhZWNjZWJmNGIxZmQ5MTMxMmRiMzliOTU2YzBmNmNiODMxMDQ1ZDBiYjM1ZTNmMzlmMGE0ODNiN2M3ODYyZjNjMTFiN2ZiODljNDNkMjE4NGFlNzU5M2JhMmQ2YTJkOWMwMmYxYTBlNTg2MzhkYzU0NzE0NjExNzkyNGU4ZjQ4NDgzMTAyNDY5OGRlNGZiMDVmNGQzNzE3NGMwOGI2NGU2NjkxMmU2NGY5M2I0YjNiMThmMzZiZmY0NTgwN2FjMDAxOWRlY2ZkYTcyOGFmNzIyZTQwNjhlMTViM2UwMmQzMmRiYjJkOTE2MmQzNWMzZWM2OGRkZjJjMjdmOTRhZGNmYzEzOTdlOWY0NjQwODFiYWU0Y2E3Y2NjZDY0NjQzNGFmZWU4ODExYWRiZTBlY2MwY2JlOThmNDliMDZkYjE2YjNjNTZhOTRiOGZkMDU=</encrypt></jdpay>";

                //req = Regex.Replace(req, @"[\t\n\r]", "", RegexOptions.IgnoreCase);

                req = req.Replace("\r", "").Replace("\n", "").Replace("\t", "");

                AsynNotifyResponse anyResponse = Payment.JDPay.XMLUtil.decryptResXml <AsynNotifyResponse>(Payment.JDPay.Config.JDPubKey, payConfig.JDPayDESKey, req);
                // System.Diagnostics.Debug.WriteLine("异步通知订单号:" + anyResponse.tradeNum + ",状态:" + anyResponse.status);
                Tolog("异步通知订单号:" + anyResponse.tradeNum + ",状态:" + anyResponse.status);
                var orderId   = anyResponse.tradeNum;
                var orderInfo = bllMall.GetOrderInfo(orderId);
                if (orderInfo == null)
                {
                    //context.Response.Write("订单未找到");
                    context.Response.StatusCode = 500;
                    context.Response.Write(failStr);
                    return;
                }
                if (orderInfo.PaymentStatus.Equals(1))
                {
                    //Tolog("已支付");
                    // context.Response.Write("订单已支付");
                    context.Response.StatusCode = 200;
                    context.Response.Write(successStr);
                    return;
                }



                if (anyResponse.status == "2")
                {
                    orderInfo.PaymentType = 3;

                    //支付成功
                    WXMallProductInfo tProductInfo  = new WXMallProductInfo();
                    UserInfo          orderUserInfo = bllUser.GetUserInfo(orderInfo.OrderUserID, orderInfo.WebsiteOwner);//下单用户信息
                    string            hasOrderIDs   = "";
                    int maxCount = 1;
                    //Tolog("准备检查更新订单状态");
                    if (BLLJIMP.BLLMall.bookingList.Contains(orderInfo.ArticleCategoryType))
                    {
                        //Tolog("预订类型");
                        #region 预约订单修改状态
                        orderInfo.PaymentStatus = 1;
                        orderInfo.PayTime       = DateTime.Now;
                        orderInfo.Status        = "预约成功";

                        #region 检查是否有预约成功的订单
                        List <WXMallOrderDetailsInfo> tDetailList = bllMall.GetOrderDetailsList(orderInfo.OrderID, null, orderInfo.ArticleCategoryType, null, null);
                        List <WXMallOrderDetailsInfo> oDetailList = bllMall.GetOrderDetailsList(null, tDetailList[0].PID, orderInfo.ArticleCategoryType, tDetailList.Min(p => p.StartDate), tDetailList.Max(p => p.EndDate));
                        tProductInfo = bllMall.GetByKey <WXMallProductInfo>("PID", tDetailList[0].PID);
                        maxCount     = tProductInfo.Stock;
                        List <string> hasOrderIDList = new List <string>();
                        foreach (var item in tDetailList)
                        {
                            List <WXMallOrderDetailsInfo> hasOrderDetailList = oDetailList.Where(p => !((item.StartDate >= p.EndDate && item.EndDate > p.EndDate) || (item.StartDate < p.StartDate && item.EndDate <= p.StartDate))).ToList();
                            if (hasOrderDetailList.Count >= maxCount)
                            {
                                hasOrderIDList.AddRange(hasOrderDetailList.Select(p => p.OrderID).Distinct());
                            }
                        }
                        hasOrderIDList = hasOrderIDList.Where(p => !p.Contains(orderInfo.OrderID)).ToList();
                        if (hasOrderIDList.Count > 0)
                        {
                            hasOrderIDList = hasOrderIDList.Distinct().ToList();
                            hasOrderIDs    = MyStringHelper.ListToStr(hasOrderIDList, "'", ",");
                        }
                        #endregion 检查是否有预约成功的订单

                        #endregion 预约订单修改状态
                    }
                    else
                    {
                        //Tolog("普通类型");
                        #region 原订单修改状态
                        orderInfo.PaymentStatus = 1;
                        orderInfo.Status        = "待发货";
                        orderInfo.PayTime       = DateTime.Now;
                        Tolog("更改状态start");
                        //if (bllMall.GetWebsiteInfoModelFromDataBase().IsDistributionMall.Equals(1))
                        //{
                        orderInfo.GroupBuyStatus     = "0";
                        orderInfo.DistributionStatus = 1;

                        #region 拼团订单
                        if (orderInfo.OrderType == 2)
                        {
                            try
                            {
                                if (!string.IsNullOrEmpty(orderInfo.GroupBuyParentOrderId))
                                {
                                    var parentOrderInfo = bllMall.GetOrderInfo(orderInfo.GroupBuyParentOrderId);

                                    if (bllMall.GetCount <WXMallOrderInfo>(string.Format("PaymentStatus=1 And GroupBuyParentOrderId='{0}' Or OrderId='{0}'", parentOrderInfo.OrderID)) >= parentOrderInfo.PeopleCount)
                                    {
                                        bllMall.Update(new WXMallOrderInfo(), string.Format("Status='已取消'"), string.Format("  GroupBuyParentOrderId='{0}' And PaymentStatus=0", parentOrderInfo.OrderID));
                                        parentOrderInfo.GroupBuyStatus = "1";
                                        bllMall.Update(parentOrderInfo);
                                    }
                                }
                            }
                            catch (Exception)
                            {
                            }
                        }
                        #endregion

                        #region 活动订单
                        if (orderInfo.OrderType == 4)
                        {
                            ActivityDataInfo data = bllMall.Get <ActivityDataInfo>(string.Format(" OrderId='{0}'", orderInfo.OrderID));
                            if (data != null)
                            {
                                bllMall.Update(data, string.Format(" PaymentStatus=1"), string.Format("  OrderId='{0}'", orderInfo.OrderID));
                            }
                        }
                        #endregion

                        bllMall.Update(orderInfo, string.Format("PaymentStatus=1,Status='待发货',PayTime=GETDATE(),DistributionStatus=1"), string.Format("ParentOrderId='{0}'", orderInfo.OrderID));

                        //}
                        #endregion 原订单修改状态

                        //orderInfo.PayTranNo = tradeNo;
                    }
                    bool result = false;

                    if (BLLJIMP.BLLMall.bookingList.Contains(orderInfo.ArticleCategoryType))
                    {
                        if (string.IsNullOrWhiteSpace(hasOrderIDs))
                        {
                            hasOrderIDs = "'0'";
                        }
                        result = bllMall.Update(new WXMallOrderInfo(),
                                                string.Format("PaymentStatus={0},PayTime=GetDate(),Status='{1}'", 1, "预约成功"),
                                                string.Format("OrderID='{0}' and WebsiteOwner='{4}' AND (select count(1) from [ZCJ_WXMallOrderInfo] where Status='{3}' and WebsiteOwner='{4}' and  OrderID IN({1}))<{2}",
                                                              orderInfo.OrderID, hasOrderIDs, maxCount, "预约成功", bllMall.WebsiteOwner)
                                                ) > 0;
                        if (result)
                        {
                            // #region 交易成功加积分
                            //增加积分 (慧聚不需要)
                            //if (orderInfo.TotalAmount > 0)
                            //{
                            //    ScoreConfig scoreConfig = bllScore.GetScoreConfig();
                            //    int addScore = 0;
                            //    if (scoreConfig != null && scoreConfig.OrderAmount > 0 && scoreConfig.OrderScore > 0)
                            //    {
                            //        addScore = (int)(orderInfo.PayableAmount / (scoreConfig.OrderAmount / scoreConfig.OrderScore));
                            //    }
                            //    if (addScore > 0)
                            //    {
                            //        if (bllUser.Update(new UserInfo(),
                            //            string.Format(" TotalScore+={0},HistoryTotalScore+={0}", addScore),
                            //            string.Format(" UserID='{0}'", orderInfo.OrderUserID)) > 0)
                            //        {
                            //            UserScoreDetailsInfo scoreRecord = new UserScoreDetailsInfo();
                            //            scoreRecord.AddTime = DateTime.Now;
                            //            scoreRecord.Score = addScore;
                            //            scoreRecord.ScoreType = "OrderSuccess";
                            //            scoreRecord.UserID = orderInfo.OrderUserID;
                            //            scoreRecord.AddNote = "预约-交易成功获得积分";
                            //            bllMall.Add(scoreRecord);
                            //        }
                            //    }
                            //}
                            // #endregion

                            #region 修改其他预约订单为预约失败 返还积分

                            if (BLLJIMP.BLLMall.bookingList.Contains(orderInfo.ArticleCategoryType) && !string.IsNullOrWhiteSpace(hasOrderIDs))
                            {
                                int tempCount = 0;
                                List <WXMallOrderInfo> tempList = bllMall.GetOrderList(0, 1, "", out tempCount, "预约成功", null, null, null,
                                                                                       null, null, null, null, null, null, null, orderInfo.ArticleCategoryType, hasOrderIDs);
                                tempCount = tempCount + 1; //加上当前订单的数量
                                if (tempCount >= maxCount)
                                {
                                    tempList = bllMall.GetColOrderListInStatus("'待付款','待审核'", hasOrderIDs, "OrderID,OrderUserID,UseScore", bllMall.WebsiteOwner);
                                    if (tempList.Count > 0)
                                    {
                                        string stopOrderIds = MyStringHelper.ListToStr(tempList.Select(p => p.OrderID).ToList(), "'", ",");
                                        tempList = tempList.Where(p => p.UseScore > 0).ToList();
                                        foreach (var item in tempList)
                                        {
                                            orderUserInfo.TotalScore += item.UseScore;
                                            if (bllUser.Update(new UserInfo(), string.Format(" TotalScore+={0}", item.UseScore),
                                                               string.Format(" UserID='{0}'", item.OrderUserID)) > 0)
                                            {
                                                UserScoreDetailsInfo scoreRecord = new UserScoreDetailsInfo();
                                                scoreRecord.AddTime      = DateTime.Now;
                                                scoreRecord.Score        = item.UseScore;
                                                scoreRecord.TotalScore   = orderUserInfo.TotalScore;
                                                scoreRecord.ScoreType    = "OrderCancel";
                                                scoreRecord.UserID       = item.OrderUserID;
                                                scoreRecord.RelationID   = item.OrderID;
                                                scoreRecord.AddNote      = "预约-订单失败返还积分";
                                                scoreRecord.WebSiteOwner = item.WebsiteOwner;
                                                bllMall.Add(scoreRecord);
                                            }
                                        }
                                        bllMall.Update(new WXMallOrderInfo(),
                                                       string.Format("Status='{0}'", "预约失败"),
                                                       string.Format("OrderID In ({0}) and WebsiteOwner='{1}'", stopOrderIds, bllMall.WebsiteOwner));
                                    }
                                }
                                //Tolog("更改修改其他预约为预约失败");
                            }
                            #endregion
                        }
                    }
                    else
                    {
                        result = bllMall.Update(orderInfo);
                    }
                    if (result)
                    {
                        Open.HongWareSDK.Client hongWareClient = new Open.HongWareSDK.Client(orderInfo.WebsiteOwner);

                        //Tolog("更改状态true");

                        #region Efast同步
                        //判读当前站点是否需要同步到驿氪和efast
                        if (bllCommRelation.ExistRelation(BLLJIMP.Enums.CommRelationType.SyncEfast, bllCommRelation.WebsiteOwner, ""))
                        {
                            try
                            {
                                Tolog("开始同步efast");

                                string outOrderId = string.Empty, msg = string.Empty;
                                var    syncResult = bllEfast.CreateOrder(orderInfo.OrderID, out outOrderId, out msg);
                                if (syncResult)
                                {
                                    orderInfo.OutOrderId = outOrderId;
                                    bllMall.Update(orderInfo);
                                }
                                Tolog(string.Format("efast订单同步结果:{0},订单号:{1},提示信息:{2}", syncResult, outOrderId, msg));
                            }
                            catch (Exception ex)
                            {
                                Tolog("efast订单同步异常:" + ex.Message);
                            }
                        }
                        #endregion

                        #region 驿氪同步
                        if (bllCommRelation.ExistRelation(BLLJIMP.Enums.CommRelationType.SyncYike, bllCommRelation.WebsiteOwner, ""))
                        {
                            try
                            {
                                Tolog("开始同步驿氪");
                                //同步成功订单到驿氪

                                //UserInfo orderUserInfo = bllUser.GetUserInfo(orderInfo.OrderUserID);
                                //if ((!string.IsNullOrEmpty(orderUserInfo.Ex1)) && (!string.IsNullOrEmpty(orderUserInfo.Ex2)) && (!string.IsNullOrEmpty(orderUserInfo.Phone)))
                                //{
                                //    client.BonusUpdate(orderUserInfo.Ex2, -(orderInfo.UseScore), "商城下单使用积分" + orderInfo.UseScore);

                                //}
                                var uploadOrderResult = yikeClient.OrderUpload(orderInfo);

                                Tolog(string.Format("驿氪订单同步结果:{0}", Common.JSONHelper.ObjectToJson(uploadOrderResult)));
                            }
                            catch (Exception ex)
                            {
                                Tolog("驿氪订单同步异常:" + ex.Message);
                            }
                        }
                        #endregion

                        #region 付款加积分
                        try
                        {
                            bllUser.AddUserScoreDetail(orderInfo.OrderUserID, CommonPlatform.Helper.EnumStringHelper.ToString(ZentCloud.BLLJIMP.Enums.ScoreDefineType.OrderPay), bllMall.WebsiteOwner, null, null);
                        }
                        catch (Exception)
                        { }

                        #endregion


                        #region 消息通知
                        if (!BLLJIMP.BLLMall.bookingList.Contains(orderInfo.ArticleCategoryType))
                        {
                            try
                            {
                                var    productName = bllMall.GetOrderDetailsList(orderInfo.OrderID)[0].ProductName;
                                string remark      = "";
                                if (!string.IsNullOrEmpty(orderInfo.OrderMemo))
                                {
                                    remark = string.Format("客户留言:{0}", orderInfo.OrderMemo);
                                }
                                bllWeiXin.SendTemplateMessageToKefu("有新的订单", string.Format("订单号:{0}\\n订单金额:{1}元\\n收货人:{2}\\n电话:{3}\\n商品:{4}\\n{5}", orderInfo.OrderID, orderInfo.TotalAmount, orderInfo.Consignee, orderInfo.Phone, productName, remark));
                                if (orderInfo.OrderType != 4)//付费的活动不发消息
                                {
                                    if (orderInfo.WebsiteOwner != "jikuwifi")
                                    {
                                        string url = string.Format("http://{0}/customize/shop/?v=1.0&ngroute=/orderDetail/{1}#/orderDetail/{1}", context.Request.Url.Host, orderInfo.OrderID);
                                        bllWeiXin.SendTemplateMessageNotifyComm(orderUserInfo, "订单已成功支付,我们将尽快发货,请保持手机畅通等待物流送达!", string.Format("订单号:{0}\\n订单金额:{1}元\\n收货人:{2}\\n电话:{3}\\n商品:{4}...\\n查看详情", orderInfo.OrderID, orderInfo.TotalAmount, orderInfo.Consignee, orderInfo.Phone, productName), url);
                                    }
                                }
                            }
                            catch (Exception)
                            {
                            }
                        }
                        else
                        {
                            try
                            {
                                bllWeiXin.SendTemplateMessageToKefu(orderInfo.Status, string.Format("预约:{2}\\n订单号:{0}\\n订单金额:{1}元\\n预约人:{3}\\n预约人手机:{4}", orderInfo.OrderID, orderInfo.TotalAmount, tProductInfo.PName, orderUserInfo.TrueName, orderUserInfo.Phone));
                                bllWeiXin.SendTemplateMessageNotifyComm(orderUserInfo, orderInfo.Status, string.Format("预约:{2}\\n订单号:{0}\\n订单金额:{1}元", orderInfo.OrderID, orderInfo.TotalAmount, tProductInfo.PName));
                            }
                            catch (Exception)
                            {
                            }
                        }
                        #endregion
                        WebsiteInfo websiteInfo = bllMall.Get <WebsiteInfo>(string.Format(" WebsiteOwner='{0}'", orderInfo.WebsiteOwner));
                        #region 分销相关
                        try
                        {
                            if (bllMenuPermission.CheckUserAndPmsKey(websiteInfo.WebsiteOwner, BLLPermission.Enums.PermissionSysKey.OnlineDistribution, websiteInfo.WebsiteOwner))
                            {
                                if (string.IsNullOrWhiteSpace(orderUserInfo.DistributionOwner))
                                {
                                    if (websiteInfo.DistributionRelationBuildMallOrder == 1)
                                    {
                                        orderUserInfo.DistributionOwner = bllMall.WebsiteOwner;
                                        bllMall.Update(orderUserInfo);
                                    }
                                }

                                bllDis.AutoUpdateLevel(orderInfo);
                                bllDis.TransfersEstimate(orderInfo);
                                bllDis.SendMessageToUser(orderInfo);
                                bllDis.UpdateDistributionSaleAmountUp(orderInfo);
                            }
                        }
                        catch (Exception ex)
                        {
                            Tolog("设置分销员异常:" + ex.Message + " 用户id:" + orderUserInfo.UserID);
                        }
                        #endregion


                        #region 宏巍通知
                        try
                        {
                            if (websiteInfo.IsUnionHongware == 1)
                            {
                                hongWareClient.OrderNotice(orderUserInfo.WXOpenId, orderInfo.OrderID);
                            }
                        }
                        catch (Exception)
                        {
                        }

                        #endregion

                        bllCard.Give(orderInfo.TotalAmount, orderUserInfo);


                        string v1ProductId = Common.ConfigHelper.GetConfigString("YGBV1ProductId");
                        string v2ProductId = Common.ConfigHelper.GetConfigString("YGBV2ProductId");
                        string v1CouponId  = Common.ConfigHelper.GetConfigString("YGBV1CouponId");
                        string v2CouponId  = Common.ConfigHelper.GetConfigString("YGBV2CouponId");

                        List <WXMallOrderDetailsInfo> orderDetailList = bllMall.GetOrderDetailsList(orderInfo.OrderID);
                        foreach (var item in orderDetailList)
                        {
                            item.IsComplete = 1;
                            bllMall.Update(item);
                            #region 购买指定商品发送指定的优惠券
                            if (!string.IsNullOrEmpty(v1ProductId) && !string.IsNullOrEmpty(v1CouponId) && item.PID == v1ProductId)
                            {
                                bllCard.SendCardCouponsByCurrUserInfo(orderUserInfo, v1CouponId);
                            }

                            if (!string.IsNullOrEmpty(v2ProductId) && !string.IsNullOrEmpty(v2CouponId) && item.PID == v2ProductId)
                            {
                                bllCard.SendCardCouponsByCurrUserInfo(orderUserInfo, v2CouponId);
                            }
                            #endregion
                        }
                        //更新销量
                        bllMall.UpdateProductSaleCount(orderInfo);

                        context.Response.StatusCode = 200;
                        context.Response.Write(successStr);
                        Tolog("支付成功" + orderInfo.OrderID);
                        return;
                    }
                    else
                    {
                        Tolog("更改状态false");
                        context.Response.StatusCode = 500;
                        context.Response.Write(failStr);
                        return;
                    }
                }
            }
            catch (Exception ex)
            {
                //error = "fail";
                Tolog("京东支付异常:" + ex.ToString());
            }

            context.Response.ContentType = "text/plain";
            context.Response.StatusCode  = 500;
            context.Response.Write(failStr);
        }
Example #15
0
File: Add.ashx.cs Project: uvbs/mmp
        public void ProcessRequest(HttpContext context)
        {
            WebsiteInfo websiteInfo = bllMall.GetWebsiteInfoModelFromDataBase();

            Open.HongWareSDK.Client     hongWareClient        = new Open.HongWareSDK.Client(websiteInfo.WebsiteOwner);
            Open.HongWareSDK.MemberInfo hongWeiWareMemberInfo = null;
            if (websiteInfo.IsUnionHongware == 1)
            {
                hongWeiWareMemberInfo = hongWareClient.GetMemberInfo(CurrentUserInfo.WXOpenId);
                if (hongWeiWareMemberInfo.member == null)
                {
                    resp.errcode = 1;
                    resp.errmsg  = "您尚未绑定宏巍账号,请先绑定";
                    context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(resp));
                    return;
                }
            }
            string            data              = context.Request["data"];
            decimal           productFee        = 0;                       //商品总价格 不包含邮费
            OrderRequestModel orderRequestModel = new OrderRequestModel(); //订单模型

            try
            {
                orderRequestModel = ZentCloud.Common.JSONHelper.JsonToModel <OrderRequestModel>(data);
            }
            catch (Exception ex)
            {
                resp.errcode = 1;
                resp.errmsg  = "JSON格式错误,请检查。错误信息:" + ex.Message;
                context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(resp));
                return;
            }
            WXMallOrderInfo orderInfo = new WXMallOrderInfo();//订单表

            orderInfo.InsertDate    = DateTime.Now;
            orderInfo.OrderUserID   = CurrentUserInfo.UserID;
            orderInfo.WebsiteOwner  = bllMall.WebsiteOwner;
            orderInfo.Transport_Fee = 0;
            orderInfo.OrderID       = bllMall.GetGUID(BLLJIMP.TransacType.AddMallOrder);
            if (bllMall.WebsiteOwner != "mixblu")
            {
                orderInfo.OutOrderId = orderInfo.OrderID;
            }
            orderInfo.OrderMemo      = orderRequestModel.buyer_memo;
            orderInfo.MyCouponCardId = orderRequestModel.cardcoupon_id.ToString();
            orderInfo.UseScore       = orderRequestModel.use_score;
            orderInfo.UseAmount      = orderRequestModel.use_amount;
            orderInfo.Status         = "待付款";
            orderInfo.OrderType      = 1;
            orderInfo.LastUpdateTime = DateTime.Now;
            if (orderRequestModel.pay_type == "WEIXIN")//微信支付
            {
                orderInfo.PaymentType = 2;
            }
            else if (orderRequestModel.pay_type == "ALIPAY")//支付宝支付
            {
                orderInfo.PaymentType = 1;
            }

            #region 格式检查
            //相关检查
            if (orderRequestModel.skus == null)
            {
                resp.errcode = 1;
                resp.errmsg  = "参数skus 不能为空";
                context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(resp));
                return;
            }
            if (orderRequestModel.skus.Count > 1)
            {
                resp.errcode = 1;
                resp.errmsg  = "只能购买一个商品";
                context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(resp));
                return;
            }

            //相关检查
            #endregion

            #region 商品检查 订单详情生成
            ///订单详情
            List <WXMallOrderDetailsInfo> detailList = new List <WXMallOrderDetailsInfo>();//订单详情
            orderRequestModel.skus = orderRequestModel.skus.Distinct().ToList();

            #region 购买的商品
            List <WXMallProductInfo> productList = new List <WXMallProductInfo>();
            foreach (var sku in orderRequestModel.skus)
            {
                ProductSku productSku = bllMall.GetProductSku(sku.sku_id);

                if (productSku == null)
                {
                    continue;
                }
                if (productList.Count(p => p.PID == productSku.ProductId.ToString()) > 0)
                {
                    continue;
                }

                WXMallProductInfo productInfo = bllMall.GetProduct(productSku.ProductId.ToString());
                productList.Add(productInfo);
            }
            //productList = productList.Distinct().ToList();
            #endregion


            #region 检查优惠券是否可用
            if (orderRequestModel.cardcoupon_id > 0)
            {
                var mycardCoupon = bllCardCoupon.GetMyCardCoupon(orderRequestModel.cardcoupon_id, CurrentUserInfo.UserID);
                if (mycardCoupon == null)
                {
                    resp.errcode = 1;
                    resp.errmsg  = "无效的优惠券";
                    context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(resp));
                    return;
                }
                var cardCoupon = bllCardCoupon.GetCardCoupon(mycardCoupon.CardId);
                if (cardCoupon == null)
                {
                    resp.errcode = 1;
                    resp.errmsg  = "无效的优惠券";
                    context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(resp));
                    return;
                }
                #region 需要购买指定商品
                if ((!string.IsNullOrEmpty(cardCoupon.Ex2)) && (cardCoupon.Ex2 != "0"))
                {
                    if (productList.Count(p => p.PID == cardCoupon.Ex2) == 0)
                    {
                        var productInfo = bllMall.GetProduct(cardCoupon.Ex2);
                        resp.errcode = 1;
                        resp.errmsg  = string.Format("此优惠券需要购买{0}时才可以使用", productInfo.PName);
                        context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(resp));
                        return;
                    }
                }
                #endregion

                #region 需要购买指定标签商品
                if (!string.IsNullOrEmpty(cardCoupon.Ex8))
                {
                    if (productList.Where(p => p.Tags == "" || p.Tags == null).Count() == productList.Count)//全部商品都没有标签
                    {
                        resp.errcode = 1;
                        resp.errmsg  = string.Format("使用此优惠券需要购买标签为{0}的商品", cardCoupon.Ex8);
                        context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(resp));
                        return;
                    }
                    bool checkResult = true;
                    foreach (var product in productList)
                    {
                        if (!string.IsNullOrEmpty(product.Tags))
                        {
                            bool tempResult = false;
                            foreach (string tag in product.Tags.Split(','))
                            {
                                if (cardCoupon.Ex8.Contains(tag))
                                {
                                    tempResult = true;
                                    break;
                                }
                            }
                            if (!tempResult)
                            {
                                checkResult = false;
                                break;
                            }
                        }
                        else//商品不包含标签
                        {
                            checkResult = false;
                            break;
                        }
                    }
                    if (!checkResult)
                    {
                        resp.errcode = 1;
                        resp.errmsg  = string.Format("使用此优惠券需要购买标签为{0}的商品", cardCoupon.Ex8);
                        context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(resp));
                        return;
                    }
                }
                #endregion
            }
            #endregion

            var     needUseScore = 0; //必须使用的积分
            decimal needUseCash  = 0; //必须使用的现金
            foreach (var sku in orderRequestModel.skus)
            {
                //先检查库存
                ProductSku productSku = bllMall.GetProductSku(sku.sku_id);
                if (productSku == null)
                {
                    resp.errcode = 1;
                    resp.errmsg  = "SKU不存在";
                    context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(resp));
                    return;
                }

                //WXMallProductInfo productInfo = bllMall.GetProduct(productSku.ProductId.ToString());
                WXMallProductInfo productInfo = productList.Single(p => p.PID == productSku.ProductId.ToString());
                if (productInfo.IsOnSale == "0")
                {
                    resp.errcode = 1;
                    resp.errmsg  = string.Format("{0}已下架", productInfo.PName);
                    context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(resp));
                    return;
                }
                if (bllMall.GetSkuCount(productSku) < sku.count)
                {
                    resp.errcode = 1;
                    resp.errmsg  = string.Format("{0}{1}库存余量为{2},库存不足,请减少购买数量", productInfo.PName, bllMall.GetProductShowProperties(productSku.SkuId), productSku.Stock);
                    context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(resp));
                    return;
                }
                if (bllMall.IsPromotionTime(productSku))
                {
                    if (sku.count > productSku.PromotionStock)
                    {
                        resp.errcode = 1;
                        resp.errmsg  = string.Format("{0}{1}特卖库存余量为{2},库存不足,请减少购买数量", productInfo.PName, bllMall.GetProductShowProperties(productSku.SkuId), productSku.PromotionStock);
                        context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(resp));
                        return;
                    }
                }
                if (productInfo.Score > 0)//必须使用的积分
                {
                    needUseScore += sku.count * productInfo.Score;
                }
                if (productInfo.IsCashPayOnly == 1)//必须使用的现金
                {
                    needUseCash += bllMall.GetSkuPrice(productSku) * sku.count;
                }
                WXMallOrderDetailsInfo detailModel = new WXMallOrderDetailsInfo();
                detailModel.OrderID     = orderInfo.OrderID;
                detailModel.PID         = productInfo.PID;
                detailModel.TotalCount  = sku.count;
                detailModel.OrderPrice  = bllMall.GetSkuPrice(productSku);
                detailModel.ProductName = productInfo.PName;
                detailModel.SkuId       = productSku.SkuId;
                detailModel.SkuShowProp = bllMall.GetProductShowProperties(productSku.SkuId);
                detailList.Add(detailModel);
            }
            #endregion

            #region 纯积分购买
            if (needUseScore > 0)
            {
                if ((CurrentUserInfo.TotalScore < needUseScore) || (orderRequestModel.use_score < needUseScore))
                {
                    resp.errcode = 1;
                    resp.errmsg  = string.Format("您需要使用{0}积分来兑换, 可用积分不足", needUseScore);
                    context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(resp));
                    return;
                }
            }
            #endregion
            productFee = detailList.Sum(p => p.OrderPrice * p.TotalCount).Value;//商品费用

            //物流费用
            //#region 运费计算
            //FreightModel freightModel = new FreightModel();
            //freightModel.skus = orderRequestModel.skus;
            //decimal freight = 0;//运费
            //string freightMsg = "";
            //if (!bllMall.CalcFreight(freightModel, out freight, out  freightMsg))
            //{
            //    resp.errcode = 1;
            //    resp.errmsg = freightMsg;
            //    context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(resp));
            //    return;

            //}
            //orderInfo.Transport_Fee = freight;
            //#endregion

            #region 优惠券计算
            decimal discountAmount   = 0;//优惠金额
            bool    canUseCardCoupon = false;
            string  msg = "";
            if (orderRequestModel.cardcoupon_id > 0)//有优惠券
            {
                discountAmount = bllMall.CalcDiscountAmount(orderRequestModel.cardcoupon_id.ToString(), data, CurrentUserInfo.UserID, out canUseCardCoupon, out msg);
                if (!canUseCardCoupon)
                {
                    resp.errcode = 1;
                    resp.errmsg  = msg;
                    context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(resp));
                    return;
                }
                //if (discountAmount > productFee + orderInfo.Transport_Fee)
                //{
                //    resp.errcode = 1;
                //    resp.errmsg = "优惠券可优惠金额超过了订单总金额";
                //    context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(resp));
                //    return;

                //}
            }
            //优惠券计算
            #endregion


            #region 积分计算
            decimal scoreExchangeAmount = 0;///积分抵扣的金额
            //积分计算
            if (orderRequestModel.use_score > 0)
            {
                #region 使用宏巍积分
                if (websiteInfo.IsUnionHongware == 1)
                {
                    CurrentUserInfo.TotalScore = hongWeiWareMemberInfo.member.point;
                }
                #endregion
                if (CurrentUserInfo.TotalScore < orderRequestModel.use_score)
                {
                    resp.errcode = 1;
                    resp.errmsg  = "积分不足";
                    context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(resp));
                    return;
                }



                ScoreConfig scoreConfig = bllScore.GetScoreConfig();
                if (scoreConfig == null)
                {
                    resp.errcode = 1;
                    resp.errmsg  = "未配置积分兑换";
                    context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(resp));
                    return;
                }
                if (scoreConfig.ExchangeScore == 0 || scoreConfig.ExchangeAmount == 0)
                {
                    resp.errcode = 1;
                    resp.errmsg  = "未配置积分兑换";
                    context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(resp));
                    return;
                }
                scoreExchangeAmount = Math.Round(orderRequestModel.use_score / (scoreConfig.ExchangeScore / scoreConfig.ExchangeAmount), 2);
            }



            //积分计算
            #endregion

            #region 使用账户余额
            if (orderRequestModel.use_amount > 0)
            {
                if (!bllMall.IsEnableAccountAmountPay())
                {
                    resp.errcode = 1;
                    resp.errmsg  = "尚未启用余额支付功能";
                    context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(resp));
                    return;
                }
                #region 使用宏巍余额
                if (websiteInfo.IsUnionHongware == 1)
                {
                    CurrentUserInfo.AccountAmount = (decimal)hongWeiWareMemberInfo.member.balance;
                }
                #endregion

                if (CurrentUserInfo.AccountAmount < orderRequestModel.use_amount)
                {
                    resp.errcode = 1;
                    resp.errmsg  = "您的账户余额不足";
                    context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(resp));
                    return;
                }
            }
            #endregion


            //合计计算
            orderInfo.Product_Fee         = productFee;
            orderInfo.TotalAmount         = orderInfo.Product_Fee + orderInfo.Transport_Fee;
            orderInfo.TotalAmount        -= discountAmount;               //优惠券优惠金额
            orderInfo.TotalAmount        -= scoreExchangeAmount;          //积分优惠金额
            orderInfo.TotalAmount        -= orderRequestModel.use_amount; //余额
            orderInfo.PayableAmount       = orderInfo.TotalAmount;        //应付金额
            orderInfo.ScoreExchangAmount  = scoreExchangeAmount;          //优惠券抵扣金额
            orderInfo.CardcouponDisAmount = discountAmount;               //卡券抵扣金额
            if ((productFee + orderInfo.Transport_Fee - discountAmount - scoreExchangeAmount) < orderInfo.TotalAmount)
            {
                resp.errcode = 1;
                resp.errmsg  = "积分兑换金额不能大于订单总金额,请减少积分兑换";
                context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(resp));
                return;
            }
            if (orderInfo.TotalAmount < 0)
            {
                orderInfo.TotalAmount = 0;
            }
            if (orderInfo.TotalAmount == 0)
            {
                orderInfo.PaymentStatus = 1;
                orderInfo.PayTime       = DateTime.Now;
                orderInfo.Status        = "待发货";
            }
            if (orderInfo.TotalAmount < needUseCash)
            {
                resp.errcode = 1;
                resp.errmsg  = string.Format("最少需要支付{0}元" + needUseCash);
                context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(resp));
                return;
            }
            ZentCloud.ZCBLLEngine.BLLTransaction tran = new ZCBLLEngine.BLLTransaction();
            try
            {
                if (!this.bllMall.Add(orderInfo, tran))
                {
                    tran.Rollback();
                    resp.errcode = 1;
                    resp.errmsg  = "提交失败";
                    context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(resp));
                    return;
                }

                #region 更新优惠券使用状态
                //优惠券
                if (orderRequestModel.cardcoupon_id > 0 && (canUseCardCoupon == true))//有优惠券且已经成功使用
                {
                    MyCardCoupons myCardCoupon = bllCardCoupon.GetMyCardCoupon(orderRequestModel.cardcoupon_id, CurrentUserInfo.UserID);
                    myCardCoupon.UseDate = DateTime.Now;
                    myCardCoupon.Status  = 1;
                    if (!bllCardCoupon.Update(myCardCoupon, tran))
                    {
                        tran.Rollback();
                        resp.errcode = 1;
                        resp.errmsg  = "更新优惠券状态失败";
                        context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(resp));
                        return;
                    }
                }
                //优惠券
                #endregion

                #region 积分抵扣
                //积分扣除
                if (orderRequestModel.use_score > 0)
                {
                    CurrentUserInfo.TotalScore -= orderRequestModel.use_score;
                    if (

                        bllMall.Update(CurrentUserInfo, string.Format(" TotalScore-={0}", orderRequestModel.use_score), string.Format(" AutoID={0}", CurrentUserInfo.AutoID)) < 0)
                    {
                        tran.Rollback();
                        resp.errcode = 1;
                        resp.errmsg  = "更新用户积分失败";
                        context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(resp));
                        return;
                    }

                    //积分记录
                    UserScoreDetailsInfo scoreRecord = new UserScoreDetailsInfo();
                    scoreRecord.AddTime      = DateTime.Now;
                    scoreRecord.Score        = -orderRequestModel.use_score;
                    scoreRecord.TotalScore   = CurrentUserInfo.TotalScore;
                    scoreRecord.ScoreType    = "OrderSubmit";
                    scoreRecord.UserID       = CurrentUserInfo.UserID;
                    scoreRecord.AddNote      = "微商城-下单使用积分";
                    scoreRecord.WebSiteOwner = CurrentUserInfo.WebsiteOwner;
                    if (!bllMall.Add(scoreRecord))
                    {
                        tran.Rollback();
                        resp.errcode = 1;
                        resp.errmsg  = "插入积分记录失败";
                        context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(resp));
                        return;
                    }

                    #region 更新宏巍积分
                    if (websiteInfo.IsUnionHongware == 1)
                    {
                        if (!hongWareClient.UpdateMemberScore(hongWeiWareMemberInfo.member.mobile, CurrentUserInfo.WXOpenId, -orderRequestModel.use_score))
                        {
                            tran.Rollback();
                            resp.errcode = 1;
                            resp.errmsg  = "更新宏巍积分失败";
                            context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(resp));
                            return;
                        }
                    }
                    #endregion

                    //积分记录
                }

                //积分扣除
                #endregion


                #region 余额抵扣

                if (orderRequestModel.use_amount > 0 && bllMall.IsEnableAccountAmountPay())
                {
                    CurrentUserInfo.AccountAmount -= orderRequestModel.use_amount;
                    if (bllMall.Update(CurrentUserInfo, string.Format(" AccountAmount={0}", CurrentUserInfo.AccountAmount), string.Format(" AutoID={0}", CurrentUserInfo.AutoID)) < 0)
                    {
                        tran.Rollback();
                        resp.errcode = 1;
                        resp.errmsg  = "更新用户余额失败";
                        context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(resp));
                        return;
                    }


                    UserScoreDetailsInfo scoreRecord = new UserScoreDetailsInfo();
                    scoreRecord.AddTime      = DateTime.Now;
                    scoreRecord.Score        = -(double)orderRequestModel.use_amount;
                    scoreRecord.TotalScore   = (double)CurrentUserInfo.AccountAmount;
                    scoreRecord.UserID       = CurrentUserInfo.UserID;
                    scoreRecord.AddNote      = "账户余额变动-下单使用余额";
                    scoreRecord.RelationID   = orderInfo.OrderID;
                    scoreRecord.WebSiteOwner = bllUser.WebsiteOwner;
                    scoreRecord.ScoreType    = "AccountAmount";
                    if (!bllMall.Add(scoreRecord))
                    {
                        tran.Rollback();
                        apiResp.code = (int)APIErrCode.OperateFail;
                        apiResp.msg  = "插入余额记录失败";
                        context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(apiResp));
                        return;
                    }

                    UserCreditAcountDetails record = new UserCreditAcountDetails();
                    record.WebsiteOwner = bllUser.WebsiteOwner;
                    record.Operator     = CurrentUserInfo.UserID;
                    record.UserID       = CurrentUserInfo.UserID;
                    record.CreditAcount = -orderRequestModel.use_amount;
                    record.SysType      = "AccountAmount";
                    record.AddTime      = DateTime.Now;
                    record.AddNote      = "账户余额变动-" + orderRequestModel.use_amount;
                    if (!bllMall.Add(record))
                    {
                        tran.Rollback();
                        resp.errcode = 1;
                        resp.errmsg  = "插入余额记录失败";
                        context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(resp));
                        return;
                    }

                    #region 更新宏巍余额
                    if (websiteInfo.IsUnionHongware == 1)
                    {
                        if (!hongWareClient.UpdateMemberBlance(hongWeiWareMemberInfo.member.mobile, CurrentUserInfo.WXOpenId, -(float)orderRequestModel.use_amount))
                        {
                            tran.Rollback();
                            resp.errcode = 1;
                            resp.errmsg  = "更新宏巍余额失败";
                            context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(resp));
                            return;
                        }
                    }
                    #endregion
                }


                #endregion

                #region 插入订单详情页及更新库存
                foreach (var item in detailList)
                {
                    ProductSku        productSku  = bllMall.GetProductSku((int)(item.SkuId));
                    WXMallProductInfo productInfo = bllMall.GetProduct(productSku.ProductId.ToString());
                    if (!this.bllMall.Add(item, tran))
                    {
                        tran.Rollback();
                        resp.errcode = 1;
                        resp.errmsg  = "提交失败";
                        context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(resp));
                        return;
                    }
                    //productSku.Stock -= item.TotalCount;
                    //if (bllMall.IsPromotionTime(productSku))
                    //{
                    //    productSku.PromotionStock -= item.TotalCount;
                    //}
                    //if (ZentCloud.ZCBLLEngine.BLLBase.ExecuteSql(string.Format("update ZCJ_ProductSku set Stock={0},PromotionStock={1} where SkuId={2}", productSku.Stock, productSku.PromotionStock, productSku.SkuId), tran) <= 0)
                    //{
                    //    tran.Rollback();
                    //    resp.errcode = 1;
                    //    resp.errmsg = "更新SKU失败";
                    //    context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(resp));
                    //    return;

                    //}
                    //更新 SKU库存
                    System.Text.StringBuilder sbUpdateStock = new StringBuilder();//更新库存sql
                    sbUpdateStock.AppendFormat(" Update ZCJ_ProductSku Set Stock-={0} ", item.TotalCount);
                    if (bllMall.IsPromotionTime(productSku))
                    {
                        sbUpdateStock.AppendFormat(",PromotionStock-={0} ", item.TotalCount);
                    }
                    sbUpdateStock.AppendFormat(" Where SkuId={0} And Stock>0 ", productSku.SkuId);
                    if (bllMall.IsPromotionTime(productSku))
                    {
                        sbUpdateStock.AppendFormat(" And PromotionStock>0 ", item.TotalCount);
                    }
                    if (ZentCloud.ZCBLLEngine.BLLBase.ExecuteSql(sbUpdateStock.ToString(), tran) <= 0)
                    {
                        tran.Rollback();
                        resp.errcode = 1;
                        resp.errmsg  = "提交订单失败,库存不足";
                        context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(resp));
                        return;
                    }
                }
                #endregion
                tran.Commit();//提交订单事务

                #region 宏巍通知
                if (websiteInfo.IsUnionHongware == 1)
                {
                    hongWareClient.OrderNotice(CurrentUserInfo.WXOpenId, orderInfo.OrderID);
                }
                #endregion
            }
            catch (Exception ex)
            {
                //回滚事物
                tran.Rollback();
                resp.errcode = 1;
                resp.errmsg  = ex.ToString();
                context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(resp));
                return;
            }
            context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(new
            {
                errcode  = 0,
                errmsg   = "ok",
                order_id = orderInfo.OrderID
            }));
        }