/// <summary> /// MQ生产者 /// </summary> /// <param name="Value"></param> /// <returns></returns> public static string ProducerMQ(string Value) { var factory = new ConnectionFactory() { HostName = ConfigurationUtil.GetSection("ObjectConfig:RabbitMqConfig:HostName"), Port = int.Parse(ConfigurationUtil.GetSection("ObjectConfig:RabbitMqConfig:Port")), UserName = ConfigurationUtil.GetSection("ObjectConfig:RabbitMqConfig:UserName"), Password = ConfigurationUtil.GetSection("ObjectConfig:RabbitMqConfig:Password"), }; using (var connection = factory.CreateConnection()) using (var channel = connection.CreateModel()) { channel.QueueDeclare(queue: "apply_queue", durable: true, exclusive: false, autoDelete: false, arguments: null); var properties = channel.CreateBasicProperties(); properties.Persistent = true; var body = Encoding.UTF8.GetBytes(Value); channel.BasicPublish(exchange: "", routingKey: "apply_queue", basicProperties: properties, body: body); } return("Hello World!"); }
/// <summary> /// 调用百度OCR小票识别服务 返回原始数据 /// </summary> /// <returns></returns> public static Result BaiDuReceiptOCR(OCRRequest oCRRequest) { try { var value = ConfigurationUtil.GetSection("ObjectConfig:CacheExpiration:AllMallOCRRule"); var hour = double.Parse(value); List <MallOCRRule> MallRuleList = CacheHandle <List <MallOCRRule> >( Key: "AllMallOCRRule", Hour: int.Parse(ConfigurationUtil.GetSection("ObjectConfig:CacheExpiration:AllMallOCRRule")), sqlWhere: ""); var MallRuleModel = MallRuleList.Where(s => s.MallID == Guid.Parse(oCRRequest.mallId)).FirstOrDefault(); if (MallRuleModel == null) { return(new Result(false, "请定义Mall的OCR规则", null)); } var result = HttpHelper.HttpPost(string.Format(MallRuleModel.OCRServerURL, MallRuleModel.OCRServerToken), $"image={HttpUtility.UrlEncode(oCRRequest.base64)}"); if (result.Contains("error_msg")) { var OCRErrorModel = JsonConvert.DeserializeObject <OCRErrorResult>(result); return(new Result(false, OCRErrorModel.error_msg, null)); } else { return(new Result(true, "", result)); } } catch (Exception ex) { Log.Error("BaiDuReceiptOCR", ex); return(new Result(false, ex.Message, null)); } }
public int Add(UserInfo model) { model.Pwd = CommonHelper.GetPwdCryptoStr(ConfigurationUtil.GetSection("DefaultPwd")); model.CreateTime = DateTime.Now; model.UpdateTime = DateTime.Now; return(base.Add(model)); }
get => new SqlSugarClient(new ConnectionConfig() { ConnectionString = ConfigurationUtil.GetSection("ConnectionStrings:conn"), //Data Source=BAIJINSUODC51\\BAIJINSUO;Initial Catalog=test;Integrated Security=True DbType = DbType.SqlServer, //必填, 数据库类型 IsAutoCloseConnection = true //默认false, 时候知道关闭数据库连接, 设置为true无需使用using或者Close操作 // InitKeyType = InitKeyType.SystemTable //默认SystemTable, 字段信息读取, 如:该属性是不是主键,是不是标识列等等信息 });
/// <summary> /// 插入MongoDb /// </summary> private void InsertMongoDb() { var client = new MongoClient(ConfigurationUtil.GetSection("MongoDb:ConnectionString")); var dataBase = client.GetDatabase("EIP_Log"); var table = dataBase.GetCollection <TLog>(LoggerConfig); table.InsertOneAsync(Log); }
public CommandResult <LoginShopOAuthReulst> LoginShopOuath(string MemberCode) { return(new LoginShopOAuthCommand().Execute(new LoginShopOAuthParamter() { OAuthAppId = ConfigurationUtil.GetSection("ShopOAuth")["OAuthAppId"], OAuthAppSecret = ConfigurationUtil.GetSection("ShopOAuth")["OAuthAppSecret"], InterfaceUrl = ConfigurationUtil.GetSection("ShopOAuth")["InterfaceUrl"], MemberCode = MemberCode })); }
public List <Category> GetCategoryList() { string domain = ConfigurationUtil.GetSection("Domain"); var data = SqlHelper.Instance.Queryable <Category>().OrderBy(r => r.CreateTime, SqlSugar.OrderByType.Desc).ToList(); data?.ForEach(item => { item.Icon = $"{domain}{item.Icon}"; }); return(data); }
/// <summary> /// 获取mongodb实例 /// </summary> /// <returns></returns> public IMongoCollection <T> MongodbInfoClient() { var client = new MongoClient(ConfigurationUtil.GetSection("MongoDb:ConnectionString")); Type t = typeof(T); string dbName = "EIP"; DbAttribute m = t.GetTypeInfo().GetCustomAttribute <DbAttribute>(); if (m != null) { dbName = m.Name; } var dataBase = client.GetDatabase(dbName); return(dataBase.GetCollection <T>(typeof(T).Name)); }
protected override CommandResult <List <Hashtable> > OnExecute(object commandParameter) { var result = new CommandResult <List <Hashtable> >(); var param = commandParameter as ComputePromotionParameter; var res = new LoadPinConfigComand().Execute(new LoadPinConfigParameter() { PinId = param.ActId }); if (res.ErrorCode == 0) { var configArry = JsonConvert.DeserializeObject <JArray>((res.Data["Config"] as PinConfig).Config); Hashtable hash = new Hashtable { //["ProductNo"] = config["ProductNo"].Value<string>(), //["SalePrice"] = config["SalePrice"].Value<decimal>(), //["ProductSkuNo"] = config["ProductSkuNo"].Value<decimal>(), ["Counter"] = 1, ["DeptCode"] = "0001", ["TypePrefix"] = "-1", ["TypeId"] = "-1" }; foreach (var item in configArry) { if (item["ProductSkuNo"].Value <string>() == param.ProductSkuNo) { hash["ProductNo"] = item["ProductNo"].Value <string>(); hash["SalePrice"] = item["SalePrice"].Value <decimal>(); hash["ProductSkuNo"] = item["ProductSkuNo"].Value <string>(); break; } } var url = ConfigurationUtil.GetSection("PromotionUrl").Value as string;; var _data = new { ActId = param.ActId, ProductList = new List <Hashtable>() { hash } }; var respromotion = ZlanAPICaller.Call <CommandResult <List <Hashtable> > >(url, _data); if (respromotion.ErrorCode == 0) { result.Data = respromotion.Data; } } return(result); }
protected override CommandResult <int> OnExecute(object commandParameter) { var result = new CommandResult <int>(); var param = commandParameter as ChangePinOrderStausParameter; using (CoreContext context = new CoreContext()) { var pinOrder = context.PinOrder.Where(p => p.OrderNo == param.OrderNo && p.Status == 0).FirstOrDefault(); if (pinOrder != null) { using (MySqlConnection conn = new MySqlConnection(ConfigurationUtil.GetSection("ConnectionStrings")["ShopConnectString"])) { conn.Open(); MySqlCommand com = new MySqlCommand(@"select count(1) Counter from shop_order_info where order_no=?no and pay_status=1", conn); com.Parameters.Add(new MySqlParameter("no", param.OrderNo)); MySqlDataReader reader = com.ExecuteReader(); while (reader.Read()) { if (Convert.ToInt32(reader["Counter"]) == 0) { result.ErrorCode = -1; result.ErrorMessage = $"订单{param.OrderNo}未支付"; return(result); } } reader.Close(); conn.Close(); } var pinInfo = context.PinInfo.Where(p => p.Recid == pinOrder.MainId).FirstOrDefault(); result.Data = context.Database.ExecuteSqlCommand("update pin_order set status=1 where order_no=@p0", param.OrderNo); List <string> OrderNo = new List <string>(); OrderNo = context.PinOrder.Where(p => p.MainId == pinInfo.Recid && p.Status == 1).Select(p => p.OrderNo).ToList(); //如果拼团人数满足则设置拼团成功 if (OrderNo.Count >= pinInfo.MinCount) { new SetPinInfoSuccessCommand().Execute(new SetPinInfoSuccessParameter { OrderNo = OrderNo, MainId = pinInfo.Recid }); } } } return(result); }
/// <summary> /// 自动积分并微信推送接口 /// </summary> /// <param name="webPosArg"></param> /// <returns></returns> private async static Task <Result> WebPosForPoint(WebPosArg webPosArg) { int amount = new Random(((unchecked ((int)DateTime.Now.Millisecond + (int)DateTime.Now.Ticks)))).Next(10, 2000); string testString = $@"<cmd type=""SALES"" appCode=""POS""> <shared offline=""true""> <companyID>{webPosArg.companyID}</companyID> <orgID>{webPosArg.orgID}</orgID> <storeID>{webPosArg.storeID}</storeID> <cashierID>{webPosArg.cashierID}</cashierID> </shared> <sales discountPercentage=""{webPosArg.discountPercentage}"" cardID=""{webPosArg.cardID}"" txnDateTime=""{webPosArg.txnDateTime}"" receiptNo=""12L102N10120180321uytu7t876896{amount}"" actualAmount=""{amount}"" payableAmount=""{amount}"" verificationCode="""" /> </cmd>"; WebPosTest.WebPOSSoapClient ws = new WebPosTest.WebPOSSoapClient(WebPosTest.WebPOSSoapClient.EndpointConfiguration.WebPOSSoap); WebPosTest.WebPOSCredentials mwc = new WebPosTest.WebPOSCredentials(); mwc.Username = ConfigurationUtil.GetSection("ObjectConfig:WebPosService:UserName"); mwc.Password = ws.GetEncryptedCharAsync(ConfigurationUtil.GetSection("ObjectConfig:WebPosService:PassWord")).Result; try { var cmdResult = await ws.CmdAsync(mwc, testString); if (!string.IsNullOrWhiteSpace(cmdResult.CmdResult) && cmdResult.CmdResult.Contains("hasError=\"false\"")) { return(new Result(true, "OCR识别成功,完成自动积分且进行微信推送", null)); } return(new Result(false, $"OCR验证通过,{cmdResult.CmdResult}", null)); } catch (Exception ex) { Log.Error("WebPos接口", ex); return(new Result(false, $"OCR验证通过,{ex.Message}", null)); } }
/// <summary> /// 初始化 /// </summary> /// <returns></returns> public static async Task Init() { NameValueCollection properties = new NameValueCollection { ["quartz.scheduler.instanceName"] = "EIPScheduler", ["quartz.scheduler.instanceId"] = "instance_one", ["quartz.threadPool.type"] = "Quartz.Simpl.SimpleThreadPool, Quartz", ["quartz.threadPool.threadCount"] = ConfigurationUtil.GetSection("Quartz:ThreadCount"), ["quartz.jobStore.misfireThreshold"] = "60000", ["quartz.jobStore.type"] = "Quartz.Impl.AdoJobStore.JobStoreTX, Quartz", ["quartz.jobStore.useProperties"] = "false", ["quartz.jobStore.dataSource"] = "default", ["quartz.jobStore.tablePrefix"] = "QRTZ_", ["quartz.jobStore.clustered"] = "true", ["quartz.jobStore.driverDelegateType"] = "Quartz.Impl.AdoJobStore.SqlServerDelegate, Quartz", ["quartz.dataSource.default.connectionString"] = ConfigurationUtil.GetSection("Quartz:ConnectionString"), ["quartz.dataSource.default.provider"] = ConfigurationUtil.GetSection("Quartz:DataSource"), ["quartz.serializer.type"] = "json" }; SchedulerFactory = new StdSchedulerFactory(properties); Scheduler = await SchedulerFactory.GetScheduler(); }
private static IConnection CreateConnection() { try { var connectionString = ConfigurationUtil.GetSection("ActiveMQConfig")["ActiveMQConnection"]; StringDictionary config = new StringDictionary(); var data = connectionString.Split(new string[] { ";" }, StringSplitOptions.RemoveEmptyEntries); foreach (var item in data) { var kvPair = item.Split(new string[] { "=" }, StringSplitOptions.RemoveEmptyEntries); config[kvPair[0]] = kvPair[1]; } var result = new ConnectionFactory(config["brokerUri"]).CreateConnection() as Connection; result.UserName = config["username"]; result.Password = config["password"]; result.Start(); return(result); } catch { return(null); } }
protected override CommandResult <List <BookInfo> > OnExecute(object commandParameter) { var param = commandParameter as LoadBookOrderListParameter; var result = new CommandResult <List <BookInfo> >(); result.Data = new List <BookInfo>(); using (CoreContext context = new CoreContext()) { var bookList = context.BookInfo.FromSql($@"select b.* from book_info b left join pay_order p on p.order_no=b.order_no where p.`STATUS`=1 and b.Member_Account={param.MemberAccount} order by b.status,b.Recid desc limit {(param.PageIndex - 1) * param.PageSize},{param.PageSize}").ToList(); foreach (var item in bookList) { using (MySqlConnection conn = new MySqlConnection(ConfigurationUtil.GetSection("ConnectionStrings")["ShopConnectString"])) { conn.Open(); MySqlCommand com = new MySqlCommand(@"select count(1) Counter from shop_order_info where order_no=?no and pay_status=1", conn); com.Parameters.Add(new MySqlParameter("no", item.ShopOrderNo)); MySqlDataReader reader = com.ExecuteReader(); while (reader.Read()) { if (Convert.ToInt32(reader["Counter"]) > 0) { item.Status = 9; } } reader.Close(); conn.Close(); } item.MemberAccount = null; } result.Data = bookList; } return(result); }
public override async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next) { var sign = context.HttpContext.Request.Headers["sign"]; var appsecret = ConfigurationUtil.GetSection("ZlanApi")["APP_SECRECT"] as string; var nonceStr = context.HttpContext.Request.Headers["noncestr"]; var timestamp = context.HttpContext.Request.Headers["timestamp"]; //根据请求类型拼接参数 var query = context.HttpContext.Request.Query; string data = string.Empty; string method = context.HttpContext.Request.Method; switch (method) { case "POST": System.IO.Stream stream = context.HttpContext.Request.Body; string responseJson = string.Empty; StreamReader streamReader = new StreamReader(stream); data = streamReader.ReadToEnd(); break; case "GET": data = query.OrderBy(k => k.Key).ToString(); break; default: context.Result = new ObjectResult(ErrorResult <int> .ParameterError); return; } var appid = context.HttpContext.Request.Headers["appid"]; if (SingUtil.Sign(appid, appsecret, nonceStr, timestamp, data) != sign) { context.Result = new ObjectResult(ErrorResult <int> .NoAuthorization); return; } await next(); }
/// <summary> /// 从OCR接口中 根据规则 获取详细内容 (暂无校验) /// </summary> /// <param name="OcrResult"></param> /// <returns></returns> private static Result RecognitOCRResult(string OcrResult) { try { var OCRResultModel = JsonConvert.DeserializeObject <OCRResult>(OcrResult); var WordList = OCRResultModel.words_result; //被识别的内容 var OCRStoreName = string.Empty; //被识别出来的商铺名称 //查询所有的商铺规则并缓存 List <StoreOCRDetail> AllStoreOCRDetailRuleList = CacheHandle <List <StoreOCRDetail> >( Key: "AllStoreOCRDetailRuleList" , Hour: double.Parse(ConfigurationUtil.GetSection("ObjectConfig:CacheExpiration:AllStoreOCRDetailRuleList")) , sqlWhere: ""); //所有商铺名称规则 var StoreNameRuleList = AllStoreOCRDetailRuleList.Where(s => s.OCRKeyType == (int)OCRKeyType.StoreName).Select(c => c.OCRKey).ToList(); var resultStoreName = FindStoreNameFromAllRule(WordList, StoreNameRuleList);//根据所有的店铺名规则匹配出的StoreName var StoreModel = dal.GetModel <Store>($" and StoreName like '%{resultStoreName}%'"); if (StoreModel == null) { return(new Result(false, "识别商铺名称失败!", "")); } //最后识别结果 var ReceiptOCRModel = new ReceiptOCR { StoreId = StoreModel.StoreId, StoreName = resultStoreName, StoreCode = StoreModel.StoreCode, ReceiptNo = "", TranAmount = 0, TransDatetime = Commom.DefaultDateTime, RecongnizelId = Guid.Empty, Base64 = "" }; //当前店铺的规则明细 var ThisStoreOCRDetail = AllStoreOCRDetailRuleList.Where(s => s.StoreId == StoreModel.StoreId).ToList(); //根据店铺规则明细 关键字类型 关键字 取值方法 匹配识别结果 foreach (var StoreDetailRule in ThisStoreOCRDetail) { for (int i = 0; i < WordList.Count(); i++) { Result ReturnResult = GetValue(WordList, i, StoreDetailRule); //根据规则取值 if (ReturnResult.Success) { var ReturnData = ReturnResult.Data.ToString(); if (!string.IsNullOrWhiteSpace(ReturnData)) { switch (StoreDetailRule.OCRKeyType) //枚举有注释,根据关键字类型赋值 { case (int)OCRKeyType.StoreName: continue; case (int)OCRKeyType.ReceiptNO: if (!string.IsNullOrWhiteSpace(ReturnData) && string.IsNullOrWhiteSpace(ReceiptOCRModel.ReceiptNo)) { ReceiptOCRModel.ReceiptNo = ReturnResult.Data.ToString(); continue; } break; case (int)OCRKeyType.DateTime: if (!string.IsNullOrWhiteSpace(ReturnData) && ReceiptOCRModel.TransDatetime == Commom.DefaultDateTime) { ReturnData = ReturnData.Replace(" ", "").Insert(10, " "); //可能会识别成 2019 - 05 - 1512:14:44 转datetime 报错 if (DateTime.TryParse(ReturnData, out var DateTimeResult)) { ReceiptOCRModel.TransDatetime = DateTimeResult; continue; } } break; case (int)OCRKeyType.Amount: if (!string.IsNullOrWhiteSpace(ReturnData) && ReceiptOCRModel.TranAmount == 0) { if (decimal.TryParse(ReturnResult.Data.ToString(), out var AmountResult)) { ReceiptOCRModel.TranAmount = AmountResult; continue; } } break; default: return(new Result(false, $"商铺未设置该关键字类型取值方法:{StoreDetailRule.OCRKeyType}", null)); } } } } } var RecongnizeModelId = Guid.NewGuid(); var RecongnizeModel = new ApplyPictureRecongnize { id = RecongnizeModelId, applyid = Guid.Empty, Lineno = 0, LineContent = JsonConvert.SerializeObject(WordList), OCRResult = JsonConvert.SerializeObject(ReceiptOCRModel) }; var AddResult = DbContext.Add(RecongnizeModel);//添加原始数据 applyid 等待积分申请 //添加成功后 出参RecongnizeModelId if (AddResult == 0) { ReceiptOCRModel.RecongnizelId = RecongnizeModelId; } else { return(new Result(false, "添加到ApplyPictureRecongnize失败", null)); } return(new Result(true, "识别成功", ReceiptOCRModel)); } catch (Exception ex) { Log.Error("VerifyOCRResult", ex); return(new Result(false, ex.Message, null)); } //同步寻找 string FindStoreNameFromAllRule(List <Words> words, List <string> StoreNameList) { foreach (var Name in StoreNameList) { foreach (var word in words) { if (word.words.Contains(Name)) { return(word.words); } } } return(""); } //异步寻找 async Task <string> FindStoreNameFromAllRuleAsync(List <Words> words, List <string> StoreNameList) { var Sresult = ""; foreach (var names in StoreNameList) { var LineCount = words.Count(); //识别内容数量 //二分异步寻找 var afterLine = LineCount % 2 == 1 ? (LineCount - 1) / 2 : LineCount / 2; //前一半 var beforeLine = LineCount - afterLine; //后一半 CancellationTokenSource ct = new CancellationTokenSource(); for (int i = 0; i < 2; i++) { var min = i % 2 == 0 ? 0 : afterLine; var max = i % 2 == 0 ? afterLine - 1 : LineCount; await Task.Run(() => { for (int j = min; j < max; j++) { if (ct.IsCancellationRequested) { if (words[j].words.Contains(names)) { ct.Cancel(); Sresult = words[j].words; } } } }, ct.Token); } } return(""); } //根据规则获取指定识别内容 Result GetValue(List <Words> words_result, int index, StoreOCRDetail StoreDetailRule) { var WordValue = ""; if (words_result[index].words.Contains(StoreDetailRule.OCRKey)) { switch (StoreDetailRule.GetValueWay)//可查看枚举注释 { case (int)GetValueWay.OCRKey: WordValue = words_result[index].words; break; case (int)GetValueWay.AfterOCRKey: var IndexOfKey = words_result[index].words.IndexOf(StoreDetailRule.OCRKey) + StoreDetailRule.OCRKey.Length + StoreDetailRule.SkipLines; WordValue = words_result[index].words.Substring(IndexOfKey); break; case (int)GetValueWay.NextLine: if (index + StoreDetailRule.SkipLines <= words_result.Count()) { WordValue = words_result[index + StoreDetailRule.SkipLines].words; } break; default: return(new Result(false, $"商铺未设置该关键字取值方法:{StoreDetailRule.GetValueWay}", null)); } } return(new Result(true, "", WordValue)); } }
protected override CommandResult <int> OnExecute(object commandParameter) { // var param = commandParameter as CreateShopOrderParameter; var result = new CommandResult <int>(); using (CoreContext context = new CoreContext()) { //if (DateTime.Now == DateTime.Parse("2018-10-31 23:30:00")) { var bookList = context.BookInfo.FromSql(@"select b.* from book_info b left join pay_order p on p.order_no=b.order_no where p.`STATUS`=1 and b.`STATUS` !=1 ").ToList(); foreach (var book in bookList) { var acc = context.MemberInfo.Where(m => m.AccountId == book.MemberAccount).Select(m => m.ZlOpenId).FirstOrDefault(); var couponticket = book.CouponTicket; if (string.IsNullOrEmpty(couponticket)) { int?couponId = context.BookInfo.Where(b => b.OrderNo == book.OrderNo && b.MemberAccount == book.MemberAccount).Select(b => b.CouponId).FirstOrDefault(); var url = ConfigurationUtil.GetSection("CouponUrl").Value as string; //领取抵扣优惠券 var res = ZlanAPICaller.Call <CommandResult <string> >(url, new { MemberAccount = acc, RuleId = couponId }); if (res.ErrorCode == 0) { context.Database.ExecuteSqlCommand($"update book_info set coupon_ticket={res.Data} where order_no={book.OrderNo}"); couponticket = res.Data; } else { result.ErrorCode = res.ErrorCode; result.ErrorMessage = res.ErrorMessage; LogUtil.Log("CreateShopOrder_TakeCoupon", book.OrderNo, res.ErrorMessage); } } { //移除购物车 var RemoveProductRes = ZlanAPICaller.ExecuteShop("Member.RemoveProduct", $"{{ 'MemberAccount': '{acc}','SkuCodeList':['{book.ProductSkuNo}'] }}"); if (RemoveProductRes["ErrorCode"].Value <string>() == "0000") { //加入购物车 var SelectProductRes = ZlanAPICaller.ExecuteShop("Member.SelectProduct", $"{{ 'ProductList':[{{ 'Increment': 0, 'Counter': 1, 'ProductSkuCode':'{book.ProductSkuNo}', 'Remark': ''}}], 'MemberAccount': '{acc}' }}"); if (SelectProductRes["ErrorCode"].Value <string>() == "0000") { //确认结算产品 var ConfirmSelectProductRes = ZlanAPICaller.ExecuteShop("Member.ConfirmSelectProduct", $"{{ 'MemberAccount': '{acc}','SkuCodeList':['{book.ProductSkuNo}'] }}"); //生成订单 if (ConfirmSelectProductRes["ErrorCode"].Value <string>() == "0000") { var CouponTicket = new Dictionary <string, IList <string> >(); CouponTicket["Coupon"] = new List <string>() { couponticket }; CouponTicket["RedPackage"] = new List <string>(); var orderParam = new { MemberAccount = acc, book.AddressId, PaymentId = 3, Kind = "shop", CouponTicket, UseSpecialDiscount = 0, VCartDiscount = 0, Score = 0 }; LogUtil.Log("CreateShopOrder_CreateOrderRes", book.OrderNo, JsonConvert.SerializeObject(orderParam)); var CreateOrderRes = ZlanAPICaller.ExecuteShop("Member.CreateOrder", orderParam); if (CreateOrderRes["ErrorCode"].Value <string>() == "0000") { result.Data += context.Database.ExecuteSqlCommand($"update book_info set Status=1,Shop_Order_No={CreateOrderRes["Result"]["PaymentNo"].Value<string>()} where order_no={book.OrderNo}"); //book.Status = 1; //book.ShopOrderNo = CreateOrderRes["Result"]["PaymentNo"].Value<string>(); //book.CouponTicket = res.Data; //context.SaveChanges(); } else { result.ErrorCode = -1; result.ErrorMessage = CreateOrderRes["ErrorMsg"].Value <string>(); LogUtil.Log("CreateShopOrder_CreateOrderRes", book.OrderNo, result.ErrorMessage); } } else { result.ErrorCode = -1; result.ErrorMessage = ConfirmSelectProductRes["ErrorMsg"].Value <string>(); LogUtil.Log("CreateShopOrder_ConfirmSelectProductRes", book.OrderNo, result.ErrorMessage); } } else { result.ErrorCode = -1; result.ErrorMessage = SelectProductRes["ErrorMsg"].Value <string>(); LogUtil.Log("CreateShopOrder_SelectProductRes", book.OrderNo, result.ErrorMessage); } } else { result.ErrorCode = -1; result.ErrorMessage = RemoveProductRes["ErrorMsg"].Value <string>(); LogUtil.Log("CreateShopOrder_RemoveProductRes", book.OrderNo, result.ErrorMessage); } } } } } return(result); }
/// <summary> /// 调用商城后台 /// </summary> /// <param name="key"></param> /// <param name="paramJSON"></param> /// <returns></returns> public static Newtonsoft.Json.Linq.JObject ExecuteSys(string key, object paramJSON = null) { return(Execute(ConfigurationUtil.GetSection("ZlanApi")["APP_ID"], ConfigurationUtil.GetSection("ZlanApi")["APP_SECRECT"], ConfigurationUtil.GetSection("ZlanApi")["SYS_URL"], key, paramJSON)); }
protected override CommandResult <int> OnExecute(object commandParameter) { var result = new CommandResult <int>(); var param = commandParameter as LoadDrawCountParameter; using (CoreContext context = new CoreContext()) { var act = context.ActivityInfo.Where(a => a.StartTime <= DateTime.Now && a.EndTime >= DateTime.Now && a.Status == 1).FirstOrDefault(); if (act == null) { result.ErrorCode = -1; result.ErrorMessage = "活动已结束"; return(result); } int count = 0; var zlopenid = ""; zlopenid = context.MemberInfo.Where(m => m.AccountId == param.MemberAccount).Select(m => m.ZlOpenId).FirstOrDefault(); string memo = ""; if (param.Kind == "login") { if ((context.AddDrawCountLog.Where(l => l.CreateDate <= DateTime.Parse(DateTime.Now.ToString("yyyy-MM-dd") + " 23:59:59") && l.CreateDate >= DateTime.Parse(DateTime.Now.ToString("yyyy-MM-dd") + " 00:00:00") && l.MemberAccount == zlopenid && l.Kind == param.Kind && l.ActId == act.Recid).Count() == 0)) { memo = "登录送1次抽奖机会"; count = 1; } } else { var constr = ConfigurationUtil.GetSection("ConnectionStrings")["ShopConnectString"]; using (MySqlConnection con = new MySqlConnection(constr)) { con.Open(); string sql = @"select payment_fee,member_account from shop_order_info where PAY_STATUS=1 and order_no=?ono and PAYMENT_TIME>='2018-11-01'"; MySqlCommand com = new MySqlCommand(sql, con); com.Parameters.Add(new MySqlParameter("?ono", param.OrderNo)); MySqlDataReader reader = com.ExecuteReader(); while (reader.Read()) { zlopenid = reader["member_account"] as string; count = Convert.ToInt32(reader["payment_fee"]) / 100; memo = $"下单赠送次数,订单号:{param.OrderNo}"; } con.Close(); } } if (count > 0) { context.Database.ExecuteSqlCommand(@"insert into member_draw_count (MEMBER_ACCOUNT,ACT_ID,COUNTER,CURRENT_COUNT) values(@p0,@p1,@p2,@p2) on DUPLICATE key update COUNTER=COUNTER+@p2,CURRENT_COUNT=CURRENT_COUNT+@p2 ", zlopenid, act.Recid, count); context.AddDrawCountLog.Add(new AddDrawCountLog() { MemberAccount = zlopenid, Counter = 1, CreateDate = DateTime.Now, Memo = memo, Kind = string.IsNullOrEmpty(param.Kind) ? "order" : param.Kind, ActId = act.Recid }); } context.SaveChanges(); result.Data = Convert.ToInt32(context.MemberDrawCount.Where(m => m.MemberAccount == zlopenid && m.ActId == act.Recid).Select(m => m.CurrentCount).FirstOrDefault()); } return(result); }
protected override CommandResult <int> OnExecute(object commandParameter) { var result = new CommandResult <int>(); var param = commandParameter as SetPinInfoSuccessParameter; using (CoreContext context = new CoreContext()) { //设置拼团成功 result.Data = context.Database.ExecuteSqlCommand("update pin_info set status=9 where recid=@p0 and status!=9 ", param.MainId); if (result.Data > 0) { foreach (var item in param.OrderNo) { try { var order = context.PinOrder.Where(p => p.OrderNo == item).FirstOrDefault(); var zlopenid = context.MemberInfo.Where(m => m.AccountId == order.MemberAccount).Select(m => m.ZlOpenId).FirstOrDefault(); var wxopneid = ""; using (MySqlConnection conn = new MySqlConnection(ConfigurationUtil.GetSection("ConnectionStrings")["ShopConnectString"])) { conn.Open(); MySqlCommand com = new MySqlCommand(@"select wx_open_id from member_info where account_id=?acc ", conn); com.Parameters.Add(new MySqlParameter("acc", zlopenid)); MySqlDataReader reader = com.ExecuteReader(); while (reader.Read()) { wxopneid = reader["wx_open_id"] as string; } reader.Close(); conn.Close(); } if (!string.IsNullOrEmpty(wxopneid)) { ActiveMQMessagePusher.Push("Message", new Dictionary <string, string> { { "MessageKey", "PinSuccess" } }, new { WxOpenId = wxopneid, OrderNo = item, Product = JsonConvert.DeserializeObject <Hashtable>(order.ProductConfig)["ProductName"] as string }); } } catch (Exception ex) { LogUtil.LogText("sendmessage:MessageKey:PinSuccess", item, ex.Message); } } var confirmRes = ZlanAPICaller.ExecuteSys("Sys.ChangeOrderConfirm", new { param.OrderNo, Type = "SUCCESS" }); if (!confirmRes["ErrorCode"].Value <string>().Equals("0000")) { LogUtil.Log("CreatePinOrder", param.MainId.ToString(), confirmRes["ErrorMsg"].Value <string>()); result.ErrorCode = -1; result.ErrorMessage = "解锁商城订单失败"; return(result); } } } return(result); }
protected override CommandResult <GetWxPaymentSignResult> OnExecute(object commandParameter) { var result = new CommandResult <GetWxPaymentSignResult>(); var param = commandParameter as GetWxPaymentSignParameter; if (string.IsNullOrEmpty(param.PayNo)) { return(ErrorResult <GetWxPaymentSignResult> .ParameterError); } using (CoreContext _context = new CoreContext()) { string payno = param.PayNo; PayOrder payOrder = _context.PayOrder.Where(o => o.OrderNo == payno).FirstOrDefault(); if (payOrder == null) { //Logger.Error("pay error,not found payconfig,payNo:" + payno); LogUtil.Log("wxpay", payno, "pay error,not found payconfig,payNo:" + payno); result.ErrorCode = -1; result.ErrorMessage = "找不到订单"; return(result); } if (payOrder.Status != 0) { //Log.Logger.Error("pay error,order is pay,payNo:" + payno); LogUtil.Log("wxpay", payno, "pay error,order is pay,payNo:" + payno); result.ErrorCode = 1; result.ErrorMessage = "订单已支付,请刷新页面"; return(result); } PaymentConfig paymentConfig = _context.PaymentConfig.Where(c => c.Id == payOrder.PaymentId).FirstOrDefault(); if (paymentConfig == null) { // Log.Logger.Error("pay error,not found payconfig,payNo:" + payno); LogUtil.Log("wxpay", payno, "pay error,not found payconfig,payNo:" + payno); result.ErrorCode = -1; result.ErrorMessage = "支付方式不正确"; return(result); } MemberInfo member = _context.MemberInfo.Where(m => m.AccountId == payOrder.MemberAccount).FirstOrDefault(); ////通过商城授权 if (string.IsNullOrEmpty(member.ZlOpenId)) { // Log.Logger.Error("pay error,ouath faild"); LogUtil.Log("wxpay", payno, "pay error,ouath faild,openid is null"); return(ErrorResult <GetWxPaymentSignResult> .NoAuthorization); } var connectionString = ConfigurationUtil.GetSection("ConnectionStrings")["ShopConnectString"]; var openid = member.ZlOpenId; using (MySqlConnection conn = new MySqlConnection(connectionString)) { try { string opneidFiled = "wx_open_id"; switch (paymentConfig.Kind) { case "XCX": opneidFiled = "xcx_open_id"; break; case "WX": opneidFiled = "wx_open_id"; break; default: break; } conn.Open(); string sql = $"select {opneidFiled} from member_info WHERE account_id=?acc LIMIT 1"; MySqlCommand command = new MySqlCommand(sql, conn); command.Parameters.Add(new MySqlParameter() { ParameterName = "?acc", Value = member.ZlOpenId }); MySqlDataReader reader = command.ExecuteReader(); while (reader.Read()) { openid = reader[opneidFiled] as string; } reader.Close(); } catch (Exception ex) { //Log.Logger.Error("get shop wx_openid fail#ex#" + ex.Message); //LogUtil.Log("GetWxPaymentSignCommand", "GetWxPaymentSignCommand", "GetWxPaymentSignCommand", "get shop wx_openid fail#ex#" + ex.Message); LogUtil.Log("wxpay", payno, ex.Message); return(ErrorResult <GetWxPaymentSignResult> .NoLogin); } } string productName = ""; string ProductDesc = payOrder.Memo; if (ProductDesc.Length > 20) { ProductDesc = ProductDesc.Substring(0, 20) + "..."; } string scheme = !StringValues.IsNullOrEmpty(httpContext.Request.Headers["X-Client-Scheme"]) ? httpContext.Request.Headers["X-Client-Scheme"].ToString() : httpContext.Request.Scheme; Hashtable paramHash = new Hashtable { ["appid"] = paymentConfig.AppId, ["mch_id"] = paymentConfig.UserId, //商户号 ["trade_type"] = "JSAPI", ["nonce_str"] = Guid.NewGuid().ToString("N"), ["openid"] = openid, ["out_trade_no"] = payno, ["total_fee"] = ((int)(payOrder.PayFee * 100)).ToString(), ["notify_url"] = $"{scheme}://{httpContext.Request.Host}" + "/PaymentCallBack/WeiXinPayCallBack", ["body"] = ProductDesc, ["spbill_create_ip"] = httpContext.Connection.LocalIpAddress.ToString(), ["time_start"] = string.Format("{0:yyyyMMddHHmmss}", Convert.ToDateTime(payOrder.CreateTime)), ["time_expire"] = string.Format("{0:yyyyMMddHHmmss}", DateTime.Now.AddMinutes(10)) }; WxPayUtil.SetMD5Sign(paramHash, paymentConfig.PrivateKey); Hashtable responseHash = WxPayUtil.GetResponseHash("wxorder_" + payno, "https://api.mch.weixin.qq.com/pay/unifiedorder", paramHash); var prepayId = ""; if (responseHash["return_code"] as string == "SUCCESS" && responseHash["result_code"] as string == "SUCCESS") { prepayId = responseHash["prepay_id"] as string; } //调用接口出错 else { result.ErrorCode = -1; result.ErrorMessage = responseHash["return_msg"] + "=>" + responseHash["err_code_des"]; return(result); } //调用接口失败,未知错误 if (string.IsNullOrEmpty(prepayId)) { result.ErrorCode = -1; result.ErrorMessage = "服务器忙"; return(result); } result.Data = new GetWxPaymentSignResult() { AppId = paymentConfig.AppId, Timestamp = string.Format("{0}", WxPayUtil.GetTimestamp()), NonceStr = WxPayUtil.GetNoncestr(), Package = "prepay_id=" + prepayId, SignType = "MD5" }; Hashtable choosePayParamHash = new Hashtable { ["appId"] = result.Data.AppId, ["timeStamp"] = result.Data.Timestamp, ["nonceStr"] = result.Data.NonceStr, ["package"] = result.Data.Package, ["signType"] = result.Data.SignType }; //签名 result.Data.Signature = WxPayUtil.SetMD5Sign(choosePayParamHash, paymentConfig.PrivateKey); LogUtil.Log("wxpay", payno, "ouput=>" + JsonConvert.SerializeObject(result.Data)); } return(result); }
protected override CommandResult <Hashtable> OnExecute(object commandParameter) { var result = new CommandResult <Hashtable>(); result.Data = new Hashtable(); var param = commandParameter as NewMemberSkillParameter; string newSql = @"select count(1) Counter from shop_order_info where MEMBER_ACCOUNT =?acc and pay_status=1"; string _30Sql = @"SELECT count(1) Counter from shop_order_info where date(ORDER_TIME)<'2018-11-01' and date(ORDER_TIME)>='2018-10-01' and pay_status=1 and MEMBER_ACCOUNT = ?acc "; var connect = ConfigurationUtil.GetSection("ConnectionStrings")["ShopConnectString"]; bool isNew = true, is30 = true; using (MySqlConnection con = new MySqlConnection(connect)) { con.Open(); MySqlCommand com1 = new MySqlCommand(newSql, con); com1.Parameters.Add(new MySqlParameter("?acc", param.MemberAccount)); var Reader1 = com1.ExecuteReader(); while (Reader1.Read()) { if (Convert.ToInt32(Reader1["Counter"]) > 0) { isNew = false; } } Reader1.Close(); if (!isNew) { MySqlCommand com2 = new MySqlCommand(_30Sql, con); com1.Parameters.Add(new MySqlParameter("?acc", param.MemberAccount)); var Reader2 = com1.ExecuteReader(); while (Reader2.Read()) { if (Convert.ToInt32(Reader2["Counter"]) > 0) { is30 = false; isNew = false; } } Reader2.Close(); } con.Close(); } result.Data["isNew"] = isNew; result.Data["is30"] = is30; Hashtable prize = null; param.LogCount = param.LogCount + 1; if (isNew) { var newmemberprize = (param.Prize["NewMemberPrize"] as JArray).ToObject <List <Hashtable> >(); foreach (var item in newmemberprize) { JObject condiction = item["Condition"] as JObject; if (param.LogCount == condiction["Counter"].Value <int>()) { prize = (item["Prize"] as JObject).ToObject <Hashtable>(); break; } } } if (is30) { var normalprize = (param.Prize["NormalPrize"] as JArray).ToObject <List <Hashtable> >(); foreach (var item in normalprize) { JObject condiction = item["Condition"] as JObject; if (param.LogCount == condiction["Counter"].Value <int>()) { prize = (item["Prize"] as JObject).ToObject <Hashtable>(); break; } } } if (prize != null) { result.Data["Prize"] = prize; } return(result); }
/// <summary> /// 根据信息校验用户是否篡改信息,是否满足商铺积分规则 /// </summary> /// <param name="receiptOCR"></param> /// <returns></returns> private static Result VerifyRecognition(ReceiptOCR receiptOCR) { //识别的原始数据 var RecongnizeModel = dal.GetModel <ApplyPictureRecongnize>($" and id ='{receiptOCR.RecongnizelId}'"); if (RecongnizeModel == null) { return(new Result(false, "ApplyPictureRecongnize is null", null)); } #region 检查数据是否篡改(Contain 不是绝对) ReceiptOCR OldReceipt = JsonConvert.DeserializeObject <ReceiptOCR>(RecongnizeModel.OCRResult); var CompareResult = CompareModel <ReceiptOCR>(OldReceipt, receiptOCR); if (!CompareResult.Success) { return(CompareResult); } #endregion #region 匹配商铺规则 StoreOCR StoreOCRRule = CacheHandle <StoreOCR>( Key: $"StoreOCR{receiptOCR.StoreId}", Hour: double.Parse(ConfigurationUtil.GetSection("ObjectConfig:CacheExpiration:StoreOCR")), sqlWhere: $"and StoreId = '{receiptOCR.StoreId}'"); if (StoreOCRRule.Enabled != 1) { return(new Result(false, "商铺未启用自动积分", null)); } if (StoreOCRRule.needVerify == 1) //当商铺启用校验规则 { if (receiptOCR.TranAmount < StoreOCRRule.MinValidReceiptValue || receiptOCR.TranAmount > StoreOCRRule.MaxValidReceiptValue) { return(new Result(false, "小票金额不在店铺规则范围之内!", null)); } if (StoreOCRRule.MaxTicketPerDay != 0) //日自动交易笔数为0时 代表不限制 { var TicketPerDay = DbContext.Query <int>($@"select count(*) from ApplyPoint where StoreID = '{receiptOCR.StoreId}' and VerifyStatus = 1 and SourceType=7 and DATEDIFF(dd,AuditDate,GETDATE())=0").FirstOrDefault(); //当日交易笔数 if (TicketPerDay >= StoreOCRRule.MaxTicketPerDay) { return(new Result(false, "今日已超过最大自动积分记录数量", null)); } } Store StoreModel = CacheHandle <Store>( Key: $"Store{receiptOCR.StoreId}", Hour: double.Parse(ConfigurationUtil.GetSection("ObjectConfig:CacheExpiration:Store")), sqlWhere: $" and StoreId = '{receiptOCR.StoreId}'"); if ((StoreModel.IsStandardPOS == "1" ? 0 : 1) != StoreOCRRule.POSType) { return(new Result(false, "OCR商铺POS类型不一致", null)); } //POS门店代码暂无验证 } #endregion return(new Result(true, "验证成功", null)); }
/// <summary> /// 创建积分申请单,校验信息成功并推送 /// 若原先存在积分申请单,失败的原因:校验失败 所有应该重新赋值 /// </summary> /// <param name="applyPointRequest"></param> /// <returns></returns> public static Result CreateApplyPoint(ApplyPointRequest applyPointRequest) { try { #region 图片上传 ImageResponse ImageResponse = null; try { var FileUploadResult = ImageUpload(Commom.FileUploadUrl, applyPointRequest.receiptOCR.Base64); if (!FileUploadResult.Success) { return(FileUploadResult); } ImageResponse = JsonConvert.DeserializeObject <ImageResponse>(FileUploadResult.Data.ToString()); } catch (Exception ex) { Log.Error("CreateApplyPoint-FileUpload", ex); return(new Result(false, ex.Message, null)); } #endregion Store StoreModel = CacheHandle <Store>( Key: $"Store{applyPointRequest.receiptOCR.StoreId}", Hour: double.Parse(ConfigurationUtil.GetSection("ObjectConfig:CacheExpiration:Store")), sqlWhere: $" and StoreId = '{applyPointRequest.receiptOCR.StoreId}'"); StoreOCR StoreOCRRule = CacheHandle <StoreOCR>( Key: $"StoreOCR{applyPointRequest.receiptOCR.StoreId}", Hour: double.Parse(ConfigurationUtil.GetSection("ObjectConfig:CacheExpiration:StoreOCR")), sqlWhere: $"and StoreId = '{applyPointRequest.receiptOCR.StoreId}'"); var ApplyPoint = dal.GetModel <ApplyPoint>($" and ReceiptNo='{applyPointRequest.receiptOCR.ReceiptNo}' and StoreID='{applyPointRequest.receiptOCR.StoreId}'"); ApplyPictureRecongnize applyPictureRecongnize = dal.GetModel <ApplyPictureRecongnize>($" and id='{applyPointRequest.receiptOCR.RecongnizelId}'"); var IsHas = false; // 是否原先存在积分申请单 默认没有 更新识别原始表 if (ApplyPoint == null) //判断该小票号 是否存在积分申请单 不存在则添加原始积分申请单 (已解析原始数据,校验失败) { var ApplyPointId = Guid.NewGuid(); ApplyPoint = new ApplyPoint { ApplyPointID = ApplyPointId, MallID = StoreModel.MallID, StoreID = applyPointRequest.receiptOCR.StoreId, CardID = Guid.Parse(applyPointRequest.cardId), ReceiptNo = applyPointRequest.receiptOCR.ReceiptNo, TransDate = applyPointRequest.receiptOCR.TransDatetime, TransAmt = applyPointRequest.receiptOCR.TranAmount, VerifyStatus = StoreOCRRule.needVerify == 0 ? 1 : 0, ReceiptPhoto = ImageResponse.fileURL }; applyPictureRecongnize.applyid = ApplyPointId; DbContext.Update <ApplyPictureRecongnize>(applyPictureRecongnize); } else { IsHas = true; ApplyPoint.MallID = StoreModel.MallID; ApplyPoint.StoreID = applyPointRequest.receiptOCR.StoreId; ApplyPoint.CardID = Guid.Parse(applyPointRequest.cardId); ApplyPoint.ReceiptNo = applyPointRequest.receiptOCR.ReceiptNo; ApplyPoint.TransDate = applyPointRequest.receiptOCR.TransDatetime; ApplyPoint.TransAmt = applyPointRequest.receiptOCR.TranAmount; ApplyPoint.VerifyStatus = StoreOCRRule.needVerify == 0 ? 1 : 0; } var VerifyRecognitionResult = VerifyRecognition(applyPointRequest.receiptOCR); //校验结果 ApplyPoint.AuditDate = DateTime.Now; if (VerifyRecognitionResult.Success) //校验成功 { ApplyPoint.RecongizeStatus = 2; ApplyPoint.VerifyStatus = 1; } else//校验失败 修改值 { ApplyPoint.RecongizeStatus = 3; ApplyPoint.VerifyStatus = 0; ApplyPoint.Status = 0; if (IsHas) { DbContext.Update <ApplyPoint>(ApplyPoint); } else { DbContext.Add <ApplyPoint>(ApplyPoint); } return(VerifyRecognitionResult); } var LastRes = true;//添加是否成功 if (IsHas) { if (!DbContext.Update <ApplyPoint>(ApplyPoint)) { LastRes = false; } } else { if (DbContext.Add <ApplyPoint>(ApplyPoint) != 0) { LastRes = false; } } if (LastRes) { List <Company> companyList = CacheHandle <List <Company> >( Key: "Company", Hour: double.Parse(ConfigurationUtil.GetSection("ObjectConfig:CacheExpiration:Company")), sqlWhere: ""); List <OrgInfo> orgList = CacheHandle <List <OrgInfo> >( Key: "OrgInfo", Hour: double.Parse(ConfigurationUtil.GetSection("ObjectConfig:CacheExpiration:OrgInfo")), sqlWhere: ""); //自动积分 推送 var arg = new WebPosArg { companyID = companyList.Where(s => s.CompanyId == StoreModel.CompanyID).FirstOrDefault()?.CompanyCode ?? "", storeID = StoreModel.StoreCode, cardID = dal.GetModel <Card>($" and CardID='{applyPointRequest.cardId}'")?.CardCode ?? "", cashierID = "CrmApplyPoint", discountPercentage = 0, orgID = orgList.Where(s => s.OrgId == StoreModel.OrgID).FirstOrDefault()?.OrgCode ?? "", receiptNo = applyPointRequest.receiptOCR.ReceiptNo, txnDateTime = applyPointRequest.receiptOCR.TransDatetime }; var argStr = JsonConvert.SerializeObject(arg); ProducerMQ(argStr); return(new Result(true, "校验成功,已申请积分!", null)); } return(new Result(false, "校验成功,对ApplyPoint操作失败!", null)); } catch (Exception ex) { Log.Error("CreateApplyPoint", ex); return(new Result(false, ex.Message, null)); } }
protected override CommandResult <PrizeModel> OnExecute(object commandParameter) { var result = new CommandResult <PrizeModel>(); var param = commandParameter as NewYearDrawPrizeParameter; result.Data = new PrizeModel(); using (CoreContext context = new CoreContext()) { var act = context.ActivityInfo.Where(a => a.StartTime <= DateTime.Now && a.EndTime >= DateTime.Now && a.Status == 1 && a.Kind == param.Kind).FirstOrDefault(); if (act == null) { result.ErrorCode = -1; result.ErrorMessage = "活动已结束"; return(result); } Hashtable pconfig = JsonConvert.DeserializeObject <Hashtable>(act.ProductConfig); var zlopenid = context.MemberInfo.Where(m => m.AccountId == param.MemberAccount).Select(m => m.ZlOpenId).FirstOrDefault(); //扣减次数,使用数据库锁 if (context.Database.ExecuteSqlCommand(@"update member_draw_count set current_count=(current_count-1) where member_account=@p0 and act_id=@p1 and current_count-1>=0", zlopenid, act.Recid) > 0) { PrizeModel prize = null; var LogCount = context.ActivityLog.Where(l => l.MemberAccount == zlopenid && l.ActivityId == act.Recid).Count(); { var connect = ConfigurationUtil.GetSection("ConnectionStrings")["ShopConnectString"]; decimal payFee = 0; using (MySqlConnection con = new MySqlConnection(connect)) { con.Open(); MySqlCommand com1 = new MySqlCommand("select sum(payment_fee) as PayFee from shop_order_info " + "where member_account=?acc and pay_status=1 and order_no like '%00' and date(payment_time)>='2019-01-16' and date(payment_time)<='2019-01-25' ", con); com1.Parameters.Add(new MySqlParameter("?acc", zlopenid)); var Reader1 = com1.ExecuteReader(); while (Reader1.Read()) { if (Reader1["PayFee"] != DBNull.Value) { payFee = Convert.ToDecimal(Reader1["PayFee"]); } } Reader1.Close(); con.Close(); } var plist = new List <PrizeModel>(); //遍历奖品规则 var redisdb = RedisClient.GetDatabase(2); foreach (var item in (pconfig["PayPrize"] as JArray).ToObject <List <Hashtable> >()) { JObject condiction = item["Condition"] as JObject; if (payFee >= condiction["Fee"].Value <decimal>()) { var _plist = new List <PrizeModel>(); foreach (var hash in (item["Prize"] as JArray).ToObject <List <Hashtable> >()) { if (!hash.ContainsKey("end") || DateTime.Parse(hash["start"] as string) <= DateTime.Now && DateTime.Parse(hash["end"] as string) >= DateTime.Now) { _plist.Add(new PrizeModel() { PrizeCode = hash["PrizeCode"] as string, PrizeName = hash["PrizeName"] as string, Kind = hash["Kind"] as string, Ratio = Convert.ToInt32(hash["Ratio"]), CouponId = hash.ContainsKey("CouponId")? Convert.ToInt32(hash["CouponId"]):0 }); } } if (_plist.Count > 0) { var p = GetPrize(_plist); if (p != null) { string key = p.PrizeCode.IndexOf("prize") > -1 ? "RealPrize" : p.PrizeCode; //判断中奖次数 if (condiction["Limit"] != null && ValidateCount(redisdb, key, param.MemberAccount, Convert.ToInt32(condiction["Limit"]))) { continue; } //处理实物奖品 if (p.Kind == "RealPrize") { string RealPrize = ""; RealPrize = redisdb.ListLeftPop("Prize:" + p.PrizeCode); if (!string.IsNullOrEmpty(RealPrize)) { prize = JsonConvert.DeserializeObject <PrizeModel>(RealPrize); } else { continue;//实物不中继续往下抽奖 } } else { prize = p; } break; } } } } } if (prize != null) { result.Data = prize; var p = new PrizeInfo() { Status = 1, ActId = act.Recid, CouponId = prize.CouponId, CreateDate = DateTime.Now, MemberAccount = zlopenid, PrizeCode = prize.PrizeCode, PrizeName = prize.PrizeName, Kind = prize.Kind, }; context.PrizeInfo.Add(p); if (prize.Kind == "Coupon") { //调用获取优惠券 var url = ConfigurationUtil.GetSection("CouponUrl").Value as string; //领取抵扣优惠券 try { ActiveMQMessagePusher.Push("Command", new Dictionary <string, string> { { "caller", "Restful" }, { "url", url } }, new { MemberAccount = zlopenid, RuleId = Convert.ToInt32(prize.CouponId) } ); } catch (Exception) { } } } else { result.ErrorMessage = "未中奖,换个姿势再试试吧"; result.ErrorCode = -22; } } else { result.ErrorCode = -21; result.ErrorMessage = ""; } context.ActivityLog.Add(new ActivityLog() { MemberAccount = zlopenid, ActivityId = act.Recid, CreateTime = DateTime.Now, Memo = result.Data != null ? "抽中:" + result.Data.PrizeName : result.ErrorMessage }); context.SaveChanges(); } return(result); }
protected override CommandResult <Hashtable> OnExecute(object commandParameter) { var result = new CommandResult <Hashtable>(); var param = commandParameter as DrawPrizeParameter; result.Data = new Hashtable(); using (CoreContext context = new CoreContext()) { var act = context.ActivityInfo.Where(a => a.StartTime <= DateTime.Now && a.EndTime >= DateTime.Now && a.Status == 1 && a.Kind == param.Kind).FirstOrDefault(); if (act == null) { result.ErrorCode = -1; result.ErrorMessage = "活动已结束"; return(result); } Hashtable pconfig = JsonConvert.DeserializeObject <Hashtable>(act.ProductConfig); var zlopenid = context.MemberInfo.Where(m => m.AccountId == param.MemberAccount).Select(m => m.ZlOpenId).FirstOrDefault(); //扣减次数,使用数据库锁 if (context.Database.ExecuteSqlCommand(@"update member_draw_count set current_count=(current_count-1) where member_account=@p0 and current_count-1>=0", zlopenid) > 0) { var LogCount = context.ActivityLog.Where(l => l.MemberAccount == zlopenid && l.ActivityId == act.Recid).Count(); var res = new NewMemberSkillCommand().Execute(new NewMemberSkillParameter() { MemberAccount = zlopenid, LogCount = LogCount, Prize = pconfig }); Hashtable prize = null; if (res.ErrorCode == 0 && (Convert.ToBoolean(res.Data["isNew"]) || Convert.ToBoolean(res.Data["is30"]))) { result.ErrorCode = res.ErrorCode; result.ErrorMessage = res.ErrorMessage; prize = res.Data["Prize"] as Hashtable; } else { var connect = ConfigurationUtil.GetSection("ConnectionStrings")["ShopConnectString"]; decimal payFee = 0; using (MySqlConnection con = new MySqlConnection(connect)) { con.Open(); MySqlCommand com1 = new MySqlCommand("select sum(payment_fee) as PayFee from shop_order_info " + "where member_account=?acc and pay_status=1 and order_no like '%00' and date(payment_time)>='2018-11-01' and date(payment_time)<='2018-11-11' ", con); com1.Parameters.Add(new MySqlParameter("?acc", zlopenid)); var Reader1 = com1.ExecuteReader(); while (Reader1.Read()) { if (Reader1["PayFee"] != DBNull.Value) { payFee = Convert.ToDecimal(Reader1["PayFee"]); } } Reader1.Close(); con.Close(); } //遍历奖品规则 var redisdb = RedisClient.GetDatabase(1); foreach (var item in (pconfig["PayPrize"] as JArray).ToObject <List <Hashtable> >()) { JObject condiction = item["Condition"] as JObject; string key = "level:" + condiction["Fee"].Value <string>(); if (redisdb.HashExists(key, param.MemberAccount)) { continue; } if (payFee >= condiction["Fee"].Value <decimal>()) { prize = (item["Prize"] as JObject).ToObject <Hashtable>(); //处理实物奖品 if (prize["Kind"] as string == "RealPrize") { //var hash = (prize["RealPrize"] as JObject).ToObject<Hashtable>(); var _realprize = new List <PrizeModel>(); foreach (var hash in (prize["RealPrize"] as JArray).ToObject <List <Hashtable> >()) { if (DateTime.Parse(hash["start"] as string) <= DateTime.Now && DateTime.Parse(hash["end"] as string) >= DateTime.Now) { _realprize.Add(new PrizeModel() { PrizeCode = hash["PrizeCode"] as string, PrizeName = hash["PrizeName"] as string, Kind = prize["Kind"] as string }); } } string RealPrize = ""; if (_realprize.Count != 0) { var r = new Random(Guid.NewGuid().GetHashCode()); var index = r.Next(0, _realprize.Count); RealPrize = redisdb.ListLeftPop("Prize:" + _realprize[index].PrizeCode); } if (!string.IsNullOrEmpty(RealPrize)) { prize = JsonConvert.DeserializeObject <Hashtable>(RealPrize); } else { prize = null; } } if (prize != null) { redisdb.HashIncrementAsync(key, param.MemberAccount); } break; } } } if (prize != null) { result.Data = prize; var p = new PrizeInfo() { Status = 1, ActId = act.Recid, CouponId = Convert.ToInt32(prize["CouponId"]), CreateDate = DateTime.Now, MemberAccount = zlopenid, PrizeCode = prize["PrizeCode"] as string, PrizeName = prize["PrizeName"] as string, Kind = prize["Kind"] as string, }; context.PrizeInfo.Add(p); if (prize["Kind"] as string == "Coupon") { //调用获取优惠券 var url = ConfigurationUtil.GetSection("CouponUrl").Value as string; //领取抵扣优惠券 try { ActiveMQMessagePusher.Push("Command", new Dictionary <string, string> { { "caller", "Restful" }, { "url", url } }, new { MemberAccount = zlopenid, RuleId = Convert.ToInt32(prize["CouponId"]) } ); } catch (Exception) { } //var couponres = ZlanAPICaller.Call<CommandResult<string>>(url, new { MemberAccount = zlopenid, RuleId = Convert.ToInt32(prize["CouponId"]) }); //if (couponres.ErrorCode == 0) //{ // couponticket = couponres.Data; //} //else //{ // LogUtil.Log("DrawPrize_TakeCoupon", p.Recid.ToString(), $"input=>{JsonConvert.SerializeObject(new { MemberAccount = zlopenid, RuleId = Convert.ToInt32(prize["CouponId"]) })}#error=>{res.ErrorMessage}"); //} } } else { result.ErrorMessage = "未中奖,换个姿势再试试吧"; result.ErrorCode = -22; } } else { result.ErrorCode = -21; result.ErrorMessage = "每下单68元,即获得一次抽奖机会,上不封顶"; } context.ActivityLog.Add(new ActivityLog() { MemberAccount = zlopenid, ActivityId = act.Recid, CreateTime = DateTime.Now, Memo = result.Data.Keys.Count > 0 ? "抽中:" + result.Data["PrizeName"] as string : result.ErrorMessage }); context.SaveChanges(); } return(result); }