orders.cs 33 KB

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