orders.cs 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739
  1. using dodohold.core;
  2. using Spire.Pdf.Xmp;
  3. using System.Data;
  4. using System.Drawing.Printing;
  5. using System.Runtime.InteropServices;
  6. using System.Text.Json;
  7. using System.Text.RegularExpressions;
  8. using System.Xml.Linq;
  9. using static System.Runtime.InteropServices.JavaScript.JSType;
  10. namespace molilian.core
  11. {
  12. public partial class AlimamaPlus
  13. {
  14. private const string base_orders_url = "https://pub.alimama.com/openapi/param2/1/gateway.unionpub/report.getTbkOrderDetails.json";
  15. public int GetHistoryOrders(int sleep, DateTime startTime, DateTime endTime)
  16. {
  17. //DateTime endTime = DateTime.Now;
  18. //DateTime startTime = endTime.AddDays(-90);
  19. //if (_accountId == 3) endTime = DateTime.Parse("2024-04-07");
  20. //#if DEBUG
  21. // startTime = DateTime.Parse("2024-05-01");
  22. // endTime = DateTime.Parse("2024-06-01");
  23. // int total = 0;
  24. // List<DateTime> orderTimes = new List<DateTime>();
  25. // for (DateTime date = startTime; date <= endTime; date = date.AddDays(1))
  26. // {
  27. // orderTimes.Add(date);
  28. // }
  29. //#else
  30. //#endif
  31. //当日往前查询
  32. (int total, DateTime max_modifiedTime, List<DateTime> orderTimes) = GetTkOrders(startTime, endTime, DateTime.MinValue, false, sleep);
  33. string sql = @"
  34. UPDATE tk_report tr
  35. JOIN (
  36. SELECT
  37. accountId, DATE(tbPaidTime) AS date, SUM(alipayTotalPrice) AS order_ord_amt,
  38. COUNT(*) AS order_ord_num, SUM(pubShareFeeForCommission) AS order_ord_tfee
  39. FROM tk_order_details
  40. WHERE DATE(tbPaidTime) IN @orderTimes AND tkStatus=3 AND accountId=@accountId
  41. GROUP BY DATE(tbPaidTime), accountId
  42. ) AS sub
  43. ON tr.accountId = sub.accountId AND tr.report_date = sub.date
  44. SET tr.order_ord_amt = sub.order_ord_amt, tr.order_ord_num_3 = sub.order_ord_num,
  45. tr.order_ord_tfee = sub.order_ord_tfee;";
  46. DBContext.Execute(sql, new { accountId = _accountId, orderTimes });
  47. sql = @"
  48. UPDATE tk_report tr
  49. JOIN (
  50. SELECT
  51. accountId, DATE(tbPaidTime) AS date, SUM(alipayTotalPrice) AS order_ord_amt,
  52. COUNT(*) AS order_ord_num, SUM(pubSharePreFeeForCommission) AS order_ord_tfee
  53. FROM tk_order_details
  54. WHERE DATE(tbPaidTime) IN @orderTimes AND tkStatus=12 AND accountId=@accountId
  55. GROUP BY DATE(tbPaidTime), accountId
  56. ) AS sub
  57. ON tr.accountId = sub.accountId AND tr.report_date = sub.date
  58. SET tr.order_ord_amt_12 = sub.order_ord_amt, tr.order_ord_num_12 = sub.order_ord_num,
  59. tr.order_ord_tfee_12 = sub.order_ord_tfee;";
  60. DBContext.Execute(sql, new { accountId = _accountId, orderTimes });
  61. sql = @"
  62. UPDATE tk_report tr
  63. JOIN (
  64. SELECT
  65. accountId, DATE(tbPaidTime) AS date, SUM(alipayTotalPrice) AS order_ord_amt,
  66. COUNT(*) AS order_ord_num, SUM(pubSharePreFeeForCommission) AS order_ord_tfee
  67. FROM tk_order_details
  68. WHERE DATE(tbPaidTime) IN @orderTimes AND tkStatus=13 AND accountId=@accountId
  69. GROUP BY DATE(tbPaidTime), accountId
  70. ) AS sub
  71. ON tr.accountId = sub.accountId AND tr.report_date = sub.date
  72. SET tr.order_ord_amt_13 = sub.order_ord_amt, tr.order_ord_num_13 = sub.order_ord_num,
  73. tr.order_ord_tfee_13 = sub.order_ord_tfee;";
  74. DBContext.Execute(sql, new { accountId = _accountId, orderTimes });
  75. sql = @"
  76. UPDATE tk_report tr
  77. JOIN (
  78. SELECT
  79. accountId, DATE(tbPaidTime) AS date, SUM(alipayTotalPrice) AS order_ord_amt,
  80. COUNT(*) AS order_ord_num, SUM(pubSharePreFeeForCommission) AS order_ord_tfee
  81. FROM tk_order_details
  82. WHERE DATE(tbPaidTime) IN @orderTimes AND tkStatus=14 AND accountId=@accountId
  83. GROUP BY DATE(tbPaidTime), accountId
  84. ) AS sub
  85. ON tr.accountId = sub.accountId AND tr.report_date = sub.date
  86. SET tr.order_ord_amt_14 = sub.order_ord_amt, tr.order_ord_num_14 = sub.order_ord_num,
  87. tr.order_ord_tfee_14 = sub.order_ord_tfee;";
  88. DBContext.Execute(sql, new { accountId = _accountId, orderTimes });
  89. sql = @"UPDATE tk_report
  90. SET order_ord_num = order_ord_num_3 + order_ord_num_12 + order_ord_num_13 + order_ord_num_14
  91. WHERE DATE(report_date) IN @orderTimes AND accountId=@accountId;";
  92. DBContext.Execute(sql, new { accountId = _accountId, orderTimes });
  93. return total;
  94. }
  95. public int GetIncyOrders(int sleep)
  96. {
  97. string cacheKey = $":cache:GetIncyOrders:{_accountName}";
  98. string cacheKey2 = $":cache:GetIncyOrders:{_accountId}";
  99. DateTime endTime = DateTime.Now;
  100. DateTime startTime = endTime.AddDays(-1);
  101. DateTime last_modifiedTime = RedisHelper.Get<DateTime>(cacheKey);
  102. ////找出数据库最新的一天
  103. //var last = new DBContext.Table("tk_order_details")
  104. // .Order("modifiedTime DESC")
  105. // .Get<TkOrderDetailDTO>("accountId=@accountId", new { accountId = _accountId });
  106. if (last_modifiedTime != DateTime.MinValue)
  107. {
  108. startTime = last_modifiedTime;
  109. }
  110. else
  111. {
  112. last_modifiedTime = startTime;
  113. }
  114. //当日往前查询
  115. (int total, DateTime max_modifiedTime, List<DateTime> orderTimes) = GetTkOrders(startTime, endTime, last_modifiedTime, true, sleep);
  116. if (max_modifiedTime != DateTime.MinValue)
  117. {
  118. RedisHelper.Set(cacheKey, max_modifiedTime);
  119. RedisHelper.Set(cacheKey2, max_modifiedTime);
  120. }
  121. //todo 根据orderTimes、settlementTimes 更新被影响的相关行
  122. string sql = @"
  123. UPDATE tk_report tr
  124. JOIN (
  125. SELECT
  126. accountId, DATE(tbPaidTime) AS date, SUM(alipayTotalPrice) AS order_ord_amt,
  127. COUNT(*) AS order_ord_num, SUM(pubShareFeeForCommission) AS order_ord_tfee
  128. FROM tk_order_details
  129. WHERE DATE(tbPaidTime) IN @orderTimes AND tkStatus=3 AND accountId=@accountId
  130. GROUP BY DATE(tbPaidTime), accountId
  131. ) AS sub
  132. ON tr.accountId = sub.accountId AND tr.report_date = sub.date
  133. SET tr.order_ord_amt = sub.order_ord_amt, tr.order_ord_num_3 = sub.order_ord_num,
  134. tr.order_ord_tfee = sub.order_ord_tfee;";
  135. DBContext.Execute(sql, new { accountId = _accountId, orderTimes });
  136. sql = @"
  137. UPDATE tk_report tr
  138. JOIN (
  139. SELECT
  140. accountId, DATE(tbPaidTime) AS date, SUM(alipayTotalPrice) AS order_ord_amt,
  141. COUNT(*) AS order_ord_num, SUM(pubSharePreFeeForCommission) AS order_ord_tfee
  142. FROM tk_order_details
  143. WHERE DATE(tbPaidTime) IN @orderTimes AND tkStatus=12 AND accountId=@accountId
  144. GROUP BY DATE(tbPaidTime), accountId
  145. ) AS sub
  146. ON tr.accountId = sub.accountId AND tr.report_date = sub.date
  147. SET tr.order_ord_amt_12 = sub.order_ord_amt, tr.order_ord_num_12 = sub.order_ord_num,
  148. tr.order_ord_tfee_12 = sub.order_ord_tfee;";
  149. DBContext.Execute(sql, new { accountId = _accountId, orderTimes });
  150. sql = @"
  151. UPDATE tk_report tr
  152. JOIN (
  153. SELECT
  154. accountId, DATE(tbPaidTime) AS date, SUM(alipayTotalPrice) AS order_ord_amt,
  155. COUNT(*) AS order_ord_num, SUM(pubSharePreFeeForCommission) AS order_ord_tfee
  156. FROM tk_order_details
  157. WHERE DATE(tbPaidTime) IN @orderTimes AND tkStatus=13 AND accountId=@accountId
  158. GROUP BY DATE(tbPaidTime), accountId
  159. ) AS sub
  160. ON tr.accountId = sub.accountId AND tr.report_date = sub.date
  161. SET tr.order_ord_amt_13 = sub.order_ord_amt, tr.order_ord_num_13 = sub.order_ord_num,
  162. tr.order_ord_tfee_13 = sub.order_ord_tfee;";
  163. DBContext.Execute(sql, new { accountId = _accountId, orderTimes });
  164. sql = @"
  165. UPDATE tk_report tr
  166. JOIN (
  167. SELECT
  168. accountId, DATE(tbPaidTime) AS date, SUM(alipayTotalPrice) AS order_ord_amt,
  169. COUNT(*) AS order_ord_num, SUM(pubSharePreFeeForCommission) AS order_ord_tfee
  170. FROM tk_order_details
  171. WHERE DATE(tbPaidTime) IN @orderTimes AND tkStatus=14 AND accountId=@accountId
  172. GROUP BY DATE(tbPaidTime), accountId
  173. ) AS sub
  174. ON tr.accountId = sub.accountId AND tr.report_date = sub.date
  175. SET tr.order_ord_amt_14 = sub.order_ord_amt, tr.order_ord_num_14 = sub.order_ord_num,
  176. tr.order_ord_tfee_14 = sub.order_ord_tfee;";
  177. DBContext.Execute(sql, new { accountId = _accountId, orderTimes });
  178. sql = @"UPDATE tk_report
  179. SET order_ord_num = order_ord_num_3 + order_ord_num_12 + order_ord_num_13 + order_ord_num_14
  180. WHERE DATE(report_date) IN @orderTimes AND accountId=@accountId;";
  181. DBContext.Execute(sql, new { accountId = _accountId, orderTimes });
  182. return total;
  183. }
  184. public int GetOrdersByAdZone(long adzoneId, DateTime startTime, DateTime endTime, int sleep)
  185. {
  186. string cacheKey = $":cache:GetOrdersByAdZone:{_accountName}";
  187. string cacheKey2 = $":cache:GetOrdersByAdZone:{_accountId}";
  188. DateTime last_modifiedTime = RedisHelper.Get<DateTime>(cacheKey);
  189. if (last_modifiedTime != DateTime.MinValue)
  190. {
  191. startTime = last_modifiedTime;
  192. }
  193. else
  194. {
  195. last_modifiedTime = startTime;
  196. }
  197. //当日往前查询
  198. (int total, DateTime max_modifiedTime, List<DateTime> orderTimes) = GetTkOrdersByAdZone(adzoneId, startTime, endTime, last_modifiedTime, true, sleep);
  199. if (max_modifiedTime != DateTime.MinValue)
  200. {
  201. RedisHelper.Set(cacheKey, max_modifiedTime);
  202. RedisHelper.Set(cacheKey2, max_modifiedTime);
  203. }
  204. return total;
  205. }
  206. public (int, DateTime, List<DateTime>) GetTkOrdersByAdZone(long adzoneId, DateTime startTime, DateTime endTime, DateTime last_modifiedTime, bool desc = true, int sleep = 100)
  207. {
  208. List<DateTime> orderTimes = [];
  209. if (startTime > endTime)
  210. {
  211. (startTime, endTime) = (endTime, startTime);
  212. }
  213. DateTime max_modifiedTime = last_modifiedTime;
  214. int pageNo = 1;
  215. string positionIndex = string.Empty;
  216. int pageSize = 100;
  217. bool hasNext = true;
  218. int total = 0;
  219. while (hasNext)
  220. {
  221. var ts = DateTime.Now.Convert2UnixTimestamp(true);
  222. string jumpType = pageNo == 1 ? "0" : "1";
  223. #if DEBUG
  224. jumpType = pageNo == 1 ? "0" : "1";
  225. #endif
  226. string queryType = desc ? "4" : "2";
  227. 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()}";
  228. string body = "";
  229. JsonElement data;
  230. try
  231. {
  232. for (var i = 1; i <= 5; i++)
  233. {
  234. var client = new WebClientUtility().SetContentType("application/json;charset=utf-8")
  235. .AddHeaders("X-Requested-With", "XMLHttpRequest")
  236. .AddHeaders("Cookie", _cookies);
  237. #if DEBUG
  238. #else
  239. client.Proxy = _proxy;
  240. #endif
  241. if (!string.IsNullOrEmpty(_user_agent)) client.UserAgent = _user_agent;
  242. var response = client.Request(url);
  243. if (response.ResponseException != null)
  244. {
  245. _ = new LoggerLibrary("api_error", "fail")
  246. .Info(response.ResponseException.Message, response.ResponseException.StackTrace)
  247. .SaveAsync();
  248. throw response.ResponseException;
  249. }
  250. body = response.Body();
  251. #if DEBUG
  252. _ = new LoggerLibrary("debug", "GetTkOrdersByAdZone")
  253. .Info(body)
  254. .SaveAsync();
  255. #endif
  256. if (body.Contains("{\"action\":\"captcha\""))
  257. {
  258. string message = $"【GetTkOrdersByAdZone】【{_accountId}:{_accountName}】第 {i} 次出现滑动验证码";
  259. NotifyCore.Notify(new NifyMessage
  260. {
  261. message = message,
  262. priority = NifyMessagePriority.high,
  263. tags = ["red_circle"]
  264. });
  265. Thread.Sleep(i * 60 * 1000);
  266. continue;
  267. }
  268. if (body.Contains("\"resultCode\":500"))
  269. {
  270. string message = $"【GetTkOrdersByAdZone】【{_accountId}:{_accountName}】第 {i} 次出现错误\n{body}";
  271. NotifyCore.Notify(new NifyMessage
  272. {
  273. message = message,
  274. priority = NifyMessagePriority.high,
  275. tags = ["red_circle"]
  276. });
  277. Thread.Sleep(i * 60 * 1000);
  278. continue;
  279. }
  280. break;
  281. }
  282. var root = body.Convert2JsonElement();
  283. var success = root.Read<bool>("success");
  284. data = root.ElementRead("data");
  285. if (!success && body.Contains("nologin"))
  286. {
  287. (success, string message) = RenewCookie();
  288. if (!success)
  289. {
  290. TkPoolCore.Disabled(_accountId, _accountName, $"{body}");
  291. }
  292. return (0, DateTime.MinValue, new List<DateTime>());
  293. }
  294. if (!success)
  295. {
  296. throw new APIException(body);
  297. }
  298. }
  299. catch (Exception ex)
  300. {
  301. throw new APIException(body);
  302. }
  303. using var conn = DBContext.GetOpenConnection();
  304. conn.Open();
  305. try
  306. {
  307. foreach (var order in data.ElementRead("result").EnumerateArray())
  308. {
  309. TkOrderDetailAdZoneDTO item = order.GetRawText().Convert2Object<TkOrderDetailAdZoneDTO>();
  310. // 处理每个订单数据
  311. if (item.adzoneId != adzoneId) continue;
  312. item.accountId = _accountId;
  313. item.accountName = _company;
  314. if (item.modifiedTime > max_modifiedTime) max_modifiedTime = item.modifiedTime;
  315. if (last_modifiedTime != DateTime.MinValue && last_modifiedTime >= item.modifiedTime)
  316. {
  317. return (total, max_modifiedTime, orderTimes);
  318. }
  319. if (item.tkStatus == 3 && item.tbPaidTime != DateTime.MinValue) orderTimes.Add(item.tbPaidTime.Date);
  320. int? id = conn.Replace(item);
  321. total++;
  322. }
  323. }
  324. catch (Exception ex)
  325. {
  326. throw;
  327. }
  328. finally
  329. {
  330. conn.Dispose();
  331. }
  332. pageNo++;
  333. hasNext = data.Read<bool>("hasNext");
  334. positionIndex = data.Read<string>("positionIndex");
  335. if (sleep > 0) Thread.Sleep(sleep);
  336. }
  337. return (total, max_modifiedTime, orderTimes);
  338. }
  339. public (int, DateTime, List<DateTime>) GetTkOrders(DateTime startTime, DateTime endTime, DateTime last_modifiedTime, bool desc = true, int sleep = 100)
  340. {
  341. List<DateTime> orderTimes = [];
  342. // 确保 startTime 小于 endTime
  343. if (startTime > endTime)
  344. {
  345. (startTime, endTime) = (endTime, startTime);
  346. }
  347. DateTime max_modifiedTime = last_modifiedTime;
  348. int pageNo = 1;
  349. string positionIndex = string.Empty;
  350. int pageSize = 100;
  351. bool hasNext = true;
  352. int total = 0;
  353. while (hasNext)
  354. {
  355. var ts = DateTime.Now.Convert2UnixTimestamp(true);
  356. //string jumpType = desc ? pageNo == 1 ? "0" : "1" : "-1";
  357. string jumpType = pageNo == 1 ? "0" : "1";
  358. #if DEBUG
  359. jumpType = pageNo == 1 ? "0" : "1";
  360. #endif
  361. //string queryType = "1";
  362. //1 创建时间;3结算时间 2付款时间 4更新时间
  363. //string queryType = "2";
  364. string queryType = desc ? "4" : "2";
  365. 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()}";
  366. //https://pub.alimama.com/openapi/param2/1/gateway.unionpub/report.getTbkOrderDetails.json?t=1719477837298&_tb_token_=7537e7ed93338&pageNo=92&pageSize=20&startTime=2024-03-31&endTime=2024-03-31&payStatus=&queryType=2&jumpType=1&tkTradeId=&positionIndex=1711883373_2vtPPr7CyYX2%7C1711883522_4zcICUeUevh2
  367. //https://pub.alimama.com/openapi/param2/1/gateway.unionpub/report.getTbkOrderDetails.json?t=1719477942492&_tb_token_=7537e7ed93338&pageNo=7&pageSize=20&startTime=2024-03-31&endTime=2024-03-31&payStatus=&queryType=2&jumpType=1&tkTradeId=&positionIndex=1711899163_4zdpOH1mbTQ2%7C1711899483_4zbH9BHqgl82
  368. string body = "";
  369. JsonElement data;
  370. try
  371. {
  372. for (var i = 1; i <= 5; i++)
  373. {
  374. var client = new WebClientUtility().SetContentType("application/json;charset=utf-8")
  375. .AddHeaders("X-Requested-With", "XMLHttpRequest")
  376. .AddHeaders("Cookie", _cookies);
  377. #if DEBUG
  378. #else
  379. client.Proxy = _proxy;
  380. #endif
  381. if (!string.IsNullOrEmpty(_user_agent)) client.UserAgent = _user_agent;
  382. var response = client.Request(url);
  383. if (response.ResponseException != null)
  384. {
  385. _ = new LoggerLibrary("api_error", "fail")
  386. .Info(response.ResponseException.Message, response.ResponseException.StackTrace)
  387. .SaveAsync();
  388. throw response.ResponseException;
  389. }
  390. body = response.Body();
  391. #if DEBUG
  392. _ = new LoggerLibrary("debug", "GetTkOrders")
  393. .Info(body)
  394. .SaveAsync();
  395. #endif
  396. if (body.Contains("{\"action\":\"captcha\""))
  397. {
  398. string message = $"【GetTkOrders】【{_accountId}:{_accountName}】第 {i} 次出现滑动验证码";
  399. NotifyCore.Notify(new NifyMessage
  400. {
  401. message = message,
  402. priority = NifyMessagePriority.high,
  403. tags = ["red_circle"]
  404. });
  405. Thread.Sleep(i * 60 * 1000);
  406. continue;
  407. }
  408. if (body.Contains("\"resultCode\":500"))
  409. {
  410. //{"success":false,"resultCode":500,"bizErrorDesc":"系统繁忙,请稍后重试!","bizErrorCode":3001}
  411. string message = $"【GetTkOrders】【{_accountId}:{_accountName}】第 {i} 次出现错误\n{body}";
  412. NotifyCore.Notify(new NifyMessage
  413. {
  414. message = message,
  415. priority = NifyMessagePriority.high,
  416. tags = ["red_circle"]
  417. });
  418. Thread.Sleep(i * 60 * 1000);
  419. continue;
  420. }
  421. break;
  422. }
  423. /*
  424. <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--> */
  425. var root = body.Convert2JsonElement();
  426. var success = root.Read<bool>("success");
  427. data = root.ElementRead("data");
  428. //{"code":601,"info":{"ok":false,"message":"nologin"}}
  429. if (!success && body.Contains("nologin"))
  430. {
  431. (success, string message) = RenewCookie();
  432. if (!success)
  433. {
  434. TkPoolCore.Disabled(_accountId, _accountName, $"{body}");
  435. }
  436. return (0, DateTime.MinValue, new List<DateTime>());
  437. }
  438. if (!success)
  439. {
  440. throw new APIException(body);
  441. }
  442. }
  443. catch (Exception ex)
  444. {
  445. _ = new LoggerLibrary("debug", "GetTkOrders")
  446. .Info(body)
  447. .SaveAsync();
  448. string message = $"【GetRawItemId】{_accountId}:{_accountName}\t{_proxy?.Address}\n" +
  449. $"{body}\n{ex.Message}\n{ex.StackTrace}";
  450. if (sleep > 0) Thread.Sleep(sleep);
  451. throw new APIException(body);
  452. }
  453. using var conn = DBContext.GetOpenConnection();
  454. conn.Open();
  455. try
  456. {
  457. foreach (var order in data.ElementRead("result").EnumerateArray())
  458. {
  459. TkOrderDetailDTO item = order.GetRawText().Convert2Object<TkOrderDetailDTO>();
  460. // 处理每个订单数据
  461. item.accountId = _accountId;
  462. item.accountName = _company;
  463. if (item.modifiedTime > max_modifiedTime) max_modifiedTime = item.modifiedTime;
  464. if (last_modifiedTime != DateTime.MinValue && last_modifiedTime >= item.modifiedTime)
  465. {
  466. return (total, max_modifiedTime, orderTimes);
  467. }
  468. //进行订单和转链匹配
  469. item.itemId = GetRawItemId(item.mktId);
  470. if (item.tkStatus == 3 && item.tbPaidTime != DateTime.MinValue) orderTimes.Add(item.tbPaidTime.Date);
  471. int? id = conn.Replace(item);
  472. if (id != null)
  473. {
  474. item.id = (int)id;
  475. TkOrderTrackingCore.MatchOrder(_account, item, conn);
  476. }
  477. total++;
  478. }
  479. }
  480. catch (Exception ex)
  481. {
  482. if (sleep > 0) Thread.Sleep(sleep);
  483. throw;
  484. }
  485. finally
  486. {
  487. conn.Dispose();
  488. }
  489. pageNo++;
  490. hasNext = data.Read<bool>("hasNext");
  491. positionIndex = data.Read<string>("positionIndex");
  492. if (sleep > 0) Thread.Sleep(sleep);
  493. }
  494. return (total, max_modifiedTime, orderTimes);
  495. }
  496. string GetRawItemId(string mktId)
  497. {
  498. string body = string.Empty, location = string.Empty;
  499. try
  500. {
  501. string lock_key = $"lock:GetRawItemId:disabled";
  502. int count = RedisHelper.Get<int>(lock_key);
  503. if (count > 0) return null;
  504. string cacheKey = $":cache:mkt2itemId:{mktId}";
  505. string itemId = RedisHelper.Get(cacheKey);
  506. if (itemId != null) return itemId;
  507. var ts = DateTime.Now.Convert2UnixTimestamp(true);
  508. string url = "https://pub.alimama.com/openapi/param2/1/gateway.unionpub/union.moose.content.entry";
  509. //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}";
  510. var client = new WebClientUtility()
  511. .SetContentType("application/x-www-form-urlencoded")
  512. .AddHeaders("Cookie", _cookies)
  513. .AddHeaders("Origin", "https://pub.alimama.com")
  514. .Post("_tb_token_", _tb_token)
  515. .Post("t", ts.ToString())
  516. .Post("bizType", "detailPage")
  517. .Post("bizParam", $"{{\"itemId\":\"{mktId}\"}}");
  518. //_tb_token_=3b88755bbe3f7&t=1718896771391&bizType=detailPage&bizParam=%7B%22itemId%22%3A%22JbtMUqkGMQvagTNb2Fvta-9ag242pu7MOX5e0bsrY%22%7D
  519. //_tb_token_=361e383eb61e5&t=1718895935097&bizType=detailPage&bizParam=%7B%22itemId%22%3A%22JbtMUqkGMQvagTNb2Fvta-9ag242pu7MOX5e0bsrY%22%7D
  520. #if DEBUG
  521. #else
  522. client.Proxy = _proxy;
  523. #endif
  524. if (!string.IsNullOrEmpty(_user_agent)) client.UserAgent = _user_agent;
  525. var response = client.Request(url);
  526. if (!response.Successed)
  527. {
  528. throw response.ResponseException;
  529. }
  530. location = response.ResponseMessage?.Headers?.Location?.ToString();
  531. if (!string.IsNullOrEmpty(location) && location.Contains("err.taobao.com/error1.html"))
  532. {
  533. RedisHelper.Set(lock_key, 1, 60);
  534. string message = $"【GetRawItemId】{_accountId}:{_accountName}\t{_proxy?.Address}\n" +
  535. $"{mktId}\n{location}";
  536. NotifyCore.Notify(new NifyMessage
  537. {
  538. message = message,
  539. priority = NifyMessagePriority.high,
  540. tags = ["red_circle"]
  541. });
  542. return null;
  543. }
  544. body = response.Body();
  545. var root = body.Convert2JsonElement();
  546. itemId = root.PathRead<string>("model.item.itemId");
  547. if (!string.IsNullOrEmpty(itemId))
  548. {
  549. RedisHelper.Set(cacheKey, itemId, 86400 * 7);
  550. }
  551. return itemId;
  552. }
  553. catch (Exception ex)
  554. {
  555. string message = $"【GetRawItemId】{_accountId}:{_accountName}\t{_proxy?.Address}\n" +
  556. $"{mktId}\n{location}\n{body}\n{ex.Message}";
  557. NotifyCore.Notify(new NifyMessage
  558. {
  559. message = message,
  560. priority = NifyMessagePriority.high,
  561. tags = ["red_circle"]
  562. });
  563. }
  564. return null;
  565. }
  566. public void GetTkOrders222()
  567. {
  568. try
  569. {
  570. string url = "https://media.alimama.com/violationu2/warning_instance_page_v2.json?r=mx_208&toPage=1&pageSize=40&params=";
  571. var client = new WebClientUtility().SetContentType("application/json;charset=utf-8")
  572. .AddHeaders("X-Requested-With", "XMLHttpRequest")
  573. .AddHeaders("Cookie", _cookies);
  574. client.Proxy = _proxy;
  575. if (!string.IsNullOrEmpty(_user_agent)) client.UserAgent = _user_agent;
  576. var response = client.Request(url);
  577. var body = response.Body();
  578. var root = body.Convert2JsonElement();
  579. int resultCode = root.Read<int>("resultCode", 0);
  580. int totalCount = root.PathRead<int>("data.totalCount", 0);
  581. bool success = root.Read("success", false);
  582. if (!success)
  583. {
  584. _ = new LoggerLibrary("violationu", "warning_error")
  585. .Info(url, body)
  586. .SaveAsync();
  587. throw new Exception(body);
  588. }
  589. if (totalCount == 0) return;
  590. _ = new LoggerLibrary("violationu", "warning").Info(url, body).SaveAsync();
  591. var list = root.ElementRead("data").ElementRead("result").EnumerateArray();
  592. foreach (var data in list)
  593. {
  594. var violation_commission = data.PathRead<decimal>("mediaInfo.订单虚假交易违规佣金", 0);
  595. new DBContext.Table("alimama_warning")
  596. .Fill(data)
  597. .Loader<int>("filterRuleId", 0)
  598. .Loader<long>("gmtCreate", 0)
  599. .Loader<long>("id", 0, "ali_id")
  600. .Loader<string>("idStr", string.Empty)
  601. .Loader<int>("mediaDimension", 0)
  602. .Loader<long>("mediaId", 0)
  603. .Loader<int>("mediaInfo.abn_cnt", 0, "abn_cnt")
  604. .Add("violation_commission", violation_commission)
  605. .Loader<int>("mediaInfo.warning_cnt", 0, "warning_cnt")
  606. .Loader<string>("mediaName", string.Empty)
  607. .Loader<long>("memberId", 0)
  608. .Loader<string>("noticeCategory", string.Empty)
  609. .Loader<int>("noticeTemplateId", 0)
  610. .Loader<string>("noticeTemplateName", string.Empty)
  611. .Loader<string>("orderFile", string.Empty)
  612. .Loader<string>("pid", string.Empty)
  613. .Loader<int>("punishRuleId", 0)
  614. .Loader<string>("riskType", string.Empty)
  615. .Loader<string>("roleName", string.Empty)
  616. .Loader<string>("ruleLink", string.Empty)
  617. .Loader<bool>("showOrderDetail", false)
  618. .Loader<int>("status", 0, "ali_status")
  619. .Loader<string>("warningText", string.Empty)
  620. .Add("accountName", _accountName)
  621. .Add("status", true)
  622. .Add("create_time", DateTime.Now)
  623. .Add("last_time", DateTime.Now)
  624. .Create(DBContext.InsertType.REPLACE);
  625. }
  626. }
  627. catch (Exception ex) { }
  628. }
  629. }
  630. }