using Api.Framework; using Api.Framework.Cps; 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 Chat.Framework.WXSdk.Events; using Chat.Framework.WXSdk.Implement; using CsharpHttpHelper; using CsharpHttpHelper.Enum; using Newtonsoft.Json; using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; using System.Threading; using TBRebate.Properties; using static Api.Framework.Tools.TBHelper; using static Api.Framework.Tools.TBHelper.TbAnalysis; using static TBRebate.Enums; namespace TBRebate.Uses { public class MessageOperation { ReciveIMEvent e = null; Class1 plugin = null; object sender = null; public MessageOperation(object sender, ReciveIMEvent e, Class1 plugin) { this.e = e; this.plugin = plugin; this.sender = sender; } #region 订单绑定 public bool BindOrderId() { try { //淘宝订单绑定 var orderid = e.Message.Trim(); if (Regex.IsMatch(e.Message.Trim(), @"^(\d{4})\s(\d{4})\s(\d{4})\s(\d{4})\s(\d{3})$")) orderid = orderid.Replace(" ", ""); if (!Regex.IsMatch(orderid, @"^\d{18,19}$")) return false; var db = ApiClient.GetSession(); var oid = long.Parse(orderid); if (oid >= 4000000000000000000) return false; var orderList = db.Find("select * from fl_order_alimama where trade_parent_id = @trade_parent_id", new { trade_parent_id = orderid }); var memberTmp = e.GetMemberinfo(); if (orderList != null && orderList.Count != 0) { var member = orderList.FirstOrDefault(f => f.db_userid != 0 && f.db_userid != memberTmp.id); if (member != null) { //订单已经被他人绑定 e.SendMessage(Class1.Config.OccupyOrderErrorTip.Replace("[订单号]", orderid)); return true; } var notices = new List(); var downAliTimer = new DownAlimamaTimer(); #region 订单用户已经绑定 纯提示,非结算的订单也提示上级 var bindOrders = orderList.Where(f => f.db_userid != 0).ToList(); if (bindOrders != null && bindOrders.Count != 0) { foreach (var order in bindOrders) { var point = HttpHelper.JsonToObject(order.db_point) as ItemPoint; memberTmp = e.GetMemberinfo(true); if (order.db_status == SystemOrderStatus.订单付款) e.SendMessage(new VariateReplace().CommonReplace(Class1.Config.OrderRepetBindTip, order, memberTmp, point)); else e.SendMessage(Class1._GetOrderStateMess(order.db_status, (order.db_status == SystemOrderStatus.订单结算 ? SettleType.已结算提示 : SettleType.未结算提示), order, memberTmp, point)); Thread.Sleep(500); } //return; } #endregion #region 订单没有被绑定(两种情况 => 一个订单已经被结算 一个是订单未结算) var notBindOrders = orderList.Where(f => f.db_userid == 0).ToList(); if (notBindOrders != null && notBindOrders.Count != 0) { if (notBindOrders[0].create_time < ApiClient.Setting.SystemConfig.allow_bind_create_order_time) { e.SendMessage($"订单:{orderid},已经过了有效绑定时间!"); return true; } foreach (var order in notBindOrders) { if (order.db_status == SystemOrderStatus.订单结算) order.db_endtime = DateTime.Now.AddMinutes(-2);//重新结算的话,需要将订单的冻结时间重新赋值,让后台处理 //没有绑定用户的订单进行绑定 order.db_userid = memberTmp.id; order.db_robotname = e.RobotName; order.db_robottype = e.RobotInfo.type; order.msg_groupid = e.Groupid; bool is_allrebatesactivity = false; #region 全额返利绑定 并且 将返利积分进行固定 var adzone = db.FindAdzoneInfos().FirstOrDefault(f => f.alliance_id == (int)CpsType.阿里妈妈 && f.custom_type == Resources.TbAllRebatesSoftwareType && f.adzone_pid.EndsWith("_" + order.adzone_id)); if (adzone != null) { var itemIdB = ApiClient.GetValidItemId(order.num_iid); var allrebatesactivity_infos = db.Find("select * from fl_plugin_allrebatesactivity_info where goods_id = @goods_id", new { goods_id = itemIdB }); if (allrebatesactivity_infos != null && allrebatesactivity_infos.Count != 0) { var allrebatesactivity_info = allrebatesactivity_infos.FirstOrDefault(f => f.time_begin <= order.create_time && order.create_time <= f.time_end && f.groups.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries).Select(z => Convert.ToInt64(z.Trim())).ToList().Contains(memberTmp.group_id) && f.robots.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries).Select(z => z.Trim()).ToList().Contains(order.db_robotname)); if (allrebatesactivity_info != null) { var allrebatesactivity_orderlists = db.Find("select * from fl_plugin_allrebatesactivity_orderlist where activity_id = @activity_id and mid = @mid", new { activity_id = allrebatesactivity_info.id, mid = memberTmp.id }); int purchased_quantity = 0;//已经购买的数量 if (allrebatesactivity_orderlists != null && allrebatesactivity_orderlists.Count != 0) { foreach (var item in allrebatesactivity_orderlists) { var order_alimama = db.FindSingle("select * from fl_order_alimama where id = @id", new { id = item.oid }); if (order_alimama != null && (order_alimama.db_status == SystemOrderStatus.订单结算 || order_alimama.db_status == SystemOrderStatus.全额退款 || order_alimama.db_status == SystemOrderStatus.部分退款 || order_alimama.db_status == SystemOrderStatus.订单付款 || order_alimama.db_status == SystemOrderStatus.订单冻结 || order_alimama.db_status == SystemOrderStatus.订单退款 || order_alimama.db_status == SystemOrderStatus.订单维权中)) purchased_quantity += order_alimama.item_num; } } if (allrebatesactivity_info.limit_quantity_number >= (order.item_num + purchased_quantity)) { is_allrebatesactivity = true; var return_money = (double)((decimal)allrebatesactivity_info.return_money * (decimal)order.item_num); var point = @"{""Type"":0,""Commission"":0,""SumPoint"":" + order.pub_share_pre_fee + @",""UserPoint"":" + return_money + @",""AwardOne"":0,""AwardTwo"":0,""AwardThree"":0,""AwardCreate"":0}"; order.db_point = point; order.db_userpoint = return_money; var robot = db.FindRobots().FirstOrDefault(f => f.name == order.db_robotname && order.db_robottype == f.type); if (robot != null) { var allrebatesactivity_orderlist = new fl_plugin_allrebatesactivity_orderlist() { activity_id = allrebatesactivity_info.id, mid = memberTmp.id, rid = robot.id, oid = order.id }; db.Saveable(allrebatesactivity_orderlist).ExecuteCommand(); } } } } } #endregion #region 手动绑定,重新计算用户的返利积分 if (!is_allrebatesactivity) { //判断是否为淘礼金订单,如果是淘礼金订单将不给这个订单返利 var isTljOrder = db.CheckIsTljOrder(order.adzone_id); //计算的佣金 - 判断使用设置模式,符合将扣除用户自定义预扣佣金 var commission = db.GetTbComparisonFeeRate(order); #region 历史查询时使用的比例 //查询历史查询比例 var compute = db.FindQueryRatioHist(CpsType.阿里妈妈, order.id); if (compute == null) { var itemIdB = ApiClient.GetValidItemId(order.num_iid); var query_item = db.FindSingle("select * from fl_query_hist where userid = @userid and itemid = @itemid and adzoneid = @adzoneid order by id desc", new { userid = memberTmp.id, itemid = itemIdB, adzoneid = order.adzone_id }); //计算公式不为空 if (query_item != null && !string.IsNullOrWhiteSpace(query_item.compute_configdic)) { try { compute = JsonConvert.DeserializeObject(query_item.compute_configdic); var queryRatioHist = new fl_query_ratio_hist() { compute_config = query_item.compute_configdic, db_orderid = order.id, createtime = DateTime.Now, cpstype = CpsType.阿里妈妈 }; db.SaveOrUpdate(queryRatioHist); } catch (Exception ex) { EventClient.OnEvent("淘宝计算", $"获取历史查询比异常:{ex.Message}"); } } } #endregion ItemPoint itempoint = null; //计算的佣金 if (compute != null) itempoint = db.FindItemPoint(CpsType.阿里妈妈, compute, isTljOrder ? 0 : commission, order.item_num); else itempoint = db.FindItemPoint(memberTmp, isTljOrder ? 0 : commission, order.item_num, CpsType.阿里妈妈); if (itempoint != null) { order.db_point = HttpHelper.ObjectToJson(itempoint); order.db_userpoint = itempoint.UserPoint; } } #endregion #region 用户的完成订单数量加1 if (memberTmp != null) { memberTmp.bind_order++; memberTmp = db.UpdateMemberGroup(memberTmp); } #endregion #region 首次付款时间 var record = db.FindStatisticsRecord(memberTmp.id); if (record == null) { record = new fl_statistics_record() { uid = memberTmp.id, ex2 = 0, ex4 = CsharpHttpHelper.HttpExtend.GetTimeStamp(DateTime.Now) }; db.Saveable(record).ExecuteCommand(); } else { if (record.ex2 == 0 && record.ex4 == 0) { record.ex4 = HttpExtend.GetTimeStamp(DateTime.Now); db.Saveable(record).ExecuteCommand(); } } #endregion db.SaveOrUpdate(order); #region 淘宝订单尾号自动采集 if (ApiClient.Setting.SystemConfig.order_alimama_last_auto_capture == SwitchType.开启) { //订单尾号和用户进行绑定 if (db.FindAlimamaOrderLastnums().FirstOrDefault(f => f.userid == memberTmp.id) == null) { db.Insertable(new fl_alimama_order_lastnum() { userid = memberTmp.id, lastnumber = order.trade_parent_id.Substring(order.trade_parent_id.Length - 6, 6) }).ExecuteCommand(); db.FindAlimamaOrderLastnums(true); } } #endregion //var strb = new StringBuilder(); //try //{ // strb.Append($@"淘宝订单ID BIND 数据: {HttpHelper.ObjectToJson(order)}"); //} //catch (Exception) //{ } downAliTimer.UpdateOrder(order, notices, db, isFrontData: true); //try //{ // strb.AppendLine($@"返回: {HttpHelper.ObjectToJson(order)}"); // EventClient.OnEvent("淘宝订单_: ", strb.ToString()); //} //catch (Exception) //{ } } } #endregion #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 //plugin.SDK_OrderNoticeEvent(this, item); } } #endregion } else { #region 未找到订单,提示用户并且加入绑定缓存中 e.SendMessage(Class1.Config.NotFoundOrderErrorTip.Replace("[订单号]", orderid)); var bind = db.FindBindCache(orderid); if (bind == null) { db.Insertable(new fl_bind_cache() { crt_time = DateTime.Now, db_robotid = e.RobotInfo.id, orderid = orderid, groupid = e.Groupid, db_userid = memberTmp.id }).ExecuteCommand(); db.FindBindCache(orderid, true); } #endregion } //消息已经处理完成,将不往后面的插件传递 e.Cancel = true; return true; } catch (Exception ex) { plugin.OnLog($"手动绑定订单号异常:{ex.Message}_{ex.StackTrace}"); } return false; } #endregion private Dictionary debutTimes = new Dictionary(); private void debug(string source, string msg) { return; var start = DateTime.Now; if (debutTimes.ContainsKey(source)) { start = debutTimes[source]; } else { debutTimes[source] = start; } plugin.OnLog($"{source} - {(DateTime.Now - start).TotalSeconds} - {msg}"); } public bool AnalyseFanLi() { Compute compute = null; var msgid = Guid.NewGuid().ToString(); try { var db = ApiClient.GetSession(); var tbinfoTemps = db.FindTbInfoTempGroups(); var tbInfoTemp = tbinfoTemps.FirstOrDefault(f => f.name == e.RobotInfo.name && f.onoff == false); if (tbInfoTemp == null) return false; var memberTmp = e.GetMemberinfo(); var message = e.Message.Trim(); //推广位 var pid = string.Empty; #region 判断使用的推广位 (群推广/私人推广位/默认推广位) var isDefaultPid = true; #region 判断消息是否为群消息并且判断群是否设置了群pid if (!string.IsNullOrWhiteSpace(e.Groupid)) { var groupAdzone = db.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)) { pid = groupAdzone.adzone_pid; isDefaultPid = false; } } #endregion #region 判断消息是否为私人消息并且判断私人是否设置了私人pid if (isDefaultPid) { var memberAdzone = db.FindAdzoneInfos().FirstOrDefault(f => f.alliance_id == (int)CpsType.阿里妈妈 && f.custom_type == PrivateAdzoneCustomType.用户私人pid.ToString() && f.member_id == memberTmp.id); if (memberAdzone != null && !string.IsNullOrWhiteSpace(memberAdzone.adzone_pid))//私人推广位 { pid = memberAdzone.adzone_pid; isDefaultPid = false; } } #endregion if (isDefaultPid)//默认推广位 { var tgw = Tools.GetTuiguangwei(e.RobotInfo.name, memberTmp, tbInfoTemp); if (tgw == null || string.IsNullOrWhiteSpace(tgw.Pid)) throw new Exception("@阿里妈妈推广位异常.请检测后重试!!"); pid = tgw.Pid; } #endregion var pids = pid.Split(new string[] { "_" }, StringSplitOptions.RemoveEmptyEntries); if (pids == null || pids.Length == 0) throw new Exception("推广位数据异常,请重新设置推广位"); var tb_cps = CpsClient.Members.FirstOrDefault(f => f.cpstype == CpsType.阿里妈妈 && f.username == pids[1]); if (tb_cps == null) throw new Exception($"@阿里妈妈推广位异常,请检测后重试!,{pid}"); //关键词/标题 var keyword = string.Empty; //是否是标题 var IsTitle = false; var api = CpsClient.CreateAlimamaRequest(tb_cps); if (api == null) throw new Exception("@创建阿里妈妈API请求失败"); #region 自定义搜索 (例:找衣服) if (Class1.Config.SearchCustomSwitch == SwitchType.开启) { if (!string.IsNullOrWhiteSpace(Class1.Config.SearchPrefix)) { //判断接收到的内容是都满足标题搜索或者关键词搜索 var reg = Regex.Match(message, Class1.Config.SearchPrefix);//获取到符合关键词搜索的正则 if (reg.Success) { keyword = reg.Groups["关键词"].Value.Trim(); if (Class1.Config.SearchTitleSwitch == SwitchType.开启)//开启淘宝标题搜索 { var ileng = Tools.GetStringLength(keyword);//这里判断字符串的长度为 30个汉字,或者60个字节 if (ileng >= 40 && ileng <= 100 && !Regex.IsMatch(keyword, HttpExtend.REGEX_GETURL, RegexOptions.IgnoreCase))//非链接并且字符串字节长度符合小于等于40,大等于60的条件,才去查询标题 IsTitle = true; } if (!IsTitle && !string.IsNullOrEmpty(keyword)) { var searchUrl = api.ComposeTbCms(pid, keyword);//内置的搜索机制 e.SendMessage(Class1.Config.PreciseSearchSuccessTip.Replace("[关键词]", keyword).Replace("[购买地址]", ApiClient.ShortURL(searchUrl, Class1.Config.SearchDwzType).Result)); return true; } } } } #endregion #region 判断消息是否符合标题验证,如果符合将判断为标题搜索 if (string.IsNullOrEmpty(keyword) && Class1.Config.SearchTitleSwitch == SwitchType.开启 && !Regex.IsMatch(message, Tools.Reg_QRCode_Goods))//开启淘宝标题搜索 { var tklreg = TbAnalysis.GetTklReg(); if ((!Regex.IsMatch(message, "[^A-Za-z0-9]?([A-Za-z0-9]{11})[^A-Za-z0-9]?") && !Regex.IsMatch(message, tklreg)) && !Regex.Match(message, @"[!,<>!@#\$%\^&*()_+~>·@#¥%……&*()——+,。、!?\?]").Success) { var wx = sender as WeixinBase; var wfm = e.Event as WXReiceveFriendMsg; if (wx != null && ((wfm != null && !wfm.IsRobot) || e.Event is WXReceiveGroupMsg)) { var ileng = Tools.GetStringLength(message);//这里判断字符串的长度为 30个汉字,或者60个字节 if (ileng >= 40 && ileng <= 100 && !Regex.IsMatch(message, HttpExtend.REGEX_GETURL, RegexOptions.IgnoreCase))//非链接并且字符串字节长度符合小于等于40,大等于60的条件,才去查询标题 { keyword = message; IsTitle = true; } } } } #endregion #region 宝贝二维码识别 string QRCodeUrl = string.Empty; if (Class1.Config.QRCodeSearchSwitch == SwitchType.开启) { var reg_ = Regex.Match(message, Tools.Reg_QRCode_Goods); if (reg_.Success) { QRCodeUrl = Util.DecodeQRCode(reg_.Groups["二维码图片"].Value);//解析的二维码图片所得到的二维码内容 message = message.Replace(reg_.Groups["二维码图片"].Value, ""); } } #endregion var tbAnalysis = new TbAnalysis(); var title = string.Empty;//商品标题 //商品id var item_id = string.Empty; try { item_id = tbAnalysis.FindItemIdByUrlAndTklAndMkl(string.IsNullOrEmpty(QRCodeUrl) ? message : QRCodeUrl, api, pids); //TODO 淘宝商品Id转成字符串Id } catch (Exception ex) { #region 获取标题xxx if (string.IsNullOrWhiteSpace(keyword)) { //try //{ // var sss = api.SendTaobao("taobao.wireless.share.tpwd.query", new { password_content = e.Message }); //} //catch (Exception ex1) //{ //} //var _title = Tools.GetGoodTitle(e.Message).Result; //if (!string.IsNullOrWhiteSpace(_title)) // title = _title; } #endregion if (!ex.Message.Contains("淘口令解析结果无效,当前淘口令无效") && string.IsNullOrEmpty(keyword) && string.IsNullOrWhiteSpace(title)) { e.SendMessage(Class1.Config.SearchNoCommissionTip.Replace("[关键词]", "").Replace("[商品标题]", "")); db.UpdateRecord(memberTmp.id); var shared = new Dictionary(); shared["msg_type"] = "查询宝贝"; shared["cps_type"] = CpsType.阿里妈妈; shared["msg_username"] = memberTmp.username; shared["price"] = "未知"; shared["title"] = title ?? keyword; shared["coupon_price"] = "未知"; shared["user_point"] = "未知"; shared["economize"] = "未知"; var sharedEvent = new SharedEvents(shared); EventClient.OnEvent(sender, sharedEvent); } return true; } #region 忽略的商品id 与 限制商品Id if (!string.IsNullOrWhiteSpace(item_id)) { #region 忽略的商品id var temp = Class1.ignoreidsCache.FirstOrDefault(f => f.itemid == item_id); if (temp != null && temp.losetime >= HttpExtend.GetTimeStamp(DateTime.Now)) { e.SendMessage(Class1.Config.SearchNoCommissionTip.Replace("[关键词]", "").Replace("[商品标题]", "")); db.UpdateRecord(memberTmp.id); var shared = new Dictionary(); shared["msg_type"] = "查询宝贝"; shared["cps_type"] = CpsType.阿里妈妈; shared["msg_username"] = memberTmp.username; shared["price"] = "未知"; shared["title"] = title ?? keyword; shared["coupon_price"] = "未知"; shared["user_point"] = "未知"; shared["economize"] = "未知"; var sharedEvent = new SharedEvents(shared); EventClient.OnEvent(sender, sharedEvent); return true; } #endregion #region 限制商品ID if (Class1.Config.ItemIDRestrictList.Contains(item_id)) { e.SendMessage(Class1.Config.ItemIDRestrictTip.Replace("[商品ID]", item_id)); return true; } #endregion } #endregion #region 标题搜索和商品id搜索 if (!string.IsNullOrWhiteSpace(title) || !string.IsNullOrEmpty(keyword) || !string.IsNullOrEmpty(item_id)) { if (!ApiClient.Setting.SystemConfig.message_warning_switch) e.SendMessage(Class1.Config.SearchingTip); var titleSuccess = false;//判断是否是标题搜索 try { //是否检测优惠券金额等信息 (其他平台获取的优惠券信息/高佣查询的优惠券信息)不需要校验 var isCheckCoupon = true; Dictionary privilege = null; //累计推广位组调用次数 Tools.GroupAdzoneCount(memberTmp, tbInfoTemp); //商品的详细信息 Dictionary objData = null; if (!string.IsNullOrEmpty(keyword) && IsTitle && string.IsNullOrEmpty(item_id))//符合搜索标题查询宝贝 { try { objData = api.SendTaobao("taobao.tbk.sc.material.optional", new { adzone_id = pids[3], site_id = pids[2], q = keyword }); titleSuccess = true; } catch (Exception) { objData = null; } } else if (!string.IsNullOrEmpty(item_id))//符合搜索宝贝id的条件 { var biz_scene_id = TBHelper.TbAnalysis.BizSceneId(item_id); objData = api.SendTaobao("taobao.tbk.item.info.get", new { num_iids = item_id, biz_scene_id = biz_scene_id }); } //商品有返利 if (objData != null && objData.Count != 0) { #region 通过标题返回的结构 或者 通过商品id返回的结构 解析至相同部分 object tbk_temp_info = null; if (titleSuccess) { if (objData.ContainsKey("result_list")) { var result_list = objData["result_list"] as Dictionary; if (result_list != null && result_list.ContainsKey("map_data")) { var map_data = (result_list["map_data"]) as ArrayList; if (map_data != null && map_data.Count != 0) tbk_temp_info = map_data[0]; } } } else { var n_tbk_item = (objData["n_tbk_item"]) as ArrayList; if (n_tbk_item != null && n_tbk_item.Count != 0) tbk_temp_info = n_tbk_item[0]; } #endregion var tbk_item = tbk_temp_info as Dictionary; //店铺ID var sellerId = string.Empty; if (tbk_item.ContainsKey("pict_url")) { var reg = Regex.Match(tbk_item["pict_url"].ToString(), @"i\d+?/(?<店铺Id>\d+?)/"); if (reg.Success) { sellerId = reg.Groups["店铺Id"].Value; if (Class1.Config.SellerIDRestrictlist.Contains(sellerId)) { e.SendMessage(Class1.Config.SellerIDRestrictTip.Replace("[店铺ID]", sellerId)); return true; } } } //商品链接 var item_url = tbk_item["item_url"].ToString(); //店铺名称 var nick = tbk_item["nick"].ToString(); //商品主图 var pict_url = tbk_item["pict_url"].ToString(); //商品id item_id = tbk_item["num_iid"].ToString(); //商品标题//< >&"© <,>,&,",©; title = tbk_item["title"].ToString().Replace("‮", "").Replace("<", "<").Replace(">", ">").Replace("&", "&").Replace(""", "\"").Replace(" ©", "©");//这里有个看不见的字符,要将其替换掉 //原价 var reserve_price = double.Parse(tbk_item["reserve_price"].ToString()); //商品折扣价格(当前售价) var zk_final_price = double.Parse(tbk_item["zk_final_price"].ToString()); //30天销量 var volume = "0"; if (tbk_item.ContainsKey("volume")) volume = tbk_item["volume"].ToString(); //券后价 var endPrice = -1d; #region 检测连接中是否包含优惠券信息 并且 获取店铺id且判断店铺id是否被屏蔽 var activityIdTmp = string.Empty; var activityId = string.Empty; activityId = tbAnalysis.activityId; var urls = HttpExtend.RegexMatchesUrl(e.Message); if (urls != null && urls.Count != 0) { foreach (var url in urls) { if (url.ToLower().Contains("uland.taobao")) { var reg = Regex.Match(url, @"activityId=(?<活动ID>[A-Za-z0-9]+)", RegexOptions.IgnoreCase); if (reg.Success) { activityIdTmp = activityId = reg.Groups["活动ID"].Value; } #region 获取店铺ID并且检测是否为屏蔽的店铺 //https://uland.taobao.com/quan/detail?sellerId=2203061148088&activityId=91a71ae9a76445288724467712c0083d reg = Regex.Match(url, @"sellerId=(?<店铺ID>[^&]*)", RegexOptions.IgnoreCase); if (reg.Success) { sellerId = reg.Groups["店铺ID"].Value; //店铺id限制 if (Class1.Config.SellerIDRestrictlist.Contains(sellerId)) { e.SendMessage(Class1.Config.SellerIDRestrictTip.Replace("[店铺ID]", sellerId)); return true; } } #endregion break; } } } #endregion //最高佣金率 var commission_rate = 0d; //实时佣金的时候special_id不为空 var SpecialIdNotNull = false; #region 申请高佣(通过设置的返利模式获取对应的高佣信息) switch (Class1.Config.QueryComparisonSwitch) { case QueryComparisonType.查询使用实时佣金: { #region 获取用户的special_id if (string.IsNullOrWhiteSpace(e.Groupid)) { var special_id = string.Empty; var relation = db.FindTbRelations().FirstOrDefault(f => f.cps_memberid == api.Member.username && f.username == e.Username); if (relation != null) { try { privilege = tbAnalysis.GetPrivilege(api, item_id, pids, "2", e.Username, relation.special_id.ToString()); if (privilege != null) SpecialIdNotNull = true; } catch (Exception ex) { db.Deleteable(relation).ExecuteCommand(); } } if (privilege == null) { try { var _data = new { info_type = 2, relation_app = "common", external_id = e.Username, external_type = 1 }; special_id = tbAnalysis.FindTbPublisherInfoFirst(api, _data); if (!string.IsNullOrWhiteSpace(special_id)) SpecialIdNotNull = true; #endregion if (privilege == null || !privilege.ContainsKey("min_commission_rate")) privilege = tbAnalysis.GetPrivilege(api, item_id, pids, "2", SpecialIdNotNull ? e.Username : string.Empty, special_id); } catch (Exception ex) { } } } if (privilege == null) privilege = tbAnalysis.GetPrivilege(api, item_id, pids, "2"); } break; case QueryComparisonType.查询使用比价佣金: { if (privilege == null) privilege = tbAnalysis.GetPrivilege(api, item_id, pids, "2"); if (privilege != null && !privilege.ContainsKey("min_commission_rate")) { var privilege_temp = tbAnalysis.GetPrivilege(api, item_id, pids, "2", e.Username); if (privilege_temp != null) { var data_temp = privilege_temp["data"] as Dictionary; if (data_temp != null && data_temp.ContainsKey("min_commission_rate")) commission_rate = double.Parse(data_temp["min_commission_rate"].ToString()); } } } break; case QueryComparisonType.查询使用正常佣金: { if (privilege == null || !privilege.ContainsKey("max_commission_rate")) privilege = tbAnalysis.GetPrivilege(api, item_id, pids, "2"); } break; default: break; } #endregion if (privilege == null) throw new Exception("申请高佣失败,原因未知"); var privilege_data = privilege["data"] as Dictionary; #region 获取商品佣金 if (commission_rate == 0) { if (privilege_data.ContainsKey("max_commission_rate")) commission_rate = double.Parse(privilege_data["max_commission_rate"].ToString()); else if (privilege_data.ContainsKey("min_commission_rate")) commission_rate = double.Parse(privilege_data["min_commission_rate"].ToString()); } #endregion //新商品ID的话,获取新的字符串IdB段 if (privilege_data.ContainsKey("item_id")) { item_id = privilege_data["item_id"].ToString(); if (item_id.Contains("-")) { var split = item_id.Split(new string[] { "-" }, StringSplitOptions.RemoveEmptyEntries); item_id = split[1]; } } //优惠券地址 var coupon_click_url = string.Empty; //优惠券金额 var coupon_price = 0.00d; //优惠券满减比较的价格(原价和最终的价格,满减金额好像是通过判断原价进行比较的) var coupon_comparison_price = (reserve_price > zk_final_price ? reserve_price : zk_final_price); #region 有无券模式 获取对应的优惠券地址和优惠券金额 if (Class1.Config.NoCouponModeSwitch == SwitchType.关闭) { #region 获取最终的付款金额 与 优惠券链接 优惠券金额 //检测大淘客是否有优惠券,和价格 //TbExCoupon exCoupon = TBHelper.FindGoodsCouponInfo(item_id); //不要去获取外部的优惠券 TbExCoupon exCoupon = null; if (exCoupon != null) { activityId = exCoupon.activityId; sellerId = exCoupon.sellerId; coupon_price = exCoupon.couponAmount; //zk_final_price = exCoupon.salePrice; //这里因为外部获取到的金额有误差通过优惠券的判断,是使用外部获取的金额还是最终的金额 //if (zk_final_price != exCoupon.salePrice && zk_final_price > exCoupon.couponAmount) //{ } //else //{ // zk_final_price = exCoupon.salePrice; // endPrice = exCoupon.endPrice; //} //TODO 这里外部获取的价格不正确,都会不准 if (zk_final_price != exCoupon.salePrice) { //zk_final_price = exCoupon.salePrice; //coupon_comparison_price = zk_final_price; //zk_final_price = exCoupon.salePrice; coupon_comparison_price = zk_final_price; if (exCoupon.salePrice < zk_final_price) endPrice = exCoupon.endPrice; isCheckCoupon = false; } //正常优惠券 var coupon_price_temp = 0d; var condition_price_temp = 0d; if (privilege_data.ContainsKey("coupon_info")) { var quan_reg = Regex.Match(privilege_data["coupon_info"].ToString(), @"满(?<满>\d+)元减(?<减>\d+)元"); if (quan_reg.Success) { coupon_price_temp = double.Parse(quan_reg.Groups["减"].Value); condition_price_temp = double.Parse(quan_reg.Groups["满"].Value); } } //妈妈优惠券 var mm_coupon_price_temp = 0d; var mm_condition_price_temp = 0d; if (privilege_data.ContainsKey("mm_coupon_info")) { var mm_quan_reg = Regex.Match(privilege_data["mm_coupon_info"].ToString(), @"满(?<满>\d+)元减(?<减>\d+)元"); if (mm_quan_reg.Success) { mm_coupon_price_temp = double.Parse(mm_quan_reg.Groups["减"].Value); mm_condition_price_temp = double.Parse(mm_quan_reg.Groups["满"].Value); } } var coupon = 0d; if (zk_final_price >= mm_condition_price_temp) { if (mm_coupon_price_temp >= exCoupon.couponAmount) { activityId = string.Empty; coupon = mm_coupon_price_temp; if (privilege_data.ContainsKey("mm_coupon_click_url")) coupon_click_url = privilege_data["mm_coupon_click_url"].ToString(); endPrice = zk_final_price - mm_coupon_price_temp; coupon_price = mm_coupon_price_temp; } } if (zk_final_price >= condition_price_temp) { if (coupon_price_temp >= exCoupon.couponAmount && coupon_price_temp > coupon) { activityId = string.Empty; if (privilege_data.ContainsKey("coupon_click_url")) coupon_click_url = privilege_data["coupon_click_url"].ToString(); endPrice = zk_final_price - coupon_price_temp; coupon_price = coupon_price_temp; } //else if (condition_price_temp <= zk_final_price && condition_price_temp < exCoupon.salePrice) //{ //} } //if (string.IsNullOrWhiteSpace(coupon_click_url)) //{ // if (privilege_data.ContainsKey("coupon_click_url")) // coupon_click_url = privilege_data["coupon_click_url"].ToString(); // else if (privilege_data.ContainsKey("mm_coupon_click_url")) // coupon_click_url = privilege_data["mm_coupon_click_url"].ToString(); // else // coupon_click_url = privilege_data["item_url"].ToString(); //} //isCheckCoupon = false; } else { if (privilege_data.ContainsKey("mm_coupon_info") && privilege_data.ContainsKey("coupon_info")) { //正常优惠券 var coupon_price_temp = 0d; var condition_price_temp = 0d; var quan_reg = Regex.Match(privilege_data["coupon_info"].ToString(), @"满(?<满>\d+)元减(?<减>\d+)元"); if (quan_reg.Success) { coupon_price_temp = double.Parse(quan_reg.Groups["减"].Value); condition_price_temp = double.Parse(quan_reg.Groups["满"].Value); } //妈妈优惠券 var mm_coupon_price_temp = 0d; var mm_condition_price_temp = 0d; var mm_quan_reg = Regex.Match(privilege_data["mm_coupon_info"].ToString(), @"满(?<满>\d+)元减(?<减>\d+)元"); if (mm_quan_reg.Success) { mm_coupon_price_temp = double.Parse(mm_quan_reg.Groups["减"].Value); mm_condition_price_temp = double.Parse(mm_quan_reg.Groups["满"].Value); } var condition_price = 0d;//满减条件 if (mm_condition_price_temp <= coupon_comparison_price && condition_price_temp <= coupon_comparison_price) { if (mm_coupon_price_temp > coupon_price_temp) { coupon_price = mm_coupon_price_temp; condition_price = mm_condition_price_temp; coupon_click_url = privilege_data["mm_coupon_click_url"].ToString(); } else { coupon_price = coupon_price_temp; condition_price = condition_price_temp; coupon_click_url = privilege_data["coupon_click_url"].ToString(); } } //妈妈优惠券条件金额小于最小的售价并且妈妈优惠券金额比正常优惠券高 else if (mm_condition_price_temp <= coupon_comparison_price && mm_coupon_price_temp > coupon_price_temp) { coupon_price = mm_coupon_price_temp; condition_price = mm_condition_price_temp; coupon_click_url = privilege_data["mm_coupon_click_url"].ToString(); } //正常优惠券条件金额小于最小的售价并且正常优惠券金额比妈妈优惠券高 else if (condition_price_temp <= coupon_comparison_price && mm_coupon_price_temp < coupon_price_temp) { coupon_price = coupon_price_temp; condition_price = condition_price_temp; coupon_click_url = privilege_data["coupon_click_url"].ToString(); } else if (mm_condition_price_temp > coupon_comparison_price && condition_price_temp > coupon_comparison_price) { if (mm_coupon_price_temp < coupon_price_temp) { coupon_price = coupon_price_temp; condition_price = condition_price_temp; coupon_click_url = privilege_data["coupon_click_url"].ToString(); } else { coupon_price = mm_coupon_price_temp; condition_price = mm_condition_price_temp; coupon_click_url = privilege_data["mm_coupon_click_url"].ToString(); } } var multiple = Math.Ceiling(condition_price / coupon_comparison_price); if (multiple != 0) zk_final_price = zk_final_price * multiple; } else if (privilege_data.ContainsKey("mm_coupon_info")) { var quan_reg = Regex.Match(privilege_data["mm_coupon_info"].ToString(), @"满(?<满>\d+)元减(?<减>\d+)元"); if (quan_reg.Success) { coupon_price = double.Parse(quan_reg.Groups["减"].Value); var condition_price = double.Parse(quan_reg.Groups["满"].Value); var multiple = Math.Ceiling(condition_price / coupon_comparison_price); if (multiple != 0) zk_final_price = zk_final_price * multiple; coupon_click_url = privilege_data["mm_coupon_click_url"].ToString(); } } else if (privilege_data.ContainsKey("coupon_info")) { var quan_reg = Regex.Match(privilege_data["coupon_info"].ToString(), @"满(?<满>\d+)元减(?<减>\d+)元"); if (quan_reg.Success) { coupon_price = double.Parse(quan_reg.Groups["减"].Value); var condition_price = double.Parse(quan_reg.Groups["满"].Value); var multiple = Math.Ceiling(condition_price / coupon_comparison_price); if (multiple != 0) { var zk_final_priceTmp = zk_final_price * multiple; if (zk_final_priceTmp <= coupon_price) { var priceTmp = (decimal)zk_final_price * (decimal)Math.Ceiling(coupon_price / zk_final_price); zk_final_price = (double)Math.Round(priceTmp, 2); } else zk_final_price = zk_final_price * multiple; } coupon_click_url = privilege_data["coupon_click_url"].ToString(); } } } #endregion if (string.IsNullOrWhiteSpace(coupon_click_url)) { if (privilege_data.ContainsKey("mm_coupon_click_url")) coupon_click_url = privilege_data["mm_coupon_click_url"].ToString(); else if (privilege_data.ContainsKey("coupon_click_url")) coupon_click_url = privilege_data["coupon_click_url"].ToString(); else if (privilege_data.ContainsKey("item_url")) coupon_click_url = privilege_data["item_url"].ToString(); } #region 校验优惠券是否有效 (通过优惠券id和店铺id | 通过优惠券链接) if (isCheckCoupon && !string.IsNullOrWhiteSpace(activityId) && !string.IsNullOrWhiteSpace(sellerId)) { #region 获取优惠券金额 var hsf_coupon = AlimamaApi.mtop_alimama_union_hsf_coupon_get(sellerId, activityId); if (hsf_coupon != null) { if (hsf_coupon.ContainsKey("result")) { var result = hsf_coupon["result"] as Dictionary; var isValid = true; //var isValid = false; //if (result.ContainsKey("effectiveStartTime")) //{ // var effectiveStartTime = result["effectiveStartTime"].ToString(); // try // { // isValid = DateTime.Now >= DateTime.Parse(effectiveStartTime); // } // catch (Exception ex) // { } //} if (isValid) { if (result.ContainsKey("amount")) coupon_price = double.Parse(result["amount"].ToString()); if (result.ContainsKey("startFee")) { //zk_final_price = double.Parse(result["startFee"].ToString()); var startFee = double.Parse(result["startFee"].ToString()); var multiple = Math.Ceiling(startFee / coupon_comparison_price); if (multiple != 0) zk_final_price = zk_final_price * multiple; } } } } #endregion } else { //if (privilege_data.ContainsKey("coupon_start_time")) if (privilege_data.ContainsKey("coupon_start_time") && string.IsNullOrWhiteSpace(activityId)) { var coupon_start_time = DateTime.Parse(privilege_data["coupon_start_time"].ToString()) <= DateTime.Now.Date; isCheckCoupon = false; } if (isCheckCoupon) { if (!string.IsNullOrWhiteSpace(activityId)) coupon_click_url = coupon_click_url + "&activityId=" + activityId; var coupon = api.CheckCoupon(coupon_click_url);//检查优惠券有效性 if (coupon != null && coupon.retStatus != 0 && string.IsNullOrWhiteSpace(activityId))//优惠券过期 { coupon_click_url = privilege_data["item_url"].ToString(); coupon_price = 0.00d; zk_final_price = double.Parse(tbk_item["zk_final_price"].ToString()); } } } #endregion } else { coupon_click_url = privilege_data["item_url"].ToString(); coupon_price = 0.00d; } #endregion if (endPrice == -1 && zk_final_price > coupon_price) endPrice = (double)((decimal)zk_final_price - (decimal)coupon_price); else if (zk_final_price <= coupon_price) { coupon_price = 0; endPrice = zk_final_price; } //plugin.OnLog("_" + commission_rate); var useCoupon_totalCommFee = Math.Round(endPrice * (commission_rate / 100.00), 2); //用券后 给用户的佣金 var useCoupon_commFee = db.FindItemPoint(memberTmp, useCoupon_totalCommFee, 1, CpsType.阿里妈妈, out compute); Compute compute1 = null; //不用券 佣金 var unuseCoupon_totalCommFee = Math.Round(zk_final_price * (commission_rate / 100.00), 2); //不用券 给用户的佣金 var unuseCoupon_commFee = db.FindItemPoint(memberTmp, unuseCoupon_totalCommFee, 1, CpsType.阿里妈妈, out compute1); if (compute == null) compute = compute1; #region 淘礼金 生成淘礼金链接,如果返回空,这不能生成. var tljUrl = TljMethod(e.GetMemberinfo(true), ref api, item_id, useCoupon_commFee.UserPoint); if (!string.IsNullOrWhiteSpace(tljUrl)) { var _tlj = db.FindTljInfos().FirstOrDefault(f => f.username == api.Member.username); if (_tlj != null) pids = _tlj.adzone_pid.Split('_'); } #endregion //判断是否有淘礼金,有淘礼金用淘礼金,没有就用购物地址 var couponUrl = string.IsNullOrWhiteSpace(tljUrl) ? coupon_click_url : tljUrl; if (!string.IsNullOrWhiteSpace(activityId)) couponUrl = couponUrl + "&activityId=" + activityId; //更新私域用户备案信息 if (Class1.Config.QueryComparisonSwitch == QueryComparisonType.查询使用实时佣金 && !SpecialIdNotNull && string.IsNullOrWhiteSpace(e.Groupid)) { try { var tmpData2 = api.SendTaobao("taobao.tbk.sc.relation.record", new { external_id = e.Username, op_type = 2, redirect_url = couponUrl, external_type = 1 }); if (tmpData2.ContainsKey("data")) couponUrl = (tmpData2["data"] as Dictionary)["url"].ToString(); api.AddTBEid(e.Username); } catch (Exception ex) { plugin.OnLog($"更细私域异常关系 :({e.RobotInfo.nick}【{e.RobotInfo.name}】){ex.Message}"); } } #region 获取淘口令 tkl TklInfo tklInfo = null; var tkl = string.Empty; try { //生成淘口令的图片(看是否有设置自定义的图片) string _pict_url = pict_url; //生成淘口令的标题(看是否有设置自定义的标题) string _title = title; if (Class1.Config.TKLCustomSwitch == SwitchType.开启) { if (!string.IsNullOrWhiteSpace(Class1.Config.TKLImageUrl)) _pict_url = Class1.Config.TKLImageUrl; if (!string.IsNullOrWhiteSpace(Class1.Config.TKLTitle)) _title = Class1.Config.TKLTitle; } //生成淘口令 tklInfo = tbAnalysis.FindTKL(couponUrl, api); if (tklInfo == null) { e.SendMessage(Class1.Config.SearchNoCommissionTip?.Replace("[关键词]", keyword).Replace("[商品标题]", title));//未搜索到提示语 db.UpdateRecord(memberTmp.id); var shared1 = new Dictionary(); shared1["msg_type"] = "查询宝贝"; shared1["cps_type"] = CpsType.阿里妈妈; shared1["msg_username"] = memberTmp?.username; shared1["price"] = "未知"; shared1["title"] = title ?? keyword; shared1["coupon_price"] = "未知"; shared1["user_point"] = "未知"; shared1["economize"] = "未知"; var sharedEvent1 = new SharedEvents(shared1); EventClient.OnEvent(sender, sharedEvent1); return true; } } catch (Exception ex) { throw new Exception($"@获取淘口令异常:{ex.Message} - {ex.StackTrace}"); } #endregion //淘口令的前/后符号有没有设置.有设置将替换掉 tkl = tbAnalysis.ReplaceTklModifier(tklInfo.tkl); //中间页地址 //var composeUrl = api.ComposeTbClick(item_id, pict_url, tklInfo.tkl, couponUrl, true); var composeUrl = api.ComposeTbClick(item_id, pict_url, tklInfo.tkl, tklInfo.isoUrl, true, pid, ApiClient.Setting.SystemConfig.ZjyComposeType == ComposeType.有推荐商品); // 获取短连接 //couponUrl = tbAnalysis.FindShortUrlBySrcUrl(couponUrl, api); couponUrl = tklInfo.isoUrl; #region 淘礼金 if (!string.IsNullOrWhiteSpace(tljUrl)) { var mess = Class1.Config.TljSearchSuccess; e.SendMessage(mess .Replace("[商品标题]", mess.Contains("", "") : title) .Replace("[商品原价]", zk_final_price.ToString()) .Replace("[商品主图]", $"[图片={pict_url}]") .Replace("[图片地址]", pict_url) .Replace("[月销量]", volume) .Replace("[店铺名称]", nick) .Replace("[优惠券金额]", (coupon_price != 0 ? coupon_price.ToString() : "0")) .Replace("[淘礼金金额]", useCoupon_commFee.UserPoint.ToString()) .Replace("[购买地址]", couponUrl) .Replace("[购买中间页地址]", composeUrl) .Replace("[购买淘口令]", tkl) .Replace("[共节省]", ((decimal)coupon_price + (decimal)useCoupon_commFee.UserPoint).ToString()) .Replace("[商品图片]", mess.Contains("[商品图片]") ? "[图片=" + ApiClient.GetQRImage(title, zk_final_price.ToString(), coupon_price.ToString(), ((decimal)zk_final_price - (decimal)coupon_price).ToString(), pict_url, composeUrl, ApiClient.QrImageType.模板B, CpsType.阿里妈妈) + "]" : string.Empty) ); } #endregion #region 正常订单 else { //有券的情况 if (coupon_price != 0) { var mess = string.Empty; if (e.ChatType == ChatType.微信 || e.ChatType == ChatType.企业微信 || (e.ChatType == ChatType.QQ && string.IsNullOrWhiteSpace(Class1.Config.QQSearchSuccessWithCouponTip))) mess = Class1.Config.SearchSuccessWithCouponTip; else mess = Class1.Config.QQSearchSuccessWithCouponTip; e.SendMessage(mess .Replace("劵", "券") .Replace("[商品标题]", mess.Contains("", "") : title) .Replace("[商品原价]", string.Format("{0:F}", zk_final_price)) .Replace("[商品主图]", $"[图片={pict_url}]") .Replace("[图片地址]", pict_url) .Replace("[月销量]", volume) .Replace("[店铺名称]", nick) .Replace("[券后返利]", string.Format("{0:F}", useCoupon_commFee.UserPoint)) .Replace("[弃券返利]", string.Format("{0:F}", unuseCoupon_commFee.UserPoint)) .Replace("[券后价]", string.Format("{0:F}", endPrice)) .Replace("[优惠券金额]", coupon_price.ToString()) .Replace("[购买地址]", couponUrl) .Replace("[购买中间页地址]", composeUrl) .Replace("[购买淘口令]", tkl) .Replace("[共节省]", string.Format("{0:F}", ((decimal)coupon_price + (decimal)useCoupon_commFee.UserPoint))) .Replace("[商品图片]", mess.Contains("[商品图片]") ? "[图片=" + ApiClient.GetQRImage(title, zk_final_price.ToString(), coupon_price.ToString(), endPrice.ToString(), pict_url, composeUrl, ApiClient.QrImageType.模板B, CpsType.阿里妈妈) + "]" : string.Empty) .Replace("[产品编号]", item_id) .Replace("[推广PID]", pid) .Replace("[淘口令]", tkl) .Replace("[图片地址]", pict_url) .Replace("[是否推荐]", (ApiClient.Setting.SystemConfig.ZjyComposeType == ComposeType.有推荐商品).ToString()) ); } else//没有券的情况 { var mess = string.Empty; if (e.ChatType == ChatType.微信 || e.ChatType == ChatType.企业微信 || (e.ChatType == ChatType.QQ && string.IsNullOrWhiteSpace(Class1.Config.QQSearchSuccessWithoutCouponTip))) mess = Class1.Config.SearchSuccessWithoutCouponTip; else mess = Class1.Config.QQSearchSuccessWithoutCouponTip; e.SendMessage(mess .Replace("[商品标题]", mess.Contains("", "") : title) .Replace("[商品原价]", string.Format("{0:F}", zk_final_price)) .Replace("[商品主图]", $"[图片={pict_url}]") .Replace("[图片地址]", pict_url) .Replace("[月销量]", volume) .Replace("[店铺名称]", nick) .Replace("[返利积分]", string.Format("{0:F}", unuseCoupon_commFee.UserPoint)) .Replace("[购买地址]", couponUrl) .Replace("[购买中间页地址]", composeUrl) .Replace("[购买淘口令]", tkl) .Replace("[共节省]", string.Format("{0:F}", useCoupon_commFee.UserPoint)) .Replace("[商品图片]", mess.Contains("[商品图片]") ? "[图片=" + ApiClient.GetQRImage(title, zk_final_price.ToString(), "0", zk_final_price.ToString(), pict_url, composeUrl, ApiClient.QrImageType.模板B, CpsType.阿里妈妈) + "]" : string.Empty) .Replace("[产品编号]", item_id) .Replace("[推广PID]", pid) .Replace("[淘口令]", tkl) .Replace("[图片地址]", pict_url) .Replace("[是否推荐]", (ApiClient.Setting.SystemConfig.ZjyComposeType == ComposeType.有推荐商品).ToString()) ); } } #endregion #region 记录用户信息,宝贝信息,平台信息,查询时间等 db.Insertable(new fl_query_hist() { crt_time = DateTime.Now, type = CpsType.阿里妈妈, itemid = item_id, groupid = e.Groupid, robot_name = e.RobotName, robot_type = e.ChatType, userid = memberTmp.id, title = title, adzoneid = pids[3], mallid = sellerId, compute_configdic = compute == null ? string.Empty : JsonConvert.SerializeObject(compute) }).ExecuteCommand(); db.UpdateRecord(memberTmp.id); var shared = new Dictionary(); shared["msg_type"] = "查询宝贝"; shared["cps_type"] = CpsType.阿里妈妈; shared["msg_username"] = memberTmp.username; shared["price"] = string.Format("{0:F}", zk_final_price); shared["title"] = title; shared["coupon_price"] = string.Format("{0:F}", coupon_price); shared["user_point"] = coupon_price != 0 ? string.Format("{0:F}", useCoupon_commFee.UserPoint) : string.Format("{0:F}", unuseCoupon_commFee.UserPoint); shared["economize"] = coupon_price != 0 ? string.Format("{0:F}", ((decimal)coupon_price + (decimal)useCoupon_commFee.UserPoint)) : string.Format("{0:F}", useCoupon_commFee.UserPoint); var sharedEvent = new SharedEvents(shared); EventClient.OnEvent(sender, sharedEvent); #endregion return true; } else { if (Class1.Config.ShopAdSwitch == SwitchType.开启) { #region 商品没有返利,店铺参加了推广,下单后有返利 string data = new HttpHelper().GetHtml(new HttpItem() { URL = $"https://item.taobao.com/item.htm?ft=t&id={item_id}", Method = "get", IsToLower = false, Cookie = "", Referer = "", Postdata = "", Timeout = 100000, ReadWriteTimeout = 30000, UserAgent = "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)", ContentType = "text/html", Allowautoredirect = false, ProxyIp = "", ResultType = ResultType.String }).Html; var reg_title = Regex.Match(data, @"title\s*:\s*'(?[^']+)'", RegexOptions.IgnoreCase); title = reg_title.Success ? HttpExtend.Unicode2String(reg_title.Groups["title"].Value) : string.Empty; var pict_url = string.Empty; var sellerId = string.Empty; var reg_sellerId = Regex.Match(data, @"userid=(?<sellerId>\d+);", RegexOptions.IgnoreCase); if (!reg_sellerId.Success) reg_sellerId = Regex.Match(data, @"sellerId\s*:\s*'(?<sellerId>\d+)'", RegexOptions.IgnoreCase); if (reg_sellerId.Success) { var reg_pic = Regex.Match(data, @"pic\s*:\s*'(?<pic>[^']+)'", RegexOptions.IgnoreCase); pict_url = reg_pic.Success ? reg_pic.Groups["pic"].Value : string.Empty; if (!pict_url.ToLower().StartsWith("http")) pict_url = "http:" + pict_url; sellerId = reg_sellerId.Groups["sellerId"].Value; } else { var url = HttpExtend.RegexMatchUrl(message); if (!string.IsNullOrWhiteSpace(url)) { data = new HttpHelper().GetHtml(new HttpItem() { URL = url, Method = "get", IsToLower = false, Cookie = "", Referer = "", Postdata = "", Timeout = 100000, ReadWriteTimeout = 30000, UserAgent = "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)", ContentType = "text/html", Allowautoredirect = false, ProxyIp = "", ResultType = ResultType.String }).Html; var reg = Regex.Match(data, @"_!!(?<sellerId>\d+).jpg", RegexOptions.IgnoreCase); if (reg.Success) { sellerId = reg.Groups["sellerId"].Value; } } } if (!string.IsNullOrWhiteSpace(sellerId)) { try { var shopConvert = api.SendTaobao("taobao.tbk.sc.shop.convert", new { fields = "user_id,click_url", site_id = pids[2], user_ids = sellerId, adzone_id = pids[3] }); if (shopConvert != null && shopConvert.Count != 0) { if (shopConvert.ContainsKey("n_tbk_shop")) { var n_tbk_shop = shopConvert["n_tbk_shop"] as ArrayList; if (n_tbk_shop.Count != 0) { var shopInfo = n_tbk_shop[0] as Dictionary<string, object>; if (shopInfo.ContainsKey("click_url")) { var click_url = shopInfo["click_url"].ToString(); if (!string.IsNullOrWhiteSpace(click_url)) { var shopTGUrl = tbAnalysis.FindShortUrlBySrcUrl(click_url, api); var tklInfo = tbAnalysis.FindTKL(shopTGUrl, api); if (tklInfo == null) { e.SendMessage(Class1.Config.SearchNoCommissionTip.Replace("[关键词]", keyword).Replace("[商品标题]", title));//未搜索到提示语 db.UpdateRecord(memberTmp.id); var shared1 = new Dictionary<string, object>(); shared1["msg_type"] = "查询宝贝"; shared1["cps_type"] = CpsType.阿里妈妈; shared1["msg_username"] = memberTmp.username; shared1["price"] = "未知"; shared1["title"] = title ?? keyword; shared1["coupon_price"] = "未知"; shared1["user_point"] = "未知"; shared1["economize"] = "未知"; var sharedEvent1 = new SharedEvents(shared1); EventClient.OnEvent(sender, sharedEvent1); return true; } //淘口令的前/后符号有没有设置.有设置将替换掉 var tkl = tbAnalysis.ReplaceTklModifier(tklInfo.tkl); //中间页地址 //var composeUrl = api.ComposeTbClick(item_id, pict_url, tklInfo.tkl, shopTGUrl, true); var composeUrl = api.ComposeTbClick(item_id, pict_url, tklInfo.tkl, tklInfo.isoUrl, true, pid, ApiClient.Setting.SystemConfig.ZjyComposeType == ComposeType.有推荐商品); var mess = string.Empty; if (e.ChatType == ChatType.微信 || e.ChatType == ChatType.企业微信 || (e.ChatType == ChatType.QQ && string.IsNullOrWhiteSpace(Class1.Config.QQSearchSuccessWithCouponTip))) mess = Class1.Config.ShopAdSuccessTip; else mess = Class1.Config.QQShopAdSuccessTip; e.SendMessage(mess .Replace("[商品标题]", mess.Contains("<appmsg") ? title.Replace("<", "").Replace(">", "") : title) .Replace("[商品主图]", $"[图片={pict_url}]") .Replace("[图片地址]", pict_url) .Replace("[购买地址]", shopTGUrl) .Replace("[购买中间页地址]", composeUrl) .Replace("[购买淘口令]", tkl) ); #region 记录用户信息,宝贝信息,平台信息,查询时间等 db.Insertable(new fl_query_hist() { crt_time = DateTime.Now, type = CpsType.阿里妈妈, itemid = item_id, groupid = e.Groupid, robot_name = e.RobotName, robot_type = e.ChatType, userid = memberTmp.id, title = title, adzoneid = pids[3], mallid = string.Empty }).ExecuteCommand(); db.UpdateRecord(memberTmp.id); var shar = new Dictionary<string, object>(); shar["msg_type"] = "查询宝贝"; shar["cps_type"] = CpsType.阿里妈妈; shar["msg_username"] = memberTmp.username; shar["price"] = "未知"; shar["title"] = title; shar["coupon_price"] = "未知"; shar["user_point"] = "未知"; shar["economize"] = "未知"; var sharEvent = new SharedEvents(shar); EventClient.OnEvent(sender, sharEvent); #endregion return true; } } } } } } catch (Exception ex) { } } #endregion } #region 强返 //判断是否为天猫商品 var flag_tianmao = api.IsTianmao(item_id); var adzone = db.FindAdzoneInfos().FirstOrDefault(f => f.custom_type == Resources.TbActivitySoftwareType && f.robot_id == e.RobotInfo.id); #region 判断是否需要标题,需要标题的情况获取标题 if (string.IsNullOrWhiteSpace(keyword) && string.IsNullOrWhiteSpace(title) && ((flag_tianmao && adzone != null) || Class1.Config.SearchTitleSwitch_NoCommission == SwitchType.开启 || Class1.Config.SearchNoCommissionTip.Contains("[商品标题]"))) { var reg = Regex.Match(e.Message, @"「(?<标题>.{5,})」"); if (reg.Success) title = reg.Groups["标题"].Value; if (string.IsNullOrEmpty(title)) { #region 一系列获取标题的操作,最终就是想获取标题 HttpHelper http = new HttpHelper(); var item = new HttpItem(); item.URL = @"https://acs.m.taobao.com/gw/mtop.taobao.detail.getdetail/6.0/?data={%22itemNumId%22%3A%22" + item_id + @"%22&qq-pf-to=pcqq.group"; var _html = http.GetHtml(item).Html; if (_html.Contains("SUCCESS::调用成功")) { reg = Regex.Match(_html, @"""title"":""(?<title>[^""]{10,})"","""); if (reg.Success) title = reg.Groups["title"].Value; } else { var html = string.Empty; for (int i = 0; i < 4; i++) { HttpItem httpItem = new HttpItem() { URL = @"https://item.taobao.com/item.htm?id=" + item_id,//宝贝的链接 Method = "GET", Timeout = 100000, ReadWriteTimeout = 30000, IsToLower = false, UserAgent = "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)", Accept = "text/html, application/xhtml+xml, */*", ContentType = "application/x-www-form-urlencoded", Allowautoredirect = true, AutoRedirectCookie = true }; http = new HttpHelper(); var result = http.GetHtml(httpItem); if (!(result != null && (result.Html.Contains("操作超时")) || result.Html.Contains("基础连接已经关闭"))) { html = result.Html; break; } Thread.Sleep(200); } reg = Regex.Match(html, @"<meta name=""keywords"" content=""(?<标题>.+?)""/>"); if (reg.Success) { title = reg.Groups["标题"].Value.Replace("淘宝,掏宝,网上购物,店铺, ", ""); if (title.Last() == '.') title = title.Substring(0, title.Length - 1); } else { } } #endregion } } #endregion if (flag_tianmao) { //var adzone = db.FindAdzoneInfos().FirstOrDefault(f => f.custom_type == Resources.TbActivitySoftwareType && f.robot_id == e.RobotInfo.id); if (adzone != null) { var group = db.FindAdzoneGroups(CpsType.阿里妈妈).FirstOrDefault(f => f.id == adzone.adzone_group); if (group != null) { var activity = Tools.GetActivityTuiguangwei(e.RobotInfo.name, tbInfoTemp); if (activity == null) throw new Exception(@"无结果"); pids = activity.Pid.Split(new string[] { "_" }, StringSplitOptions.RemoveEmptyEntries); if (pids == null || pids.Length == 0) throw new Exception("推广位异常,请重新设置强返推广位"); tb_cps = CpsClient.Members.FirstOrDefault(f => f.cpstype == CpsType.阿里妈妈 && f.username == pids[1]); if (tb_cps == null) throw new Exception("@阿里妈妈推广位异常,请检测后重试 !"); api = CpsClient.CreateAlimamaRequest(tb_cps); if (api == null) throw new Exception("@创建阿里妈妈API请求失败"); #region 生成自己的淘口令 var tklInfo = tbAnalysis.FindTKL(activity.ShortUrl, api); if (tklInfo != null) { if (!string.IsNullOrEmpty(title)) { title = title.Replace("这个#聚划算团购#宝贝不错:", "").Replace("(分享自@手机淘宝android客户端)", ""); var temp_url = api.ComposeTbClick(item_id, "https://img.alicdn.com/tfs/TB1MaLKRXXXXXaWXFXXXXXXXXXX-480-260.png", tklInfo.tkl, tklInfo.isoUrl, true, activity.Pid, ApiClient.Setting.SystemConfig.ZjyComposeType == ComposeType.有推荐商品, -1, Class1.Config.CoercePageUrl.Trim());//中间页地址 e.SendMessage(Class1.Config.CoerceSearchSuccessTip .Replace("[商品标题]", title) .Replace("[商品原价]", "未知") .Replace("[商品主图]", "")//$"[图片 ={tbInfo.ItemImage}]") .Replace("[月销量]", "未知") .Replace("[店铺名称]", "未知") .Replace("[购买中间页地址]", temp_url) .Replace("[购买淘口令]", tklInfo.tkl) .Replace("[图片地址]", "") ); #region 记录用户信息,宝贝信息,平台信息,查询时间等 db.Insertable(new fl_query_hist() { crt_time = DateTime.Now, type = CpsType.阿里妈妈, itemid = item_id, groupid = e.Groupid, robot_name = e.RobotName, robot_type = e.ChatType, userid = memberTmp.id, title = title, adzoneid = activity.Pid.Split('_')[3], mallid = string.Empty }).ExecuteCommand(); db.UpdateRecord(memberTmp.id); var _shared = new Dictionary<string, object>(); _shared["msg_type"] = "查询宝贝"; _shared["cps_type"] = CpsType.阿里妈妈; _shared["msg_username"] = memberTmp.username; _shared["price"] = "未知"; _shared["title"] = title; _shared["coupon_price"] = "未知"; _shared["user_point"] = "未知"; _shared["economize"] = "未知"; EventClient.OnEvent(sender, new SharedEvents(_shared)); #endregion return true; } } #endregion } } } if (string.IsNullOrWhiteSpace(keyword) && !string.IsNullOrWhiteSpace(title) && Class1.Config.SearchTitleSwitch_NoCommission == SwitchType.开启) { keyword = title; IsTitle = true; var searchUrl = api.ComposeTbCms(pid, keyword);//内置的搜索机制 e.SendMessage(Class1.Config.SearchTitle_NoCommissionTip.Replace("[商品标题]", title).Replace("[购买地址]", ApiClient.ShortURL(searchUrl).Result)); } else e.SendMessage(Class1.Config.SearchNoCommissionTip.Replace("[关键词]", keyword).Replace("[商品标题]", title));//未搜索到提示语 db.UpdateRecord(memberTmp.id); var shared = new Dictionary<string, object>(); shared = new Dictionary<string, object>(); shared["msg_type"] = "查询宝贝"; shared["cps_type"] = CpsType.阿里妈妈; shared["msg_username"] = memberTmp.username; shared["price"] = "未知"; shared["title"] = (title ?? keyword) ?? "未知"; shared["coupon_price"] = "未知"; shared["user_point"] = "未知"; shared["economize"] = "未知"; var sharedEvent = new SharedEvents(shared); EventClient.OnEvent(sender, sharedEvent); return true; #endregion } } catch (Exception ex) { if (Regex.IsMatch(ex.Message, @"sub_msg\"":\""无结果", RegexOptions.IgnoreCase) || ex.Message == "无结果" || Regex.IsMatch(ex.Message, @"sub_msg\"":\""非淘客宝贝", RegexOptions.IgnoreCase)) { if (string.IsNullOrWhiteSpace(keyword) && !string.IsNullOrWhiteSpace(title) && Class1.Config.SearchTitleSwitch_NoCommission == SwitchType.开启) { keyword = title; IsTitle = true; var searchUrl = api.ComposeTbCms(pid, keyword);//内置的搜索机制 e.SendMessage(Class1.Config.SearchTitle_NoCommissionTip.Replace("[商品标题]", title).Replace("[购买地址]", ApiClient.ShortURL(searchUrl).Result)); return true; } else { e.SendMessage(Class1.Config.SearchNoCommissionTip.Replace("[关键词]", keyword).Replace("[商品标题]", title)); db.UpdateRecord(memberTmp.id); var shared = new Dictionary<string, object>(); shared["msg_type"] = "查询宝贝"; shared["cps_type"] = CpsType.阿里妈妈; shared["msg_username"] = memberTmp.username; shared["price"] = "未知"; shared["title"] = title ?? keyword; shared["coupon_price"] = "未知"; shared["user_point"] = "未知"; shared["economize"] = "未知"; var sharedEvent = new SharedEvents(shared); EventClient.OnEvent(sender, sharedEvent); return true; } } else //if (ex.Message.Contains("该item_id对应宝贝已下架或非淘客宝贝")) { e.SendMessage(Class1.Config?.SearchNoCommissionTip?.Replace("[关键词]", keyword).Replace("[商品标题]", title));//未搜索到提示语 db.UpdateRecord(memberTmp.id); var shared = new Dictionary<string, object>(); shared["msg_type"] = "查询宝贝"; shared["cps_type"] = CpsType.阿里妈妈; shared["msg_username"] = memberTmp?.username; shared["price"] = "未知"; shared["title"] = title ?? keyword; shared["coupon_price"] = "未知"; shared["user_point"] = "未知"; shared["economize"] = "未知"; var sharedEvent = new SharedEvents(shared); EventClient.OnEvent(sender, sharedEvent); throw ex; } } } #endregion } catch (Exception ex) { if (ex.Message.StartsWith("@")) plugin.OnLog($"E :({e.RobotInfo.nick}【{e.RobotInfo.name}】){ex.Message.Replace("@", "")}"); else plugin.OnLog($"E:({e.RobotInfo.nick}【{e.RobotInfo.name}】){ex.Message} - {ex.StackTrace}"); plugin.OnLog(ApiClient.Setting.SystemConfig.msg_error); } return false; } #region 淘礼金相关 /// <summary> /// 淘礼金方法 /// </summary> /// <param name="member"></param> /// <returns></returns> public string TljMethod(fl_member_info member, ref AlimamaApi api, string item_id, double perface) { try { if (!Class1.Config.TljOnOff) return string.Empty; if (perface < 1) return string.Empty; var session = ApiClient.GetSession(); var tljInfos = session.FindTljInfos(); var tljCreateRecords = session.Find<fl_alimama_tlj_create_record>("select * from fl_alimama_tlj_create_record"); if (tljInfos != null && tljInfos.Count != 0) { var cpsnames1 = tljInfos.Select(f => f.username).ToList(); var cpsnames2 = tljCreateRecords.Select(f => f.cpsname).ToList(); for (int i = 0; i < cpsnames1.Count; i++) { if (!cpsnames2.Contains(cpsnames1[i])) { var tljRecord = new fl_alimama_tlj_create_record() { cpsname = cpsnames1[i], date = DateTime.Now.ToString("yyyyMMdd"), number = 0 }; tljCreateRecords.Add(session.Saveable(tljRecord).ExecuteReturnEntity()); } } } List<fl_alimama_tlj_create_record> tljs = null; if (tljCreateRecords != null) tljs = tljCreateRecords.Where(f => (f.date == DateTime.Now.ToString("yyyyMMdd") && f.number < 30) || f.date != DateTime.Now.ToString("yyyyMMdd")).ToList(); switch (Class1.Config.TljModel) { case TLJModel.新人首次查询时使用淘礼金: { var incomeResult = session.FindSingle<fl_statistics_record>(@"select * from fl_statistics_record where uid = @userid", new { userid = member.id }); if (incomeResult == null) return CreateTljUrl(ref api, tljs, item_id, perface); } break; case TLJModel.首单付款前使用淘礼金: { if (member.bind_order == 0) return CreateTljUrl(ref api, tljs, item_id, perface); } break; case TLJModel.查询随机分配淘礼金: { var random = new Random(Guid.NewGuid().GetHashCode()); var num = random.Next(1, 5000); if ((1000 < num && num < 1250) || 10 < num && num < 260) return CreateTljUrl(ref api, tljs, item_id, perface); } break; } } catch (Exception ex) { } return string.Empty; } private readonly object lock_tlj = new object(); /// <summary> /// 创建淘礼金 /// </summary> /// <param name="api"></param> /// <param name="item_id"></param> /// <param name="image"></param> /// <returns>返回淘礼金连接</returns> private string CreateTljUrl(ref AlimamaApi api, List<fl_alimama_tlj_create_record> tljs, string item_id, double perface) { try { lock (lock_tlj) { var session = ApiClient.GetSession(); #region 寻找以前创建的并且现在有效的淘礼金 var _tlj = session.FindTljByItemid(item_id); if (_tlj != null) { var cps = CpsClient.Members.FirstOrDefault(f => f.cpstype == CpsType.阿里妈妈 && f.username == _tlj.cpsname); if (cps != null) { AlimamaApi _api = CpsClient.CreateAlimamaRequest(cps); if (_api != null) api = _api; } if (_tlj.number == 1) session.Deleteable<fl_alimama_tlj_get_record>(_tlj).ExecuteCommand(); else { _tlj.number--; session.SaveOrUpdate(_tlj); } return _tlj.url; } #endregion if (!string.IsNullOrWhiteSpace(Class1.Config.TljItemIds)) { var itemids = Class1.Config.TljItemIds.Replace(",", ",").Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries).ToList(); if (string.IsNullOrWhiteSpace(itemids.FirstOrDefault(f => f.Trim() == item_id))) return string.Empty; } if (tljs != null) { foreach (var item in tljs) { var cps = CpsClient.Members.FirstOrDefault(f => f.cpstype == CpsType.阿里妈妈 && f.username == item.cpsname); if (cps != null) { AlimamaApi _api = CpsClient.CreateAlimamaRequest(cps); if (_api != null) { var tlj = session.FindTljInfos().FirstOrDefault(f => f.username == _api.Member.username); if (tlj != null) { if (string.IsNullOrWhiteSpace(tlj.appkey) || string.IsNullOrWhiteSpace(tlj.appsecret) || string.IsNullOrWhiteSpace(tlj.adzone_pid)) continue; var reg = Regex.Match(tlj.adzone_pid, @"mm_(?<cpsname>\d+)_(?<pid1>\d+)_(?<pid2>\d+)"); if (!reg.Success) continue; //throw new Exception($"淘宝推广位格式不正确"); var cpsname = reg.Groups["cpsname"].Value; //var pid1 = reg.Groups["pid1"].Value; var pid2 = reg.Groups["pid2"].Value; var now = DateTime.Now; var send_end_time = now.AddHours(Class1.Config.TljExpireDate); var tljResult = _api.SendTaobao("taobao.tbk.dg.vegas.tlj.create", new { adzone_id = pid2, item_id = item_id, security_switch = "true", total_num = Class1.Config.TljCreateNum, name = Class1.Config.TljName, user_total_win_num_limit = Class1.Config.TljGetLimit, per_face = perface, send_start_time = now.ToString("yyyy-MM-dd HH:mm:ss"), send_end_time = send_end_time.ToString("yyyy-MM-dd HH:mm:ss") }, tlj.appkey, tlj.appsecret); if (tljResult != null && tljResult.ContainsKey("success")) { if (tljResult["success"].ToString().ToLower() == "false") { if (tljResult.ContainsKey("msg_info")) { var msg = tljResult["msg_info"].ToString(); if (msg == "您创建的淘礼金商品数目已达上限") session.ExcuteSQL("update fl_alimama_tlj_create_record set date = @date ,number = 30 where cpsname = @cpsname", new { date = now.ToString("yyyyMMdd"), cpsname = cpsname }); //throw new Exception("该淘宝账号ID今日创建淘礼金次数已耗尽"); } //throw new Exception(tljResult.ContainsKey("msg_info") ? tljResult["msg_info"].ToString() : $"生成淘礼金失败,{HttpHelper.ObjectToJson(tljResult)}"); continue; } if (tljResult.ContainsKey("model")) { var model = tljResult["model"] as Dictionary<string, object>; if (model.ContainsKey("send_url")) { var send_url = model["send_url"].ToString(); #region 统计次数 session.AddTljCreateNum(cpsname); #endregion #region 将创建的淘礼金保存在数据库中 if (Class1.Config.TljCreateNum > 1) { session.SaveOrUpdate(new fl_alimama_tlj_get_record() { adzoneid = pid2, expiredate = send_end_time, itemid = item_id, number = Class1.Config.TljCreateNum - 1, url = send_url, cpsname = cpsname }); } #endregion api = _api; return send_url; } } } } } } } } } } catch (Exception ex) { } return string.Empty; } #endregion } }