orders.cs 35 KB

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