using Api.Framework; using Api.Framework.Enums; using Api.Framework.Events; using Api.Framework.Model; using Api.Framework.SDK; using Api.Framework.Timers; using Api.Framework.Tools; using CsharpHttpHelper; using Newtonsoft.Json; using SNRebate.Entitys; using SNRebate.Properties; using System; using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; using static Api.Framework.Tools.SNHelper; namespace SNRebate { public class Class1 : Plugin { public Class1() { this.Logo = Resources.苏宁; this.Name = Resources.PluginName; this.Note = Resources.PluginNote; } #region 自定义变量 public static Config Config; private MainForm mainForm = null; #endregion public override void Start() { try { var session = ApiClient.GetSession(); #region 判断表是否存在,不存在创建表 if (session.TableExist()) { var sntgws = session.Find("select * from fl_plugin_snrebate_sntgw").ToList(); if (sntgws != null) { foreach (var item in sntgws) { //插入主推广位数据 session.Insertable(new fl_adzone_info() { adzone_name = item.pid_chief_name, //推广位名称 adzone_pid = item.pid_chief, //推广位pid adzone_pid_cps_name = item.pid_chief_cps_name, //推广位cps名称 alliance_id = (int)CpsType.苏宁易购, //联盟id robot_id = item.robot_id, //机器人id group_id = string.Empty, //群id is_download = false, //不下载 member_id = 0, //私人id onoff = item.onoff, //不禁用 custom_type = Resources.SoftwareType, //自定义类型 extend = "chief" }).ExecuteCommand(); //插入副推广位数据 session.Insertable(new fl_adzone_info() { adzone_name = item.pid_deputy_name, //推广位名称 adzone_pid = item.pid_deputy, //推广位pid adzone_pid_cps_name = item.pid_deputy_cps_name, //推广位cps名称 alliance_id = (int)CpsType.苏宁易购, //联盟id robot_id = item.robot_id, //机器人id group_id = string.Empty, //群id is_download = false, //不下载 member_id = 0, //私人id onoff = item.onoff, //不禁用 custom_type = Resources.SoftwareType, //自定义类型 extend = "deputy" }).ExecuteCommand(); } } session.DropTable(); } #endregion //创建配置文件 Config = this.ReadConfig(); SDK.ReciveIMEvent += SDK_ReciveIMEvent; SDK.OrderNoticeEvent += SDK_OrderNoticeEvent; } catch (Exception ex) { this.OnLog(ex.Message); } } #region 订单事件处理 private void SDK_OrderNoticeEvent(object sender, OrderNoticeEvent e) { try { if (e.Member != null && e.ChatType == CpsType.苏宁易购) { //是否黑名单 if (ApiClient.IsBlackFlMemberInfo(e.Member)) { return; } var session = ApiClient.GetSession(); var order = e.Order as fl_order_suning; if (order == null) return; var robot_info = session.FindRobotInfo(e.Member.robot_name, e.Member.robot_type); if (robot_info != null) { var mess = string.Empty; var point = HttpHelper.JsonToObject(order.db_point) as ItemPoint; switch (e.OrderNoticeType) { case OrderNoticeType.客户订单: if (Config.UserOrderChangeSwitch == SwitchType.开启 && !ApiClient.Setting.SystemConfig.message_warning_switch) { mess = _GetOrderStateMess(order.db_status, order, e.Member, point); if (!string.IsNullOrEmpty(e.Member.username) && !string.IsNullOrEmpty(mess)) ApiClient.SendMessage(robot_info, e.Member.username, mess, order.msg_groupid); } return; case OrderNoticeType.一级提成: if (Config.AgentReceivedCommissionSwitch == SwitchType.开启) { if (e.Customer != null && point.AwardOne != 0) { if (order.db_status == SystemOrderStatus.订单维权中) mess = Config.ClientOrderRefund_OneLevelTip; if (order.db_status == SystemOrderStatus.订单付款) mess = Config.OrderPaymentInform_OneLevelTip; else if (order.db_status == SystemOrderStatus.订单失效) mess = Config.OrderCountermandInform_OneLevelTip; else if (order.db_status == SystemOrderStatus.订单结算) mess = Config.OrderSettlement_OneLevelTip; } } break; case OrderNoticeType.二级提成: if (Config.AgentReceivedCommissionSwitch == SwitchType.开启) { if (e.Customer != null) { if (order.db_status == SystemOrderStatus.订单维权中) mess = Config.ClientOrderRefund_TwoLevelTip; if (order.db_status == SystemOrderStatus.订单付款) mess = Config.OrderPaymentInform_TwoLevelTip; else if (order.db_status == SystemOrderStatus.订单失效) mess = Config.OrderCountermandInform_TwoLevelTip; else if (order.db_status == SystemOrderStatus.订单结算) mess = Config.OrderSettlement_TwoLevelTip; } } break; case OrderNoticeType.三级提成: if (Config.AgentReceivedCommissionSwitch == SwitchType.开启) { if (e.Customer != null) { if (order.db_status == SystemOrderStatus.订单维权中) mess = Config.ClientOrderRefund_ThreeLevelTip; if (order.db_status == SystemOrderStatus.订单付款) mess = Config.OrderPaymentInform_ThreeLevelTip; else if (order.db_status == SystemOrderStatus.订单失效) mess = Config.OrderCountermandInform_ThreeLevelTip; else if (order.db_status == SystemOrderStatus.订单结算) mess = Config.OrderSettlement_ThreeLevelTip; } } break; case OrderNoticeType.群主分成: if (Config.PrincipalReceivedCommissionSwitch == SwitchType.开启) { if (e.Customer != null) { if (order.db_status == SystemOrderStatus.订单维权中) mess = Config.ClientOrderRefund_LeaderTip; if (order.db_status == SystemOrderStatus.订单付款) mess = Config.OrderPaymentInform_LeaderTip; else if (order.db_status == SystemOrderStatus.订单失效) mess = Config.OrderCountermandInform_LeaderTip; else if (order.db_status == SystemOrderStatus.订单结算) mess = Config.OrderSettlement_LeaderTip; } } break; default: break; } if (!ApiClient.Setting.SystemConfig.message_warning_switch && !string.IsNullOrEmpty(e.Member.username) && !string.IsNullOrWhiteSpace(mess)) { ApiClient.SendMessage(robot_info, e.Member.username, new VariateReplace().CommonReplace(mess, order, e.Member, point).Replace("[下级昵称]", e.Customer.realnick)); } } } } catch (Exception ex) { this.OnLog($"苏宁订单通知异常:{ex.Message},{ex.StackTrace}"); } } #endregion #region 消息事件处理 private void SDK_ReciveIMEvent(object sender, ReciveIMEvent e) { Compute compute = null; var goodsName = string.Empty; try { //过滤表情xml和卡片xml if (((e.Message.Contains(@"("select * from fl_order_suning where orderCode = @orderCode", new { orderCode = orderid }); if (orders != null && orders.Count != 0) { var notices = new List(); var downSuningTimer = new DownSuningTimer(); foreach (var order in orders) { if (order.db_userid != 0 && order.db_userid != member.id) { e.SendMessage(Config.OccupyOrderErrorTip.Replace("[订单号]", orderid)); return; } if (order.db_userid != 0) { var point = HttpHelper.JsonToObject(order.db_point) as ItemPoint; member = e.GetMemberinfo(true); if (order.db_status == SystemOrderStatus.订单付款) e.SendMessage(new VariateReplace().CommonReplace(Config.OrderRepetBindTip, order, member, point)); else e.SendMessage(_GetOrderStateMess(order.db_status, order, member, point)); } else { if (order.payTime < ApiClient.Setting.SystemConfig.allow_bind_create_order_time) { e.SendMessage($"订单:{orderid},已经过了有效绑定时间!"); return; } if (order.db_status == SystemOrderStatus.订单结算) order.db_endtime = DateTime.Now.AddMinutes(-5);//重新结算的话,需要将订单的冻结时间重新赋值,让后台处理 //用户绑定订单 order.db_robotname = e.RobotName; order.db_robottype = e.ChatType; order.msg_groupid = e.Groupid; order.db_userid = member.id; session.SaveOrUpdate(order); if (member != null) { member.bind_order++; member = session.UpdateMemberGroup(member); } #region 首次付款时间 var record = session.FindStatisticsRecord(member.id); if (record == null) { record = new fl_statistics_record() { uid = member.id, ex2 = 0, ex4 = HttpExtend.GetTimeStamp(DateTime.Now) }; session.Saveable(record).ExecuteCommand(); } else { if (record.ex2 == 0 && record.ex4 == 0) { record.ex4 = HttpExtend.GetTimeStamp(DateTime.Now); session.Saveable(record).ExecuteCommand(); } } #endregion downSuningTimer.UpdateOrder(order, session, notices, isFrontData: true); } } #region 触发通知上级获得下级的提成奖励 if (!ApiClient.Setting.SystemConfig.message_warning_switch && notices.Count != 0) { var tasks = TimerTask.GetTimer() as Update_NoticeQueue; foreach (var item in notices) { //if (item.IsRewards) tasks.Add(item); //else //SDK_OrderNoticeEvent(this, item); } } #endregion e.Cancel = true; } else { if (i < 1) { CpsClient.UpdateOrder(CpsType.苏宁易购, DateTime.Now.AddMinutes(-30), DateTime.Now, orderid); i++; goto Next; } e.SendMessage(Config.NotFoundOrderErrorTip.Replace("[订单号]", orderid)); e.Cancel = true; return; } } if (OrderHelper.IsOrderId(e.Message.Trim())) return; #endregion #region 关键词解析、链接解析、标题查找 临时注释 var sninfoTemps = session.FindSnInfoTempGroups(); var snInfoTemp = sninfoTemps.FirstOrDefault(f => f.name == e.RobotInfo.name && f.onoff == false); if (snInfoTemp == null) return; try { SNId snid = SNHelper.GetSNGoodsID(message); if (snid == null) return; fl_cps_member sn_cps = null; var pid = string.Empty;//使用的推广位 #region 判断使用的推广位 var isDefault = true; if (!string.IsNullOrWhiteSpace(e.Groupid))//群pid { var groupAdzone = session.FindAdzoneInfos().FirstOrDefault(f => f.alliance_id == (int)CpsType.苏宁易购 && f.custom_type == PrivateAdzoneCustomType.群pid.ToString() && f.group_id == e.Groupid); if (groupAdzone != null && !string.IsNullOrWhiteSpace(groupAdzone.adzone_pid)) { string username = groupAdzone.adzone_pid_cps_name; pid = groupAdzone.adzone_pid; sn_cps = CpsClient.Members.FirstOrDefault(f => f.cpstype == CpsType.苏宁易购 && f.username == username); isDefault = false; } } if (isDefault)//私人pid { var memberAdzone = session.FindAdzoneInfos().FirstOrDefault(f => f.alliance_id == (int)CpsType.苏宁易购 && f.custom_type == PrivateAdzoneCustomType.用户私人pid.ToString() && f.member_id == member.id); if (memberAdzone != null && !string.IsNullOrWhiteSpace(memberAdzone.adzone_pid))//私人推广位 { string username = memberAdzone.adzone_pid_cps_name; sn_cps = CpsClient.Members.FirstOrDefault(f => f.cpstype == CpsType.苏宁易购 && f.username == username); pid = memberAdzone.adzone_pid; isDefault = false; } } if (isDefault)//默认推广位 { sn_cps = CpsClient.Members.FirstOrDefault(f => f.cpstype == CpsType.苏宁易购 && f.username == ((member.buy_point >= Config.Point && member.finish_order >= Config.OrderNum) ? snInfoTemp.pid_chief_cps_name : snInfoTemp.pid_deputy_cps_name));//通过判断用户的购物积分,来判断用户使用哪个推广位 pid = ((member.buy_point >= Config.Point && member.finish_order >= Config.OrderNum) ? snInfoTemp.pid_chief : snInfoTemp.pid_deputy); } #endregion if (sn_cps == null) throw new Exception("@苏宁易购推广位异常,请检测后重试!"); if (string.IsNullOrWhiteSpace(pid)) throw new Exception("@苏宁易购推广位为空,请检测后重试!"); var api = CpsClient.CreateSuNingRequest(sn_cps); if (api == null) throw new Exception("@创建苏宁易购API请求失败"); #region 判断商品Id是否为屏蔽的商品 if (Class1.Config.ItemIDRestrictList.Contains(snid.goodid)) { e.SendMessage(Config.ItemIDRestrictTip.Replace("[商品ID]", snid.goodid)); return; } #endregion if (!ApiClient.Setting.SystemConfig.message_warning_switch) e.SendMessage(Config.SearchingTip);//正在搜索提示 var snGInfo = api.QueryGoodInfo($"{snid.goodid}-{snid.shop}"); if (snGInfo.sn_responseContent.sn_error != null) throw new Exception(snGInfo.sn_responseContent.sn_error.error_msg);//查询没结果 else if (snGInfo.sn_responseContent.sn_body == null || snGInfo.sn_responseContent.sn_body.queryCommoditydetail == null || snGInfo.sn_responseContent.sn_body.queryCommoditydetail.Count == 0) throw new Exception("查询没结果2"); foreach (var item in snGInfo.sn_responseContent.sn_body.queryCommoditydetail) { #region 判断店铺ID是否为屏蔽的店铺 if (!string.IsNullOrWhiteSpace(item.commodityInfo.supplierCode)) { if (Config.SellerIDRestrictlist.Contains(item.commodityInfo.supplierCode)) { e.SendMessage(Config.SellerIDRestrictTip.Replace("[店铺ID]", item.commodityInfo.supplierCode).Replace("[店铺名称]", item.commodityInfo.supplierName)); return; } } #endregion var vipPrice = -1d; if (!string.IsNullOrWhiteSpace(item.commodityInfo.snPrice)) vipPrice = double.Parse(item.commodityInfo.snPrice); if (vipPrice == -1 && !string.IsNullOrWhiteSpace(item.commodityInfo.commodityPrice)) vipPrice = double.Parse(item.commodityInfo.commodityPrice); var buyUrl = item.commodityInfo.productUrl; if (item.pgInfo != null) { if (!string.IsNullOrWhiteSpace(item.pgInfo.pgUrl)) { buyUrl = item.pgInfo.pgUrl; if (!string.IsNullOrWhiteSpace(item.pgInfo.pgUrl)) { vipPrice = double.Parse(item.pgInfo.pgPrice); } } } if (vipPrice == -1) throw new Exception("当前价格不明"); //优惠券金额 var coupon_price = 0.00d; //怕两个地址都没有链接.用自己拼的 if (string.IsNullOrWhiteSpace(buyUrl)) buyUrl = $@"https://product.suning.com/{snid.shop}/{snid.goodid}.html"; //优惠券地址 var couponUrl = (item.couponInfo != null && !string.IsNullOrWhiteSpace(item.couponInfo.couponUrl)) ? item.couponInfo.couponUrl : string.Empty; //优惠券地址 //var coupon_click_url = string.Empty; if (Config.NoCouponModeSwitch != SwitchType.开启) { if (!string.IsNullOrWhiteSpace(couponUrl))//有券 { //优惠券没有过期 if (item.couponInfo.couponEndTime >= DateTime.Now && ( (!string.IsNullOrWhiteSpace(item.couponInfo.bounsLimit) && double.Parse(item.couponInfo.bounsLimit) <= vipPrice) || (string.IsNullOrWhiteSpace(item.couponInfo.bounsLimit)) ) ) coupon_price = double.Parse(item.couponInfo.couponValue); } } //商品标题//< >&"© <,>,&,",©; goodsName = item.commodityInfo.commodityName.Replace("‮", "").Replace("<", "<").Replace(">", ">").Replace("&", "&").Replace(""", "\"").Replace(" ©", "©"); var endPrice = vipPrice; if (coupon_price != 0) endPrice = (double)((decimal)vipPrice - (decimal)coupon_price); //佣金比例 var commissionRate = double.Parse(item.commodityInfo.rate); //券后 总佣金 var useCoupon_totalCommFee = Math.Round(endPrice * (commissionRate / 100.00), 2); //用券后 给用户的佣金 var useCoupon_commFee = session.FindItemPoint(member, useCoupon_totalCommFee, 1, CpsType.苏宁易购, out compute); Compute compute1 = null; //不用券 佣金 var unuseCoupon_totalCommFee = Math.Round(vipPrice * (commissionRate / 100.00), 2); //不用券 给用户的佣金 var unuseCoupon_commFee = session.FindItemPoint(member, unuseCoupon_totalCommFee, 1, CpsType.苏宁易购, out compute1); if (compute == null) compute = compute1; var storeName = item.commodityInfo.supplierName; #region 转链 //pid=(?.+?)\sr=(?<机器人名>.*?)\st=(?<类型>\d+)\su=(?<会员名>.+?)\smid=(?<店铺ID>\d+)\sgid=(?<商品ID>\d+) var custom = Util.EncryptDES($"pid={pid} r={e.RobotName} t={(int)e.RobotInfo.type} u={e.GetMemberinfo().username} mid={item.commodityInfo.supplierCode} gid={snid.goodid} g={e.Groupid}"); var extension = api.GetExtensionUrl(custom, buyUrl, couponUrl); if (extension.sn_responseContent.sn_body == null) throw new Exception(); #endregion var picUrl = (item.commodityInfo.pictureUrl != null && item.commodityInfo.pictureUrl.Count != 0) ? item.commodityInfo.pictureUrl[0].picUrl : string.Empty; #region 正常订单 //有券的情况 if (coupon_price != 0) { var mess = string.Empty; if (e.ChatType == ChatType.微信 || e.ChatType == ChatType.企业微信 || (e.ChatType == ChatType.QQ && string.IsNullOrWhiteSpace(Config.QQSearchSuccessWithCouponTip))) mess = Config.SearchSuccessWithCouponTip; else mess = Config.QQSearchSuccessWithCouponTip; e.SendMessage(mess .Replace("劵", "券") .Replace("[商品标题]", mess.Contains("", "") : goodsName) .Replace("[商品原价]", string.Format("{0:F}", vipPrice)) .Replace("[商品主图]", $"[图片={picUrl}]") .Replace("[图片地址]", picUrl) .Replace("[店铺名称]", storeName) .Replace("[券后返利]", string.Format("{0:F}", useCoupon_commFee.UserPoint)) .Replace("[弃券返利]", string.Format("{0:F}", unuseCoupon_commFee.UserPoint)) .Replace("[券后价]", string.Format("{0:F}", endPrice)) .Replace("[优惠券金额]", string.Format("{0:F}", coupon_price)) .Replace("[购买地址]", extension.sn_responseContent.sn_body.getExtensionlink.shortLink) .Replace("[共节省]", ((decimal)coupon_price + (decimal)useCoupon_commFee.UserPoint).ToString()) .Replace("[商品图片]", mess.Contains("[商品图片]") ? "[图片=" + ApiClient.GetQRImage(goodsName, string.Format("{0:F}", vipPrice), string.Format("{0:F}", coupon_price), string.Format("{0:F}", endPrice), picUrl, couponUrl, ApiClient.QrImageType.模板B, CpsType.苏宁易购) + "]" : string.Empty) ); } else//没有券的情况 { var mess = string.Empty; if (e.ChatType == ChatType.微信 || e.ChatType == ChatType.企业微信 || (e.ChatType == ChatType.QQ && string.IsNullOrWhiteSpace(Config.QQSearchSuccessWithoutCouponTip))) mess = Config.SearchSuccessWithoutCouponTip; else mess = Config.QQSearchSuccessWithoutCouponTip; e.SendMessage(mess .Replace("[商品标题]", mess.Contains("", "") : goodsName) .Replace("[商品原价]", string.Format("{0:F}", vipPrice)) .Replace("[商品主图]", $"[图片={picUrl}]") .Replace("[图片地址]", picUrl) .Replace("[店铺名称]", storeName) .Replace("[返利积分]", string.Format("{0:F}", unuseCoupon_commFee.UserPoint)) .Replace("[购买地址]", extension.sn_responseContent.sn_body.getExtensionlink.shortLink) .Replace("[共节省]", string.Format("{0:F}", useCoupon_commFee.UserPoint)) .Replace("[商品图片]", mess.Contains("[商品图片]") ? "[图片=" + ApiClient.GetQRImage(goodsName, string.Format("{0:F}", vipPrice), "0", string.Format("{0:F}", vipPrice), picUrl, couponUrl, ApiClient.QrImageType.模板B, CpsType.苏宁易购) + "]" : string.Empty) ); } #endregion #region 记录用户信息,宝贝信息,平台信息,查询时间等 session.Insertable(new fl_query_hist() { crt_time = DateTime.Now, type = CpsType.苏宁易购, itemid = snid.goodid, groupid = e.Groupid, robot_name = e.RobotName, robot_type = e.ChatType, userid = member.id, title = goodsName, adzoneid = pid, mallid = item.commodityInfo.supplierCode, compute_configdic = compute == null ? string.Empty : JsonConvert.SerializeObject(compute) }).ExecuteCommand(); session.UpdateRecord(member.id); var shared = new Dictionary(); shared["msg_type"] = "查询宝贝"; shared["cps_type"] = CpsType.苏宁易购; shared["msg_username"] = member.username; shared["price"] = string.Format("{0:F}", vipPrice); shared["title"] = goodsName; shared["coupon_price"] = string.Format("{0:F}", (coupon_price != 0 ? coupon_price : 0)); shared["user_point"] = coupon_price != 0 ? string.Format("{0:F}", useCoupon_commFee.UserPoint) : string.Format("{0:F}", unuseCoupon_commFee.UserPoint); shared["economize"] = string.Format("{0:F}", (coupon_price != 0 ? ((decimal)coupon_price + (decimal)useCoupon_commFee.UserPoint) : (decimal)useCoupon_commFee.UserPoint)); var sharedEvent = new SharedEvents(shared); EventClient.OnEvent(sender, sharedEvent); #endregion } } catch (Exception ex) { e.SendMessage(Config.SearchNoCommissionTip.Replace("[关键词]", goodsName).Replace("[商品标题]", goodsName));//未搜索到提示语 var db = ApiClient.GetSession(); db.UpdateRecord(e.GetMemberinfo().id); var shared = new Dictionary(); shared["msg_type"] = "查询宝贝"; shared["cps_type"] = CpsType.苏宁易购; shared["msg_username"] = e.GetMemberinfo().username; shared["price"] = "未知"; shared["title"] = goodsName; shared["coupon_price"] = "未知"; shared["user_point"] = "未知"; shared["economize"] = "未知"; var sharedEvent = new SharedEvents(shared); EventClient.OnEvent(sender, sharedEvent); if (!ex.Message.Contains("查询没结果")) throw ex; } #endregion } catch (Exception ex) { if (ex.Message.StartsWith("@")) this.OnLog($"W :({e.RobotInfo.nick}【{e.RobotInfo.name}】){ex.Message.Replace("@", "")}"); else this.OnLog($"W:({e.RobotInfo.nick}【{e.RobotInfo.name}】){ex.Message} - {ex.StackTrace}"); this.OnLog(ApiClient.Setting.SystemConfig.msg_error); } } #endregion public override void ShowForm() { try { if (mainForm == null || mainForm.IsDisposed) { mainForm = new MainForm(); mainForm.Show(); } mainForm.TopMost = true; mainForm.TopMost = false; } catch (Exception ex) { this.OnLog(ex.Message); } } public override void Stop() { try { if (mainForm != null) { mainForm.CloseForm(); mainForm = null; } } catch (Exception ex) { this.OnLog(ex.Message); } } #region 变量替换 /// /// 订单状态 提示语替换 /// /// /// /// private string _GetOrderStateMess(SystemOrderStatus order, params object[] objs) { var mess = string.Empty; switch (order) { case SystemOrderStatus.订单付款: mess = new VariateReplace().CommonReplace(Config.OrderPaymentTip, objs); break; case SystemOrderStatus.订单失效: mess = new VariateReplace().CommonReplace(Config.OrderFailureTip, objs); break; case SystemOrderStatus.全额退款: case SystemOrderStatus.部分退款: case SystemOrderStatus.订单维权中: mess = new VariateReplace().CommonReplace(Config.OrderRefundTip, objs); break; case SystemOrderStatus.订单结算: mess = new VariateReplace().CommonReplace(Config.OrderSettlementTip, objs); break; case SystemOrderStatus.订单冻结: mess = new VariateReplace().CommonReplace(Config.OrderFreezeTip, objs); break; } return mess; } #endregion } }