orders.cs 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910
  1. using dodohold.core;
  2. using System.Text.Json;
  3. namespace molilian.core
  4. {
  5. public partial class AlimamaPlus
  6. {
  7. private const string base_orders_url = "https://pub.alimama.com/openapi/param2/1/gateway.unionpub/report.getTbkOrderDetails.json";
  8. public async Task<int> GetHistoryOrdersAsync(int sleep, DateTime startTime, DateTime endTime)
  9. {
  10. // 隐藏号不同步任何订单数据
  11. if (_account.is_hide) return 0;
  12. string lockKey = $"lock:GetHistoryOrders:{_accountId}";
  13. if (!RedisHelper.Set(lockKey, "1", 1800))
  14. {
  15. string message = $"【GetHistoryOrders】【{_accountId}:{_accountName}】任务正在执行中,跳过本次调用";
  16. _ = new LoggerLibrary("task_lock", "skip")
  17. .Info(message)
  18. .SaveAsync();
  19. return 0;
  20. }
  21. var startTimestamp = DateTime.Now;
  22. try
  23. {
  24. //DateTime endTime = DateTime.Now;
  25. //DateTime startTime = endTime.AddDays(-90);
  26. //if (_accountId == 3) endTime = DateTime.Parse("2024-04-07");
  27. //#if DEBUG
  28. // startTime = DateTime.Parse("2024-05-01");
  29. // endTime = DateTime.Parse("2024-06-01");
  30. // int total = 0;
  31. // List<DateTime> orderTimes = new List<DateTime>();
  32. // for (DateTime date = startTime; date <= endTime; date = date.AddDays(1))
  33. // {
  34. // orderTimes.Add(date);
  35. // }
  36. //#else
  37. //#endif
  38. //当日往前查询
  39. (int total, DateTime max_modifiedTime, List<DateTime> orderTimes) = await GetTkOrdersAsync(startTime, endTime, DateTime.MinValue, false, sleep);
  40. string sql = @"
  41. UPDATE tk_report tr
  42. JOIN (
  43. SELECT
  44. accountId, DATE(tbPaidTime) AS date, SUM(alipayTotalPrice) AS order_ord_amt,
  45. COUNT(*) AS order_ord_num, SUM(pubShareFeeForCommission) AS order_ord_tfee
  46. FROM tk_order_details
  47. WHERE DATE(tbPaidTime) IN @orderTimes AND tkStatus=3 AND accountId=@accountId
  48. GROUP BY DATE(tbPaidTime), accountId
  49. ) AS sub
  50. ON tr.accountId = sub.accountId AND tr.report_date = sub.date
  51. SET tr.order_ord_amt = sub.order_ord_amt, tr.order_ord_num_3 = sub.order_ord_num,
  52. tr.order_ord_tfee = sub.order_ord_tfee;";
  53. DBContext.Execute(sql, new { accountId = _accountId, orderTimes });
  54. sql = @"
  55. UPDATE tk_report tr
  56. JOIN (
  57. SELECT
  58. accountId, DATE(tbPaidTime) AS date, SUM(alipayTotalPrice) AS order_ord_amt,
  59. COUNT(*) AS order_ord_num, SUM(pubSharePreFeeForCommission) AS order_ord_tfee
  60. FROM tk_order_details
  61. WHERE DATE(tbPaidTime) IN @orderTimes AND tkStatus=12 AND accountId=@accountId
  62. GROUP BY DATE(tbPaidTime), accountId
  63. ) AS sub
  64. ON tr.accountId = sub.accountId AND tr.report_date = sub.date
  65. SET tr.order_ord_amt_12 = sub.order_ord_amt, tr.order_ord_num_12 = sub.order_ord_num,
  66. tr.order_ord_tfee_12 = sub.order_ord_tfee;";
  67. DBContext.Execute(sql, new { accountId = _accountId, orderTimes });
  68. sql = @"
  69. UPDATE tk_report tr
  70. JOIN (
  71. SELECT
  72. accountId, DATE(tbPaidTime) AS date, SUM(alipayTotalPrice) AS order_ord_amt,
  73. COUNT(*) AS order_ord_num, SUM(pubSharePreFeeForCommission) AS order_ord_tfee
  74. FROM tk_order_details
  75. WHERE DATE(tbPaidTime) IN @orderTimes AND tkStatus=13 AND accountId=@accountId
  76. GROUP BY DATE(tbPaidTime), accountId
  77. ) AS sub
  78. ON tr.accountId = sub.accountId AND tr.report_date = sub.date
  79. SET tr.order_ord_amt_13 = sub.order_ord_amt, tr.order_ord_num_13 = sub.order_ord_num,
  80. tr.order_ord_tfee_13 = sub.order_ord_tfee;";
  81. DBContext.Execute(sql, new { accountId = _accountId, orderTimes });
  82. sql = @"
  83. UPDATE tk_report tr
  84. JOIN (
  85. SELECT
  86. accountId, DATE(tbPaidTime) AS date, SUM(alipayTotalPrice) AS order_ord_amt,
  87. COUNT(*) AS order_ord_num, SUM(pubSharePreFeeForCommission) AS order_ord_tfee
  88. FROM tk_order_details
  89. WHERE DATE(tbPaidTime) IN @orderTimes AND tkStatus=14 AND accountId=@accountId
  90. GROUP BY DATE(tbPaidTime), accountId
  91. ) AS sub
  92. ON tr.accountId = sub.accountId AND tr.report_date = sub.date
  93. SET tr.order_ord_amt_14 = sub.order_ord_amt, tr.order_ord_num_14 = sub.order_ord_num,
  94. tr.order_ord_tfee_14 = sub.order_ord_tfee;";
  95. DBContext.Execute(sql, new { accountId = _accountId, orderTimes });
  96. sql = @"UPDATE tk_report
  97. SET order_ord_num = order_ord_num_3 + order_ord_num_12 + order_ord_num_13 + order_ord_num_14
  98. WHERE DATE(report_date) IN @orderTimes AND accountId=@accountId;";
  99. DBContext.Execute(sql, new { accountId = _accountId, orderTimes });
  100. return total;
  101. }
  102. catch (Exception ex)
  103. {
  104. string errorMessage = $"【GetHistoryOrders】【{_accountId}:{_accountName}】执行异常: {ex.Message}";
  105. _ = new LoggerLibrary("task_error", "GetHistoryOrders")
  106. .Info(errorMessage, ex.StackTrace)
  107. .SaveAsync();
  108. throw;
  109. }
  110. finally
  111. {
  112. var executionTime = DateTime.Now - startTimestamp;
  113. string logMessage = $"【GetHistoryOrders】【{_accountId}:{_accountName}】执行完成,耗时: {executionTime.TotalSeconds:F2}秒";
  114. _ = new LoggerLibrary("task_performance", "GetHistoryOrders")
  115. .Info(logMessage)
  116. .SaveAsync();
  117. RedisHelper.Del(lockKey);
  118. }
  119. }
  120. public async Task<int> GetIncyOrdersAsync(int sleep, int retry_days = 0)
  121. {
  122. // 隐藏号不同步任何订单数据
  123. if (_account.is_hide) return 0;
  124. string lockKey = $"lock:GetIncyOrders:{_accountId}";
  125. if (!RedisHelper.Set(lockKey, "1", 1800))
  126. {
  127. string message = $"【GetIncyOrders】【{_accountId}:{_accountName}】任务正在执行中,跳过本次调用";
  128. _ = new LoggerLibrary("task_lock", "skip")
  129. .Info(message)
  130. .SaveAsync();
  131. return 0;
  132. }
  133. var startTimestamp = DateTime.Now;
  134. try
  135. {
  136. string cacheKey = $":cache:GetIncyOrders:{_accountName}";
  137. string cacheKey2 = $":cache:GetIncyOrders:{_accountId}";
  138. DateTime endTime = DateTime.Now;
  139. DateTime startTime = endTime.AddDays(-1);
  140. DateTime last_modifiedTime = RedisHelper.Get<DateTime>(cacheKey);
  141. ////找出数据库最新的一天
  142. //var last = new DBContext.Table("tk_order_details")
  143. // .Order("modifiedTime DESC")
  144. // .Get<TkOrderDetailDTO>("accountId=@accountId", new { accountId = _accountId });
  145. if (last_modifiedTime != DateTime.MinValue)
  146. {
  147. startTime = last_modifiedTime;
  148. }
  149. else
  150. {
  151. last_modifiedTime = startTime;
  152. }
  153. if (retry_days > 0)
  154. {
  155. last_modifiedTime = DateTime.Now.AddDays(-retry_days);
  156. }
  157. //当日往前查询
  158. (int total, DateTime max_modifiedTime, List<DateTime> orderTimes) = await GetTkOrdersAsync(startTime, endTime, last_modifiedTime, true, sleep);
  159. if (max_modifiedTime != DateTime.MinValue)
  160. {
  161. RedisHelper.Set(cacheKey, max_modifiedTime);
  162. RedisHelper.Set(cacheKey2, max_modifiedTime);
  163. }
  164. if (total == 0) return 0;
  165. //todo 根据orderTimes、settlementTimes 更新被影响的相关行
  166. string sql = @"
  167. UPDATE tk_report tr
  168. JOIN (
  169. SELECT
  170. accountId, DATE(tbPaidTime) AS date, SUM(alipayTotalPrice) AS order_ord_amt,
  171. COUNT(*) AS order_ord_num, SUM(pubShareFeeForCommission) AS order_ord_tfee
  172. FROM tk_order_details
  173. WHERE DATE(tbPaidTime) IN @orderTimes AND tkStatus=3 AND accountId=@accountId
  174. GROUP BY DATE(tbPaidTime), accountId
  175. ) AS sub
  176. ON tr.accountId = sub.accountId AND tr.report_date = sub.date
  177. SET tr.order_ord_amt = sub.order_ord_amt, tr.order_ord_num_3 = sub.order_ord_num,
  178. tr.order_ord_tfee = sub.order_ord_tfee;";
  179. int x = DBContext.Execute(sql, new { accountId = _accountId, orderTimes });
  180. sql = @"
  181. UPDATE tk_report tr
  182. JOIN (
  183. SELECT
  184. accountId, DATE(tbPaidTime) AS date, SUM(alipayTotalPrice) AS order_ord_amt,
  185. COUNT(*) AS order_ord_num, SUM(pubSharePreFeeForCommission) AS order_ord_tfee
  186. FROM tk_order_details
  187. WHERE DATE(tbPaidTime) IN @orderTimes AND tkStatus=12 AND accountId=@accountId
  188. GROUP BY DATE(tbPaidTime), accountId
  189. ) AS sub
  190. ON tr.accountId = sub.accountId AND tr.report_date = sub.date
  191. SET tr.order_ord_amt_12 = sub.order_ord_amt, tr.order_ord_num_12 = sub.order_ord_num,
  192. tr.order_ord_tfee_12 = sub.order_ord_tfee;";
  193. DBContext.Execute(sql, new { accountId = _accountId, orderTimes });
  194. sql = @"
  195. UPDATE tk_report tr
  196. JOIN (
  197. SELECT
  198. accountId, DATE(tbPaidTime) AS date, SUM(alipayTotalPrice) AS order_ord_amt,
  199. COUNT(*) AS order_ord_num, SUM(pubSharePreFeeForCommission) AS order_ord_tfee
  200. FROM tk_order_details
  201. WHERE DATE(tbPaidTime) IN @orderTimes AND tkStatus=13 AND accountId=@accountId
  202. GROUP BY DATE(tbPaidTime), accountId
  203. ) AS sub
  204. ON tr.accountId = sub.accountId AND tr.report_date = sub.date
  205. SET tr.order_ord_amt_13 = sub.order_ord_amt, tr.order_ord_num_13 = sub.order_ord_num,
  206. tr.order_ord_tfee_13 = sub.order_ord_tfee;";
  207. DBContext.Execute(sql, new { accountId = _accountId, orderTimes });
  208. sql = @"
  209. UPDATE tk_report tr
  210. JOIN (
  211. SELECT
  212. accountId, DATE(tbPaidTime) AS date, SUM(alipayTotalPrice) AS order_ord_amt,
  213. COUNT(*) AS order_ord_num, SUM(pubSharePreFeeForCommission) AS order_ord_tfee
  214. FROM tk_order_details
  215. WHERE DATE(tbPaidTime) IN @orderTimes AND tkStatus=14 AND accountId=@accountId
  216. GROUP BY DATE(tbPaidTime), accountId
  217. ) AS sub
  218. ON tr.accountId = sub.accountId AND tr.report_date = sub.date
  219. SET tr.order_ord_amt_14 = sub.order_ord_amt, tr.order_ord_num_14 = sub.order_ord_num,
  220. tr.order_ord_tfee_14 = sub.order_ord_tfee;";
  221. DBContext.Execute(sql, new { accountId = _accountId, orderTimes });
  222. sql = @"UPDATE tk_report
  223. SET order_ord_num = order_ord_num_3 + order_ord_num_12 + order_ord_num_13 + order_ord_num_14
  224. WHERE DATE(report_date) IN @orderTimes AND accountId=@accountId;";
  225. DBContext.Execute(sql, new { accountId = _accountId, orderTimes });
  226. return total;
  227. }
  228. catch (Exception ex)
  229. {
  230. string errorMessage = $"【GetIncyOrders】【{_accountId}:{_accountName}】执行异常: {ex.Message}";
  231. _ = new LoggerLibrary("task_error", "GetIncyOrders")
  232. .Info(errorMessage, ex.StackTrace)
  233. .SaveAsync();
  234. throw;
  235. }
  236. finally
  237. {
  238. var executionTime = DateTime.Now - startTimestamp;
  239. string logMessage = $"【GetIncyOrders】【{_accountId}:{_accountName}】执行完成,耗时: {executionTime.TotalSeconds:F2}秒";
  240. _ = new LoggerLibrary("task_performance", "GetIncyOrders")
  241. .Info(logMessage)
  242. .SaveAsync();
  243. RedisHelper.Del(lockKey);
  244. }
  245. }
  246. public async Task<int> GetOrdersByAdZoneAsync(long adzoneId, DateTime startTime, DateTime endTime, int sleep)
  247. {
  248. // 隐藏号不同步任何订单数据
  249. if (_account.is_hide) return 0;
  250. string cacheKey = $":cache:GetOrdersByAdZone:{_accountName}";
  251. string cacheKey2 = $":cache:GetOrdersByAdZone:{_accountId}";
  252. DateTime last_modifiedTime = RedisHelper.Get<DateTime>(cacheKey);
  253. if (last_modifiedTime != DateTime.MinValue)
  254. {
  255. startTime = last_modifiedTime;
  256. }
  257. else
  258. {
  259. last_modifiedTime = startTime;
  260. }
  261. //当日往前查询
  262. (int total, DateTime max_modifiedTime, List<DateTime> orderTimes) = await GetTkOrdersByAdZoneAsync(adzoneId, startTime, endTime, last_modifiedTime, true, sleep);
  263. if (max_modifiedTime != DateTime.MinValue)
  264. {
  265. RedisHelper.Set(cacheKey, max_modifiedTime);
  266. RedisHelper.Set(cacheKey2, max_modifiedTime);
  267. }
  268. return total;
  269. }
  270. public async Task<(int, DateTime, List<DateTime>)> GetTkOrdersByAdZoneAsync(long adzoneId, DateTime startTime, DateTime endTime, DateTime last_modifiedTime, bool desc = true, int sleep = 100)
  271. {
  272. List<DateTime> orderTimes = [];
  273. if (startTime > endTime)
  274. {
  275. (startTime, endTime) = (endTime, startTime);
  276. }
  277. DateTime max_modifiedTime = last_modifiedTime;
  278. int pageNo = 1;
  279. string positionIndex = string.Empty;
  280. int pageSize = 100;
  281. bool hasNext = true;
  282. int total = 0;
  283. while (hasNext)
  284. {
  285. var ts = DateTime.Now.Convert2UnixTimestamp(true);
  286. string jumpType = pageNo == 1 ? "0" : "1";
  287. #if DEBUG
  288. jumpType = pageNo == 1 ? "0" : "1";
  289. #endif
  290. string queryType = desc ? "4" : "2";
  291. string url = $"{base_orders_url}?t={ts}&_tb_token_={_tb_token}&pageNo={pageNo}&pageSize={pageSize}&startTime={startTime:yyyy-MM-dd}&endTime={endTime:yyyy-MM-dd}&payStatus=&queryType={queryType}&jumpType={jumpType}&positionIndex={positionIndex.UrlEncode()}";
  292. string body = "";
  293. JsonElement data;
  294. try
  295. {
  296. var client = new WebClientUtility().SetContentType("application/x-www-form-urlencoded; charset=UTF-8")
  297. .AddHeaders("X-Requested-With", "XMLHttpRequest")
  298. .AddHeaders("Cookie", _cookies);
  299. #if DEBUG
  300. #else
  301. client.Proxy = _proxy;
  302. #endif
  303. if (!string.IsNullOrEmpty(_user_agent)) client.UserAgent = _user_agent;
  304. var response = client.Request(url);
  305. if (response.ResponseException != null)
  306. {
  307. _ = new LoggerLibrary("api_error", "fail")
  308. .Info(response.ResponseException.Message, response.ResponseException.StackTrace)
  309. .SaveAsync();
  310. throw response.ResponseException;
  311. }
  312. body = response.Body();
  313. #if DEBUG
  314. _ = new LoggerLibrary("debug", "GetTkOrdersByAdZone")
  315. .Info(body)
  316. .SaveAsync();
  317. #endif
  318. if (body.Contains("{\"action\":\"captcha\""))
  319. {
  320. RiskControlCore.SetRiskCookie($"tb:{_accountId}", "滑块");
  321. string message = $"【GetTkOrdersByAdZone】【{_accountId}:{_accountName}】出现滑动验证码";
  322. //NotifyCore.Notify(new NifyMessage
  323. //{
  324. // message = message,
  325. // priority = NifyMessagePriority.high,
  326. // tags = ["red_circle"]
  327. //});
  328. if (!_account.is_hide)
  329. {
  330. _ = NotifyCore.QYWeixinPushNotifyAsync(message, message);
  331. }
  332. throw new Exception(message);
  333. }
  334. if (body.Contains("\"resultCode\":500"))
  335. {
  336. string message = $"【GetTkOrdersByAdZone】【{_accountId}:{_accountName}】出现错误\n{body}";
  337. NotifyCore.Notify(new NifyMessage
  338. {
  339. message = message,
  340. priority = NifyMessagePriority.high,
  341. tags = ["red_circle"]
  342. });
  343. throw new Exception(message);
  344. }
  345. var root = body.Convert2JsonElement();
  346. var success = root.Read<bool>("success");
  347. data = root.ElementRead("data");
  348. if (!success && body.Contains("nologin"))
  349. {
  350. (success, string message) = RenewCookie();
  351. if (!success)
  352. {
  353. TkPoolCore.Disabled(_accountId, _accountName, $"{body}", _account.is_hide);
  354. }
  355. return (0, DateTime.MinValue, new List<DateTime>());
  356. }
  357. if (!success)
  358. {
  359. throw new APIException(body);
  360. }
  361. }
  362. catch (Exception ex)
  363. {
  364. throw new APIException(body);
  365. }
  366. using var conn = DBContext.GetOpenConnection();
  367. conn.Open();
  368. try
  369. {
  370. foreach (var order in data.ElementRead("result").EnumerateArray())
  371. {
  372. TkOrderDetailAdZoneDTO item = order.GetRawText().Convert2Object<TkOrderDetailAdZoneDTO>();
  373. // 处理每个订单数据
  374. if (item.adzoneId != adzoneId) continue;
  375. item.accountId = _accountId;
  376. item.accountName = _company;
  377. if (item.modifiedTime > max_modifiedTime) max_modifiedTime = item.modifiedTime;
  378. if (last_modifiedTime != DateTime.MinValue && last_modifiedTime >= item.modifiedTime)
  379. {
  380. return (total, max_modifiedTime, orderTimes);
  381. }
  382. if (item.tkStatus == 3 && item.tbPaidTime != DateTime.MinValue) orderTimes.Add(item.tbPaidTime.Date);
  383. int? id = conn.Replace(item);
  384. total++;
  385. }
  386. }
  387. catch (Exception ex)
  388. {
  389. throw;
  390. }
  391. finally
  392. {
  393. conn.Dispose();
  394. }
  395. pageNo++;
  396. hasNext = data.Read<bool>("hasNext");
  397. positionIndex = data.Read<string>("positionIndex");
  398. if (sleep > 0) await Task.Delay(sleep);
  399. }
  400. return (total, max_modifiedTime, orderTimes);
  401. }
  402. public async Task<(int, DateTime, List<DateTime>)> GetTkOrdersAsync(DateTime startTime, DateTime endTime, DateTime last_modifiedTime, bool desc = true, int sleep = 100)
  403. {
  404. List<DateTime> orderTimes = [];
  405. // 确保 startTime 小于 endTime
  406. if (startTime > endTime)
  407. {
  408. (startTime, endTime) = (endTime, startTime);
  409. }
  410. DateTime max_modifiedTime = last_modifiedTime;
  411. int pageNo = 1;
  412. string positionIndex = string.Empty;
  413. int pageSize = 100;
  414. bool hasNext = true;
  415. int total = 0;
  416. while (hasNext)
  417. {
  418. var ts = DateTime.Now.Convert2UnixTimestamp(true);
  419. //string jumpType = desc ? pageNo == 1 ? "0" : "1" : "-1";
  420. string jumpType = pageNo == 1 ? "0" : "1";
  421. #if DEBUG
  422. jumpType = pageNo == 1 ? "0" : "1";
  423. #endif
  424. //string queryType = "1";
  425. //1 创建时间;3结算时间 2付款时间 4更新时间
  426. //string queryType = "2";
  427. string queryType = desc ? "4" : "2";
  428. string url = $"{base_orders_url}?t={ts}&_tb_token_={_tb_token}&pageNo={pageNo}&pageSize={pageSize}&startTime={startTime:yyyy-MM-dd}&endTime={endTime:yyyy-MM-dd}&payStatus=&queryType={queryType}&jumpType={jumpType}&positionIndex={positionIndex.UrlEncode()}";
  429. string body = "";
  430. JsonElement data;
  431. try
  432. {
  433. bool success = false;
  434. #if DEBUG
  435. _cookies = "t_alimama=265947ef5452cb1dbc3a85423cb0b4ac; xlly_s=1; wk_cookie2=153667c5e7c346da3c64cc8be5db65b5; wk_unb=UUpjNmHYrAUDFe1XcQ%3D%3D; arms_uid=50fb4ec1-5342-4774-9b30-822cfb71ac29; cookie2_alimama=1939cd118da29bee099e20497d91d195; lid=tb464407448627; cookie3_bak=17c2085f3ca7b7e1d9932184a321265b; env_bak=FM%2BgwZ4N3DW5Nit1vtAN%2BnGo%2FlvOs%2BhcfJ4%2F0uUixKyv; cookie3_bak_exp=1753443569194; havana_lgc_exp=1786690298961; dnk=tb464407448627; tracknick=tb464407448627; lgc=; cookie2=17c2085f3ca7b7e1d9932184a321265b; cancelledSubSites=empty; t=b0f1900bb872fb73431103fd9fd685da; sn=; _tb_token_=e3be75e77317e; uc1=cookie14=UoYbzibV4BRygw%3D%3D&pas=0&cookie16=WqG3DMC9UpAPBHGz5QBErFxlCA%3D%3D&existShop=false&cookie15=WqG3DMC9VAQiUQ%3D%3D&cookie21=V32FPkk%2FhSt4; sgcookie=E100maFa2uGfFmlaN000MHH4oUxgMX%2Fe%2FWHW96Um0swftox2LuxNNHviK0VTqoHo%2F1NuX%2BYAGoSBwA8mzA3bTrtPkhdwXGBaIPytPt3iO9Ay%2Bh8%3D; csg=8a980a9f; login=; rurl=aHR0cHM6Ly9wdWIuYWxpbWFtYS5jb20vaW5kZXguaHRtP2ZvcndhcmQ9aHR0cHMlM0ElMkYlMkZwdWIuYWxpbWFtYS5jb20lMkZwb3J0YWwlMkZ2MiUyRmVmZmVjdCUyRm9yZGVyJTJGb3ZlcnZpZXdPcmRlciUyRnBhZ2UlMkZpbmRleC5odG0%3D; v_alimama=0; JSESSIONID=5529D2F4B4C1D00E84AEBD50280FB383; cna=BfkxIaeXgCYCAXs5yWAuAa9d; x5sec=7b22733b32223a2263613337363636363063313961373062222c2277616762726964676561643b32223a2232643831656432356532633264343332333737306462646238363761376562664350476374385547454a612f707654392f2f2f2f2f774561454449794d6a41794e544d314d5445314e446b374d545977332f6e4f3651553d227d; tfstk=gEftPuYb-kqMTmoZWi2noACNV9Uh0JbN8G7SinxihMIduaU2hRS0MsIcvPJbbCfAvZSeoj2NmMHXkHWGnrzwDEtCYEf07KjdDaIJoxXg7msFkg6MoCODMmdNtOcDjlRAlgAYquVuZN7wMIZuq5jhO1dWrcMsmnOCRIYvWC9CtN7wg2unc8XC7qEntGc6lnapOELocIT6lBapkUKXGh9jAvTWAnOfcn_BOF8r5FTsGXapuHT6GIsfRyLDAnOXGi_ITUU9YVTtMOE1kwEYa-WPI6L9B3_LUbczeTol8NGsajfdp4xR5xljG6L9B6M24HxwIt_yU1bUMXRGy9OBWiN7fpW1JspPg-cMQ9_hwe17oY-h9hjf6paowKACZLO1KJrMnCLRc1StkjsXshOG1IumgaO9ACf9pqGAVwbl_p5Y2DtVIURBWiN7vgWFZ_L570xJoAaLJxk2CezoM3hD13hyWeKu5dMq3KYeJ34LJxk2Ce8pqPGj3xJD8";
  436. #endif
  437. var client = new WebClientUtility().SetContentType("application/x-www-form-urlencoded; charset=UTF-8")
  438. .AddHeaders("X-Requested-With", "XMLHttpRequest")
  439. .AddHeaders("Cookie", _cookies);
  440. #if DEBUG
  441. #else
  442. client.Proxy = _proxy;
  443. #endif
  444. if (!string.IsNullOrEmpty(_user_agent)) client.UserAgent = _user_agent;
  445. client.Referer = "https://pub.alimama.com/portal/v2/effect/order/overviewOrder/page/index.htm";
  446. var response = client.Request(url);
  447. if (response.ResponseException != null)
  448. {
  449. _ = new LoggerLibrary("api_error", "fail")
  450. .Info(response.ResponseException.Message, response.ResponseException.StackTrace)
  451. .SaveAsync();
  452. throw response.ResponseException;
  453. }
  454. body = response.Body();
  455. _ = new LoggerLibrary("debug", "GetTkOrders")
  456. .Info(body)
  457. .SaveAsync();
  458. if (body.Contains("{\"action\":\"login\"") || body.Contains("\"action\": \"login\""))
  459. {
  460. (success, string message) = RenewCookie();
  461. if (!success)
  462. {
  463. TkPoolCore.Disabled(_accountId, _accountName, $"{body}", _account.is_hide);
  464. }
  465. return (0, DateTime.MinValue, new List<DateTime>());
  466. }
  467. if (body.Contains("{\"action\":\"captcha\""))
  468. {
  469. RiskControlCore.SetRiskCookie($"tb:{_accountId}", "滑块");
  470. string message = $"【GetTkOrders】【{_accountId}:{_accountName}】出现滑动验证码";
  471. //NotifyCore.Notify(new NifyMessage
  472. //{
  473. // message = message,
  474. // priority = NifyMessagePriority.high,
  475. // tags = ["red_circle"]
  476. //});
  477. if (!_account.is_hide)
  478. {
  479. _ = NotifyCore.QYWeixinPushNotifyAsync(message, message);
  480. }
  481. return (0, max_modifiedTime, new List<DateTime>());
  482. //throw new Exception(message);
  483. }
  484. if (body.Contains("\"resultCode\":500"))
  485. {
  486. //{"success":false,"resultCode":500,"bizErrorDesc":"系统繁忙,请稍后重试!","bizErrorCode":3001}
  487. string message = $"【GetTkOrders】【{_accountId}:{_accountName}】出现错误\n{body}";
  488. NotifyCore.Notify(new NifyMessage
  489. {
  490. message = message,
  491. priority = NifyMessagePriority.high,
  492. tags = ["red_circle"]
  493. });
  494. throw new Exception(message);
  495. }
  496. /*
  497. <script>sessionStorage.x5referer = window.location.href;var url = window.location.protocol + "//pub.alimama.com//openapi/param2/1/gateway.unionpub/report.getTbkOrderDetails.json/_____tmd_____/punish?x5secdata=xc1iwR0XfHknuQ2tGhtadtTAvEt14YScfTDHt2ZiSRqroaYZK98uykgsVOy7o75Rw8uuycKT3Rpx30%2fB5H0gRc0%2fJVGQUcV5g%2fsAmZ%2bc46eyD7DXSdA4R3mLnmtbp9wuZ1vmrG3ZPlH7brUilFbXBdZ7EBrru1X7wPfC05Eq3g4mhDFiGq39xUtwQcC%2f%2bPbtekcm8%2fVJ%2brVt8aExunwzXzJPJJTAvEt14YScfTDHt2ZiSRqroaYZK98uykgsiXIkw%2ffMWwebJ3zxCja5CzSu%2ffTA%3d%3d__bx__pub.alimama.com%2fopenapi%2fparam2%2f1%2fgateway.unionpub%2freport.getTbkOrderDetails.json&x5step=1";window.location.replace(url);window._config_ = {"action":"captcha","url":"https://pub.alimama.com//openapi/param2/1/gateway.unionpub/report.getTbkOrderDetails.json/_____tmd_____/punish?x5secdata=xc1iwR0XfHknuQ2tGhtadtTAvEt14YScfTDHt2ZiSRqroaYZK98uykgsVOy7o75Rw8uuycKT3Rpx30%2fB5H0gRc0%2fJVGQUcV5g%2fsAmZ%2bc46eyD7DXSdA4R3mLnmtbp9wuZ1vmrG3ZPlH7brUilFbXBdZ7EBrru1X7wPfC05Eq3g4mhDFiGq39xUtwQcC%2f%2bPbtekcm8%2fVJ%2brVt8aExunwzXzJPJJTAvEt14YScfTDHt2ZiSRqroaYZK98uykgsiXIkw%2ffMWwebJ3zxCja5CzSu%2ffTA%3d%3d__bx__pub.alimama.com%2fopenapi%2fparam2%2f1%2fgateway.unionpub%2freport.getTbkOrderDetails.json&x5step=1"};</script><!--rgv587_flag:sm--> */
  498. var root = body.Convert2JsonElement();
  499. success = root.Read<bool>("success");
  500. data = root.ElementRead("data");
  501. //{"code":601,"info":{"ok":false,"message":"nologin"}}
  502. if (!success && body.Contains("nologin"))
  503. {
  504. (success, string message) = RenewCookie();
  505. if (!success)
  506. {
  507. TkPoolCore.Disabled(_accountId, _accountName, $"{body}", _account.is_hide);
  508. }
  509. return (0, DateTime.MinValue, new List<DateTime>());
  510. }
  511. if (!success)
  512. {
  513. throw new APIException(body);
  514. }
  515. }
  516. catch (Exception ex)
  517. {
  518. _ = new LoggerLibrary("debug", "GetTkOrders")
  519. .Info(body)
  520. .Info(ex.Message, ex.StackTrace)
  521. .SaveAsync();
  522. string message = $"【GetRawItemId】{_accountId}:{_accountName}\t{_proxy?.Address}\n" +
  523. $"{body}\n{ex.Message}\n{ex.StackTrace}";
  524. if (sleep > 0) await Task.Delay(sleep);
  525. throw new APIException(body);
  526. }
  527. try
  528. {
  529. foreach (var order in data.ElementRead("result").EnumerateArray())
  530. {
  531. TkOrderDetailDTO item = order.GetRawText().Convert2Object<TkOrderDetailDTO>();
  532. // 处理每个订单数据
  533. item.accountId = _accountId;
  534. item.accountName = _company;
  535. if (item.modifiedTime > max_modifiedTime) max_modifiedTime = item.modifiedTime;
  536. if (last_modifiedTime != DateTime.MinValue && last_modifiedTime >= item.modifiedTime)
  537. {
  538. return (total, max_modifiedTime, orderTimes);
  539. }
  540. //进行订单和转链匹配
  541. (int state, item.itemId) = GetRawItemId(item.mktId);
  542. if (item.tkStatus == 3 && item.tbPaidTime != DateTime.MinValue) orderTimes.Add(item.tbPaidTime.Date);
  543. using var conn = DBContext.GetOpenConnection();
  544. int? id = conn.Replace(item);
  545. if (id != null)
  546. {
  547. item.id = (int)id;
  548. TkOrderTrackingCore.MatchOrder(_account, item);
  549. }
  550. total++;
  551. }
  552. }
  553. catch (Exception ex)
  554. {
  555. if (sleep > 0) await Task.Delay(sleep);
  556. throw;
  557. }
  558. pageNo++;
  559. hasNext = data.Read<bool>("hasNext");
  560. positionIndex = data.Read<string>("positionIndex");
  561. if (sleep > 0) await Task.Delay(sleep);
  562. }
  563. return (total, max_modifiedTime, orderTimes);
  564. }
  565. public (int, string) GetRawItemId(string mktId)
  566. {
  567. ////
  568. ///
  569. string body = string.Empty, location = string.Empty;
  570. var proxy = ProxyNodesCore.RandomOne();
  571. try
  572. {
  573. string cacheKey = $":cache:mkt2itemId:{mktId}";
  574. string itemId = RedisHelper.Get(cacheKey);
  575. if (itemId != null) return (1, itemId);
  576. string mktItemLink = $"https://uland.taobao.com/item/edetail?id={mktId}";
  577. ////uland.taobao.com/item/edetail?id=98t7UOZmNWX4dh2eJSQt6-b7Y8yZVuBQ5ywoz7TDA
  578. ////uland.taobao.com/item/edetail?id=98t7UOZmNWX4dh2eJSQt6-b7Y8yZVuBQ5ywoz7TD
  579. ///
  580. var client = new WebClientUtility();
  581. client.Proxy = proxy;
  582. client.AddHeaders("accept-language", "zh-CN,zh;q=0.9");
  583. client.AllowAutoRedirect = false;
  584. var response = client.Request(mktItemLink);
  585. if (!response.Successed)
  586. {
  587. throw response.ResponseException;
  588. }
  589. location = response.ResponseMessage?.Headers?.Location?.ToString();
  590. string message;
  591. if (!string.IsNullOrEmpty(location) && location.Contains("err.taobao.com/error1.html"))
  592. {
  593. message = $"【GetRawItemId】{_accountId}:{_accountName}\t{proxy?.Address}\n" +
  594. $"{mktId}\n{location}";
  595. //NotifyCore.Notify(new NifyMessage
  596. //{
  597. // message = message,
  598. // priority = NifyMessagePriority.high,
  599. // tags = ["red_circle"]
  600. //});
  601. return (0, null);
  602. }
  603. if (!string.IsNullOrEmpty(location) && location.Contains("item.htm?id="))
  604. {
  605. itemId = location.GetContentPart("?id=", "");
  606. }
  607. if (!string.IsNullOrEmpty(itemId))
  608. {
  609. RedisHelper.Set(cacheKey, itemId, 86400 * 7);
  610. }
  611. else
  612. {
  613. }
  614. return (1, itemId);
  615. }
  616. catch (Exception ex)
  617. {
  618. string message = $"【GetRawItemId】{_accountId}:{_accountName}\t{proxy?.Address}\n" +
  619. $"{mktId}\n{location}\n{body}\n{ex.Message}";
  620. NotifyCore.Notify(new NifyMessage
  621. {
  622. message = message,
  623. priority = NifyMessagePriority.high,
  624. tags = ["red_circle"]
  625. });
  626. }
  627. return (0, null);
  628. }
  629. public (int, string) GetRawItemId22(string mktId)
  630. {
  631. string body = string.Empty, location = string.Empty;
  632. try
  633. {
  634. string lock_key = $"lock:GetRawItemId:disabled";
  635. int count = RedisHelper.Get<int>(lock_key);
  636. if (count > 0) return (0, null);
  637. string cacheKey = $":cache:mkt2itemId:{mktId}";
  638. string itemId = RedisHelper.Get(cacheKey);
  639. if (itemId != null) return (1, itemId);
  640. var ts = DateTime.Now.Convert2UnixTimestamp(true);
  641. string url = "https://pub.alimama.com/openapi/param2/1/gateway.unionpub/union.moose.content.entry";
  642. //string url = $"{base_orders_url}?t={ts}&_tb_token_={_tb_token}&pageNo={pageNo}&pageSize={pageSize}&startTime={startTime:yyyy-MM-dd}&endTime={endTime:yyyy-MM-dd}&payStatus=&queryType={queryType}&jumpType={jumpType}&tkTradeId=&positionIndex={positionIndex}";
  643. var client = new WebClientUtility()
  644. .SetContentType("application/x-www-form-urlencoded")
  645. .AddHeaders("Cookie", _cookies)
  646. .AddHeaders("Origin", "https://pub.alimama.com")
  647. .Post("_tb_token_", _tb_token)
  648. .Post("t", ts.ToString())
  649. .Post("bizType", "detailPage")
  650. .Post("bizParam", $"{{\"itemId\":\"{mktId}\"}}");
  651. //_tb_token_=3b88755bbe3f7&t=1718896771391&bizType=detailPage&bizParam=%7B%22itemId%22%3A%22JbtMUqkGMQvagTNb2Fvta-9ag242pu7MOX5e0bsrY%22%7D
  652. //_tb_token_=361e383eb61e5&t=1718895935097&bizType=detailPage&bizParam=%7B%22itemId%22%3A%22JbtMUqkGMQvagTNb2Fvta-9ag242pu7MOX5e0bsrY%22%7D
  653. #if DEBUG
  654. #else
  655. client.Proxy = _proxy;
  656. #endif
  657. if (!string.IsNullOrEmpty(_user_agent)) client.UserAgent = _user_agent;
  658. var response = client.Request(url);
  659. if (!response.Successed)
  660. {
  661. throw response.ResponseException;
  662. }
  663. location = response.ResponseMessage?.Headers?.Location?.ToString();
  664. string message;
  665. if (!string.IsNullOrEmpty(location) && location.Contains("err.taobao.com/error1.html"))
  666. {
  667. RedisHelper.Set(lock_key, 1, 60);
  668. message = $"【GetRawItemId】{_accountId}:{_accountName}\t{_proxy?.Address}\n" +
  669. $"{mktId}\n{location}";
  670. //NotifyCore.Notify(new NifyMessage
  671. //{
  672. // message = message,
  673. // priority = NifyMessagePriority.high,
  674. // tags = ["red_circle"]
  675. //});
  676. return (0, null);
  677. }
  678. body = response.Body();
  679. var root = body.Convert2JsonElement();
  680. int code = root.PathRead<int>("code");
  681. message = root.PathRead<string>("info.message");
  682. //if ("nologin".Equals(message))
  683. //{
  684. // (bool success, message) = RenewCookie();
  685. // if (!success)
  686. // {
  687. // TkPoolCore.Disabled(_accountId, _accountName, body);
  688. // throw new Exception("nologin");
  689. // }
  690. // return (-1, null);
  691. //}
  692. itemId = root.PathRead<string>("model.item.itemId");
  693. if (!string.IsNullOrEmpty(itemId))
  694. {
  695. RedisHelper.Set(cacheKey, itemId, 86400 * 7);
  696. }
  697. else
  698. {
  699. //RedisHelper.Set(lock_key, 1, 3600);
  700. }
  701. return (1, itemId);
  702. }
  703. catch (Exception ex)
  704. {
  705. string message = $"【GetRawItemId】{_accountId}:{_accountName}\t{_proxy?.Address}\n" +
  706. $"{mktId}\n{location}\n{body}\n{ex.Message}";
  707. NotifyCore.Notify(new NifyMessage
  708. {
  709. message = message,
  710. priority = NifyMessagePriority.high,
  711. tags = ["red_circle"]
  712. });
  713. }
  714. return (0, null);
  715. }
  716. public void GetTkOrders222()
  717. {
  718. try
  719. {
  720. string url = "https://media.alimama.com/violationu2/warning_instance_page_v2.json?r=mx_208&toPage=1&pageSize=40&params=";
  721. var client = new WebClientUtility().SetContentType("application/json;charset=utf-8")
  722. .AddHeaders("X-Requested-With", "XMLHttpRequest")
  723. .AddHeaders("Cookie", _cookies);
  724. client.Proxy = _proxy;
  725. if (!string.IsNullOrEmpty(_user_agent)) client.UserAgent = _user_agent;
  726. var response = client.Request(url);
  727. var body = response.Body();
  728. var root = body.Convert2JsonElement();
  729. int resultCode = root.Read<int>("resultCode", 0);
  730. int totalCount = root.PathRead<int>("data.totalCount", 0);
  731. bool success = root.Read("success", false);
  732. if (!success)
  733. {
  734. _ = new LoggerLibrary("violationu", "warning_error")
  735. .Info(url, body)
  736. .SaveAsync();
  737. throw new Exception(body);
  738. }
  739. if (totalCount == 0) return;
  740. _ = new LoggerLibrary("violationu", "warning").Info(url, body).SaveAsync();
  741. var list = root.ElementRead("data").ElementRead("result").EnumerateArray();
  742. foreach (var data in list)
  743. {
  744. var violation_commission = data.PathRead<decimal>("mediaInfo.订单虚假交易违规佣金", 0);
  745. new DBContext.Table("alimama_warning")
  746. .Fill(data)
  747. .Loader<int>("filterRuleId", 0)
  748. .Loader<long>("gmtCreate", 0)
  749. .Loader<long>("id", 0, "ali_id")
  750. .Loader<string>("idStr", string.Empty)
  751. .Loader<int>("mediaDimension", 0)
  752. .Loader<long>("mediaId", 0)
  753. .Loader<int>("mediaInfo.abn_cnt", 0, "abn_cnt")
  754. .Add("violation_commission", violation_commission)
  755. .Loader<int>("mediaInfo.warning_cnt", 0, "warning_cnt")
  756. .Loader<string>("mediaName", string.Empty)
  757. .Loader<long>("memberId", 0)
  758. .Loader<string>("noticeCategory", string.Empty)
  759. .Loader<int>("noticeTemplateId", 0)
  760. .Loader<string>("noticeTemplateName", string.Empty)
  761. .Loader<string>("orderFile", string.Empty)
  762. .Loader<string>("pid", string.Empty)
  763. .Loader<int>("punishRuleId", 0)
  764. .Loader<string>("riskType", string.Empty)
  765. .Loader<string>("roleName", string.Empty)
  766. .Loader<string>("ruleLink", string.Empty)
  767. .Loader<bool>("showOrderDetail", false)
  768. .Loader<int>("status", 0, "ali_status")
  769. .Loader<string>("warningText", string.Empty)
  770. .Add("accountName", _accountName)
  771. .Add("status", true)
  772. .Add("create_time", DateTime.Now)
  773. .Add("last_time", DateTime.Now)
  774. .Create(DBContext.InsertType.REPLACE);
  775. }
  776. }
  777. catch (Exception ex) { }
  778. }
  779. }
  780. }