orders.cs 41 KB

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