orders.cs 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899
  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. int x = 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}&positionIndex={positionIndex.UrlEncode()}";
  284. string body = "";
  285. JsonElement data;
  286. try
  287. {
  288. var client = new WebClientUtility().SetContentType("application/x-www-form-urlencoded; 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}&positionIndex={positionIndex.UrlEncode()}";
  420. string body = "";
  421. JsonElement data;
  422. try
  423. {
  424. bool success = false;
  425. #if DEBUG
  426. _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";
  427. #endif
  428. var client = new WebClientUtility().SetContentType("application/x-www-form-urlencoded; charset=UTF-8")
  429. .AddHeaders("X-Requested-With", "XMLHttpRequest")
  430. .AddHeaders("Cookie", _cookies);
  431. #if DEBUG
  432. #else
  433. client.Proxy = _proxy;
  434. #endif
  435. if (!string.IsNullOrEmpty(_user_agent)) client.UserAgent = _user_agent;
  436. client.Referer = "https://pub.alimama.com/portal/v2/effect/order/overviewOrder/page/index.htm";
  437. var response = client.Request(url);
  438. if (response.ResponseException != null)
  439. {
  440. _ = new LoggerLibrary("api_error", "fail")
  441. .Info(response.ResponseException.Message, response.ResponseException.StackTrace)
  442. .SaveAsync();
  443. throw response.ResponseException;
  444. }
  445. body = response.Body();
  446. _ = new LoggerLibrary("debug", "GetTkOrders")
  447. .Info(body)
  448. .SaveAsync();
  449. if (body.Contains("{\"action\":\"login\"") || body.Contains("\"action\": \"login\""))
  450. {
  451. (success, string message) = RenewCookie();
  452. if (!success)
  453. {
  454. TkPoolCore.Disabled(_accountId, _accountName, $"{body}", _account.is_hide);
  455. }
  456. return (0, DateTime.MinValue, new List<DateTime>());
  457. }
  458. if (body.Contains("{\"action\":\"captcha\""))
  459. {
  460. string message = $"【GetTkOrders】【{_accountId}:{_accountName}】出现滑动验证码";
  461. NotifyCore.Notify(new NifyMessage
  462. {
  463. message = message,
  464. priority = NifyMessagePriority.high,
  465. tags = ["red_circle"]
  466. });
  467. if (!_account.is_hide)
  468. {
  469. _ = NotifyCore.QYWeixinPushNotifyAsync(message, message);
  470. }
  471. return (0, max_modifiedTime, new List<DateTime>());
  472. //throw new Exception(message);
  473. }
  474. if (body.Contains("\"resultCode\":500"))
  475. {
  476. //{"success":false,"resultCode":500,"bizErrorDesc":"系统繁忙,请稍后重试!","bizErrorCode":3001}
  477. string message = $"【GetTkOrders】【{_accountId}:{_accountName}】出现错误\n{body}";
  478. NotifyCore.Notify(new NifyMessage
  479. {
  480. message = message,
  481. priority = NifyMessagePriority.high,
  482. tags = ["red_circle"]
  483. });
  484. throw new Exception(message);
  485. }
  486. /*
  487. <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--> */
  488. var root = body.Convert2JsonElement();
  489. success = root.Read<bool>("success");
  490. data = root.ElementRead("data");
  491. //{"code":601,"info":{"ok":false,"message":"nologin"}}
  492. if (!success && body.Contains("nologin"))
  493. {
  494. (success, string message) = RenewCookie();
  495. if (!success)
  496. {
  497. TkPoolCore.Disabled(_accountId, _accountName, $"{body}", _account.is_hide);
  498. }
  499. return (0, DateTime.MinValue, new List<DateTime>());
  500. }
  501. if (!success)
  502. {
  503. throw new APIException(body);
  504. }
  505. }
  506. catch (Exception ex)
  507. {
  508. _ = new LoggerLibrary("debug", "GetTkOrders")
  509. .Info(body)
  510. .Info(ex.Message, ex.StackTrace)
  511. .SaveAsync();
  512. string message = $"【GetRawItemId】{_accountId}:{_accountName}\t{_proxy?.Address}\n" +
  513. $"{body}\n{ex.Message}\n{ex.StackTrace}";
  514. if (sleep > 0) await Task.Delay(sleep);
  515. throw new APIException(body);
  516. }
  517. try
  518. {
  519. foreach (var order in data.ElementRead("result").EnumerateArray())
  520. {
  521. TkOrderDetailDTO item = order.GetRawText().Convert2Object<TkOrderDetailDTO>();
  522. // 处理每个订单数据
  523. item.accountId = _accountId;
  524. item.accountName = _company;
  525. if (item.modifiedTime > max_modifiedTime) max_modifiedTime = item.modifiedTime;
  526. if (last_modifiedTime != DateTime.MinValue && last_modifiedTime >= item.modifiedTime)
  527. {
  528. return (total, max_modifiedTime, orderTimes);
  529. }
  530. //进行订单和转链匹配
  531. (int state, item.itemId) = GetRawItemId(item.mktId);
  532. if (item.tkStatus == 3 && item.tbPaidTime != DateTime.MinValue) orderTimes.Add(item.tbPaidTime.Date);
  533. using var conn = DBContext.GetOpenConnection();
  534. int? id = conn.Replace(item);
  535. if (id != null)
  536. {
  537. item.id = (int)id;
  538. TkOrderTrackingCore.MatchOrder(_account, item);
  539. }
  540. total++;
  541. }
  542. }
  543. catch (Exception ex)
  544. {
  545. if (sleep > 0) await Task.Delay(sleep);
  546. throw;
  547. }
  548. pageNo++;
  549. hasNext = data.Read<bool>("hasNext");
  550. positionIndex = data.Read<string>("positionIndex");
  551. if (sleep > 0) await Task.Delay(sleep);
  552. }
  553. return (total, max_modifiedTime, orderTimes);
  554. }
  555. public (int, string) GetRawItemId(string mktId)
  556. {
  557. ////
  558. ///
  559. string body = string.Empty, location = string.Empty;
  560. var proxy = ProxyNodesCore.RandomOne();
  561. try
  562. {
  563. string cacheKey = $":cache:mkt2itemId:{mktId}";
  564. string itemId = RedisHelper.Get(cacheKey);
  565. if (itemId != null) return (1, itemId);
  566. string mktItemLink = $"https://uland.taobao.com/item/edetail?id={mktId}";
  567. ////uland.taobao.com/item/edetail?id=98t7UOZmNWX4dh2eJSQt6-b7Y8yZVuBQ5ywoz7TDA
  568. ////uland.taobao.com/item/edetail?id=98t7UOZmNWX4dh2eJSQt6-b7Y8yZVuBQ5ywoz7TD
  569. ///
  570. var client = new WebClientUtility();
  571. client.Proxy = proxy;
  572. client.AddHeaders("accept-language", "zh-CN,zh;q=0.9");
  573. client.AllowAutoRedirect = false;
  574. var response = client.Request(mktItemLink);
  575. if (!response.Successed)
  576. {
  577. throw response.ResponseException;
  578. }
  579. location = response.ResponseMessage?.Headers?.Location?.ToString();
  580. string message;
  581. if (!string.IsNullOrEmpty(location) && location.Contains("err.taobao.com/error1.html"))
  582. {
  583. message = $"【GetRawItemId】{_accountId}:{_accountName}\t{proxy?.Address}\n" +
  584. $"{mktId}\n{location}";
  585. //NotifyCore.Notify(new NifyMessage
  586. //{
  587. // message = message,
  588. // priority = NifyMessagePriority.high,
  589. // tags = ["red_circle"]
  590. //});
  591. return (0, null);
  592. }
  593. if (!string.IsNullOrEmpty(location) && location.Contains("item.htm?id="))
  594. {
  595. itemId = location.GetContentPart("?id=", "");
  596. }
  597. if (!string.IsNullOrEmpty(itemId))
  598. {
  599. RedisHelper.Set(cacheKey, itemId, 86400 * 7);
  600. }
  601. else
  602. {
  603. }
  604. return (1, itemId);
  605. }
  606. catch (Exception ex)
  607. {
  608. string message = $"【GetRawItemId】{_accountId}:{_accountName}\t{proxy?.Address}\n" +
  609. $"{mktId}\n{location}\n{body}\n{ex.Message}";
  610. NotifyCore.Notify(new NifyMessage
  611. {
  612. message = message,
  613. priority = NifyMessagePriority.high,
  614. tags = ["red_circle"]
  615. });
  616. }
  617. return (0, null);
  618. }
  619. public (int, string) GetRawItemId22(string mktId)
  620. {
  621. string body = string.Empty, location = string.Empty;
  622. try
  623. {
  624. string lock_key = $"lock:GetRawItemId:disabled";
  625. int count = RedisHelper.Get<int>(lock_key);
  626. if (count > 0) return (0, null);
  627. string cacheKey = $":cache:mkt2itemId:{mktId}";
  628. string itemId = RedisHelper.Get(cacheKey);
  629. if (itemId != null) return (1, itemId);
  630. var ts = DateTime.Now.Convert2UnixTimestamp(true);
  631. string url = "https://pub.alimama.com/openapi/param2/1/gateway.unionpub/union.moose.content.entry";
  632. //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}";
  633. var client = new WebClientUtility()
  634. .SetContentType("application/x-www-form-urlencoded")
  635. .AddHeaders("Cookie", _cookies)
  636. .AddHeaders("Origin", "https://pub.alimama.com")
  637. .Post("_tb_token_", _tb_token)
  638. .Post("t", ts.ToString())
  639. .Post("bizType", "detailPage")
  640. .Post("bizParam", $"{{\"itemId\":\"{mktId}\"}}");
  641. //_tb_token_=3b88755bbe3f7&t=1718896771391&bizType=detailPage&bizParam=%7B%22itemId%22%3A%22JbtMUqkGMQvagTNb2Fvta-9ag242pu7MOX5e0bsrY%22%7D
  642. //_tb_token_=361e383eb61e5&t=1718895935097&bizType=detailPage&bizParam=%7B%22itemId%22%3A%22JbtMUqkGMQvagTNb2Fvta-9ag242pu7MOX5e0bsrY%22%7D
  643. #if DEBUG
  644. #else
  645. client.Proxy = _proxy;
  646. #endif
  647. if (!string.IsNullOrEmpty(_user_agent)) client.UserAgent = _user_agent;
  648. var response = client.Request(url);
  649. if (!response.Successed)
  650. {
  651. throw response.ResponseException;
  652. }
  653. location = response.ResponseMessage?.Headers?.Location?.ToString();
  654. string message;
  655. if (!string.IsNullOrEmpty(location) && location.Contains("err.taobao.com/error1.html"))
  656. {
  657. RedisHelper.Set(lock_key, 1, 60);
  658. message = $"【GetRawItemId】{_accountId}:{_accountName}\t{_proxy?.Address}\n" +
  659. $"{mktId}\n{location}";
  660. //NotifyCore.Notify(new NifyMessage
  661. //{
  662. // message = message,
  663. // priority = NifyMessagePriority.high,
  664. // tags = ["red_circle"]
  665. //});
  666. return (0, null);
  667. }
  668. body = response.Body();
  669. var root = body.Convert2JsonElement();
  670. int code = root.PathRead<int>("code");
  671. message = root.PathRead<string>("info.message");
  672. //if ("nologin".Equals(message))
  673. //{
  674. // (bool success, message) = RenewCookie();
  675. // if (!success)
  676. // {
  677. // TkPoolCore.Disabled(_accountId, _accountName, body);
  678. // throw new Exception("nologin");
  679. // }
  680. // return (-1, null);
  681. //}
  682. itemId = root.PathRead<string>("model.item.itemId");
  683. if (!string.IsNullOrEmpty(itemId))
  684. {
  685. RedisHelper.Set(cacheKey, itemId, 86400 * 7);
  686. }
  687. else
  688. {
  689. //RedisHelper.Set(lock_key, 1, 3600);
  690. }
  691. return (1, itemId);
  692. }
  693. catch (Exception ex)
  694. {
  695. string message = $"【GetRawItemId】{_accountId}:{_accountName}\t{_proxy?.Address}\n" +
  696. $"{mktId}\n{location}\n{body}\n{ex.Message}";
  697. NotifyCore.Notify(new NifyMessage
  698. {
  699. message = message,
  700. priority = NifyMessagePriority.high,
  701. tags = ["red_circle"]
  702. });
  703. }
  704. return (0, null);
  705. }
  706. public void GetTkOrders222()
  707. {
  708. try
  709. {
  710. string url = "https://media.alimama.com/violationu2/warning_instance_page_v2.json?r=mx_208&toPage=1&pageSize=40&params=";
  711. var client = new WebClientUtility().SetContentType("application/json;charset=utf-8")
  712. .AddHeaders("X-Requested-With", "XMLHttpRequest")
  713. .AddHeaders("Cookie", _cookies);
  714. client.Proxy = _proxy;
  715. if (!string.IsNullOrEmpty(_user_agent)) client.UserAgent = _user_agent;
  716. var response = client.Request(url);
  717. var body = response.Body();
  718. var root = body.Convert2JsonElement();
  719. int resultCode = root.Read<int>("resultCode", 0);
  720. int totalCount = root.PathRead<int>("data.totalCount", 0);
  721. bool success = root.Read("success", false);
  722. if (!success)
  723. {
  724. _ = new LoggerLibrary("violationu", "warning_error")
  725. .Info(url, body)
  726. .SaveAsync();
  727. throw new Exception(body);
  728. }
  729. if (totalCount == 0) return;
  730. _ = new LoggerLibrary("violationu", "warning").Info(url, body).SaveAsync();
  731. var list = root.ElementRead("data").ElementRead("result").EnumerateArray();
  732. foreach (var data in list)
  733. {
  734. var violation_commission = data.PathRead<decimal>("mediaInfo.订单虚假交易违规佣金", 0);
  735. new DBContext.Table("alimama_warning")
  736. .Fill(data)
  737. .Loader<int>("filterRuleId", 0)
  738. .Loader<long>("gmtCreate", 0)
  739. .Loader<long>("id", 0, "ali_id")
  740. .Loader<string>("idStr", string.Empty)
  741. .Loader<int>("mediaDimension", 0)
  742. .Loader<long>("mediaId", 0)
  743. .Loader<int>("mediaInfo.abn_cnt", 0, "abn_cnt")
  744. .Add("violation_commission", violation_commission)
  745. .Loader<int>("mediaInfo.warning_cnt", 0, "warning_cnt")
  746. .Loader<string>("mediaName", string.Empty)
  747. .Loader<long>("memberId", 0)
  748. .Loader<string>("noticeCategory", string.Empty)
  749. .Loader<int>("noticeTemplateId", 0)
  750. .Loader<string>("noticeTemplateName", string.Empty)
  751. .Loader<string>("orderFile", string.Empty)
  752. .Loader<string>("pid", string.Empty)
  753. .Loader<int>("punishRuleId", 0)
  754. .Loader<string>("riskType", string.Empty)
  755. .Loader<string>("roleName", string.Empty)
  756. .Loader<string>("ruleLink", string.Empty)
  757. .Loader<bool>("showOrderDetail", false)
  758. .Loader<int>("status", 0, "ali_status")
  759. .Loader<string>("warningText", string.Empty)
  760. .Add("accountName", _accountName)
  761. .Add("status", true)
  762. .Add("create_time", DateTime.Now)
  763. .Add("last_time", DateTime.Now)
  764. .Create(DBContext.InsertType.REPLACE);
  765. }
  766. }
  767. catch (Exception ex) { }
  768. }
  769. }
  770. }