VivoAuthService.java 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574
  1. package com.adx.tencent.vivo.service;
  2. import com.adx.tencent.vivo.model.VivoAdvertiserAccountRecord;
  3. import com.adx.tencent.vivo.model.VivoClientConfigRecord;
  4. import com.adx.tencent.vivo.model.VivoTokenRecord;
  5. import com.adx.tencent.vivo.store.VivoColdStore;
  6. import com.fasterxml.jackson.databind.JsonNode;
  7. import com.fasterxml.jackson.databind.ObjectMapper;
  8. import org.slf4j.Logger;
  9. import org.slf4j.LoggerFactory;
  10. import org.springframework.data.redis.core.StringRedisTemplate;
  11. import java.net.URI;
  12. import java.net.URLEncoder;
  13. import java.net.http.HttpClient;
  14. import java.net.http.HttpRequest;
  15. import java.net.http.HttpResponse;
  16. import java.nio.charset.StandardCharsets;
  17. import java.time.Duration;
  18. import java.time.Instant;
  19. import java.util.ArrayList;
  20. import java.util.LinkedHashMap;
  21. import java.util.List;
  22. import java.util.Map;
  23. import java.util.UUID;
  24. import java.util.concurrent.ConcurrentHashMap;
  25. public class VivoAuthService {
  26. private static final Logger log = LoggerFactory.getLogger(VivoAuthService.class);
  27. private static final long REFRESH_AHEAD_MS = 60_000L;
  28. private static final Duration DEFAULT_REDIS_TTL = Duration.ofDays(30);
  29. private static final String TOKEN_PATH = "/openapi/v1/oauth2/token";
  30. private static final String REFRESH_PATH = "/openapi/v1/oauth2/refreshToken";
  31. private static final String AGENT_FETCH_PATH = "/openapi/v1/account/agent/fetch";
  32. private final String baseUrl;
  33. private final String redirectUri;
  34. private final String tokenRedisKeyPrefix;
  35. private final String advertiserRedisKeyPrefix;
  36. private final StringRedisTemplate redis;
  37. private final VivoColdStore coldStore;
  38. private final ObjectMapper objectMapper;
  39. private final HttpClient httpClient;
  40. private final ConcurrentHashMap<String, Object> locks = new ConcurrentHashMap<>();
  41. public VivoAuthService(String baseUrl,
  42. String redirectUri,
  43. String tokenRedisKeyPrefix,
  44. String advertiserRedisKeyPrefix,
  45. StringRedisTemplate redis,
  46. VivoColdStore coldStore,
  47. ObjectMapper objectMapper) {
  48. this.baseUrl = trimTrailingSlash(baseUrl);
  49. this.redirectUri = redirectUri;
  50. this.tokenRedisKeyPrefix = tokenRedisKeyPrefix == null ? "adx:vivo:token:" : tokenRedisKeyPrefix;
  51. this.advertiserRedisKeyPrefix = advertiserRedisKeyPrefix == null
  52. ? "adx:vivo:advertiser:"
  53. : advertiserRedisKeyPrefix;
  54. this.redis = redis;
  55. this.coldStore = coldStore;
  56. this.objectMapper = objectMapper;
  57. this.httpClient = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(10)).build();
  58. }
  59. public VivoTokenRecord authorizeSecondaryAccount(String secondaryAccountId, String clientId, String code) {
  60. if (secondaryAccountId == null || secondaryAccountId.isBlank()) {
  61. throw new IllegalArgumentException("vivo secondaryAccountId is required");
  62. }
  63. if (code == null || code.isBlank()) {
  64. throw new IllegalArgumentException("vivo authorization code is required");
  65. }
  66. String expectedSecondaryAccountId = secondaryAccountId.trim();
  67. ClientCredentials credentials = resolveAuthorizeCredentials(expectedSecondaryAccountId, clientId);
  68. TokenPayload payload = fetchToken(Map.of(
  69. "client_id", credentials.clientId,
  70. "client_secret", credentials.clientSecret,
  71. "grant_type", "code",
  72. "code", code
  73. ), TOKEN_PATH);
  74. AgentAccountProfile profile = fetchAgentAccountProfile(payload.accessToken);
  75. if (profile.accountId == null || profile.accountId.isBlank()) {
  76. throw new IllegalStateException("vivo secondary account uuid is missing");
  77. }
  78. if (!expectedSecondaryAccountId.equals(profile.accountId)) {
  79. throw new IllegalStateException("authorized vivo secondaryAccountId mismatch: expected="
  80. + expectedSecondaryAccountId + ", actual=" + profile.accountId);
  81. }
  82. VivoTokenRecord record = buildTokenRecord(profile, payload, expectedSecondaryAccountId, credentials);
  83. saveToken(record);
  84. log.info("[Vivo][授权] secondaryAccountId={} accountName={} level={} status={} tokenExpireAt={} refreshExpireAt={}",
  85. record.getAccountId(), record.getAccountName(), record.getAccountLevel(), record.getAccountStatus(),
  86. record.getTokenExpireAt(), record.getRefreshTokenExpireAt());
  87. return record;
  88. }
  89. public String getAccessTokenForAdvertiser(String advertiserId) {
  90. if (advertiserId == null || advertiserId.isBlank()) {
  91. throw new IllegalArgumentException("vivo advertiserId is required");
  92. }
  93. String normalizedAdvertiserId = advertiserId.trim();
  94. String secondaryAccountId = resolveSecondaryAccountId(normalizedAdvertiserId);
  95. if (secondaryAccountId != null && !secondaryAccountId.isBlank()) {
  96. return getAccessTokenBySecondaryAccountId(secondaryAccountId);
  97. }
  98. VivoTokenRecord directAuthorized = loadToken(normalizedAdvertiserId);
  99. if (directAuthorized != null) {
  100. log.warn("[Vivo][Token] advertiserId={} 未命中二代映射,退回使用同ID授权 token", normalizedAdvertiserId);
  101. return getAccessTokenBySecondaryAccountId(normalizedAdvertiserId);
  102. }
  103. throw new IllegalStateException("vivo advertiser not mapped to any secondary account: " + normalizedAdvertiserId);
  104. }
  105. public String getAccessTokenBySecondaryAccountId(String secondaryAccountId) {
  106. if (secondaryAccountId == null || secondaryAccountId.isBlank()) {
  107. throw new IllegalArgumentException("vivo secondaryAccountId is required");
  108. }
  109. String normalizedSecondaryAccountId = secondaryAccountId.trim();
  110. synchronized (locks.computeIfAbsent(normalizedSecondaryAccountId, ignored -> new Object())) {
  111. VivoTokenRecord record = loadToken(normalizedSecondaryAccountId);
  112. long now = System.currentTimeMillis();
  113. if (isUsable(record != null ? record.getAccessToken() : null, record != null ? record.getTokenExpireAt() : null, now)) {
  114. return record.getAccessToken();
  115. }
  116. if (record != null && isUsable(record.getRefreshToken(), record.getRefreshTokenExpireAt(), now)) {
  117. VivoTokenRecord refreshed = refresh(normalizedSecondaryAccountId, record.getRefreshToken());
  118. return refreshed.getAccessToken();
  119. }
  120. if (record != null && record.getAccessToken() != null && !record.getAccessToken().isBlank()) {
  121. log.warn("[Vivo][Token] secondaryAccountId={} access_token 已过期且 refresh_token 不可用,暂退回使用旧 token",
  122. normalizedSecondaryAccountId);
  123. return record.getAccessToken();
  124. }
  125. throw new IllegalStateException("vivo secondary account not authorized: " + normalizedSecondaryAccountId);
  126. }
  127. }
  128. public List<VivoTokenRecord> listAuthorizedSecondaryAccounts() {
  129. if (coldStore == null) {
  130. return List.of();
  131. }
  132. return coldStore.listTokens();
  133. }
  134. public void cacheAdvertiserMappings(List<VivoAdvertiserAccountRecord> records) {
  135. if (records == null || records.isEmpty()) {
  136. return;
  137. }
  138. for (VivoAdvertiserAccountRecord record : records) {
  139. cacheAdvertiserMapping(record);
  140. }
  141. }
  142. public void evictAdvertiserMappings(List<String> advertiserIds) {
  143. if (advertiserIds == null || advertiserIds.isEmpty()) {
  144. return;
  145. }
  146. for (String advertiserId : advertiserIds) {
  147. if (advertiserId == null || advertiserId.isBlank()) {
  148. continue;
  149. }
  150. try {
  151. redis.delete(advertiserRedisKey(advertiserId.trim()));
  152. } catch (Exception e) {
  153. log.warn("[Vivo][Advertiser] evict redis failed | advertiserId={} | error={}",
  154. advertiserId, e.getMessage());
  155. }
  156. }
  157. }
  158. public String buildAuthorizeUrl(String secondaryAccountId, String clientId) {
  159. String normalizedSecondaryAccountId = secondaryAccountId == null ? "" : secondaryAccountId.trim();
  160. ClientCredentials credentials = requireClientConfig(clientId);
  161. return trimTrailingSlash("https://open-ad.vivo.com.cn")
  162. + "/OAuth?clientId=" + urlEncode(credentials.clientId)
  163. + "&state=" + urlEncode(normalizedSecondaryAccountId)
  164. + "&redirectUri=" + urlEncode(redirectUri == null ? "" : redirectUri);
  165. }
  166. public String buildAuthorizeState(String secondaryAccountId, String clientId) {
  167. if (secondaryAccountId == null || secondaryAccountId.isBlank()) {
  168. throw new IllegalArgumentException("vivo secondaryAccountId is required");
  169. }
  170. return secondaryAccountId.trim();
  171. }
  172. private String resolveSecondaryAccountId(String advertiserId) {
  173. String cached = loadSecondaryAccountIdFromRedis(advertiserId);
  174. if (cached != null) {
  175. return cached;
  176. }
  177. if (coldStore == null) {
  178. return null;
  179. }
  180. VivoAdvertiserAccountRecord record = coldStore.getAdvertiserAccount(advertiserId);
  181. if (record != null && record.getSecondaryAccountId() != null && !record.getSecondaryAccountId().isBlank()) {
  182. cacheAdvertiserMapping(record);
  183. return record.getSecondaryAccountId();
  184. }
  185. return null;
  186. }
  187. private String loadSecondaryAccountIdFromRedis(String advertiserId) {
  188. try {
  189. String payload = redis.opsForValue().get(advertiserRedisKey(advertiserId));
  190. return payload == null || payload.isBlank() ? null : payload.trim();
  191. } catch (Exception e) {
  192. log.warn("[Vivo][Advertiser] read redis failed | advertiserId={} | error={}", advertiserId, e.getMessage());
  193. return null;
  194. }
  195. }
  196. private void cacheAdvertiserMapping(VivoAdvertiserAccountRecord record) {
  197. if (record == null || record.getAdvertiserId() == null || record.getAdvertiserId().isBlank()
  198. || record.getSecondaryAccountId() == null || record.getSecondaryAccountId().isBlank()) {
  199. return;
  200. }
  201. try {
  202. redis.opsForValue().set(
  203. advertiserRedisKey(record.getAdvertiserId().trim()),
  204. record.getSecondaryAccountId().trim(),
  205. DEFAULT_REDIS_TTL
  206. );
  207. } catch (Exception e) {
  208. log.warn("[Vivo][Advertiser] write redis failed | advertiserId={} | secondaryAccountId={} | error={}",
  209. record.getAdvertiserId(), record.getSecondaryAccountId(), e.getMessage());
  210. }
  211. }
  212. private VivoTokenRecord refresh(String secondaryAccountId, String refreshToken) {
  213. ClientCredentials credentials = requireStoredCredentials(secondaryAccountId);
  214. TokenPayload payload = fetchToken(Map.of(
  215. "client_id", credentials.clientId,
  216. "client_secret", credentials.clientSecret,
  217. "refresh_token", refreshToken
  218. ), REFRESH_PATH);
  219. AgentAccountProfile profile = fetchAgentAccountProfile(payload.accessToken);
  220. if (profile.accountId != null && !profile.accountId.isBlank() && !secondaryAccountId.equals(profile.accountId)) {
  221. throw new IllegalStateException("refreshed vivo secondaryAccountId mismatch: expected="
  222. + secondaryAccountId + ", actual=" + profile.accountId);
  223. }
  224. VivoTokenRecord existing = coldStore != null ? coldStore.getToken(secondaryAccountId) : null;
  225. VivoTokenRecord record = buildTokenRecord(profile, payload, secondaryAccountId, credentials);
  226. record.setAuthorizedAt(existing != null && existing.getAuthorizedAt() != null ? existing.getAuthorizedAt() : Instant.now());
  227. saveToken(record);
  228. log.info("[Vivo][Token] secondaryAccountId={} refresh success tokenExpireAt={} refreshExpireAt={}",
  229. secondaryAccountId, payload.tokenExpireAt, payload.refreshTokenExpireAt);
  230. return record;
  231. }
  232. private VivoTokenRecord buildTokenRecord(AgentAccountProfile profile,
  233. TokenPayload payload,
  234. String secondaryAccountId,
  235. ClientCredentials credentials) {
  236. VivoTokenRecord record = new VivoTokenRecord();
  237. record.setAccountId(secondaryAccountId);
  238. record.setAccountName(profile.accountName);
  239. record.setAccountLevel(profile.accountLevel);
  240. record.setAccountStatus(profile.accountStatus);
  241. record.setClientId(credentials.clientId);
  242. record.setClientSecret(credentials.clientSecret);
  243. record.setAccessToken(payload.accessToken);
  244. record.setRefreshToken(payload.refreshToken);
  245. record.setTokenExpireAt(payload.tokenExpireAt);
  246. record.setRefreshTokenExpireAt(payload.refreshTokenExpireAt);
  247. if (record.getAuthorizedAt() == null) {
  248. record.setAuthorizedAt(Instant.now());
  249. }
  250. record.setUpdatedAt(Instant.now());
  251. return record;
  252. }
  253. private AgentAccountProfile fetchAgentAccountProfile(String accessToken) {
  254. try {
  255. long timestamp = System.currentTimeMillis();
  256. String nonce = randomNonce();
  257. HttpRequest request = HttpRequest.newBuilder()
  258. .uri(URI.create(baseUrl + AGENT_FETCH_PATH + "?" + toQuery(Map.of(
  259. "access_token", accessToken,
  260. "timestamp", String.valueOf(timestamp),
  261. "nonce", nonce
  262. ))))
  263. .GET()
  264. .timeout(Duration.ofSeconds(15))
  265. .build();
  266. HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString(StandardCharsets.UTF_8));
  267. if (response.statusCode() < 200 || response.statusCode() >= 300) {
  268. throw new IllegalStateException("HTTP status: " + response.statusCode() + ", body=" + response.body());
  269. }
  270. JsonNode root = objectMapper.readTree(response.body());
  271. int code = root.path("code").asInt(Integer.MIN_VALUE);
  272. if (code != 0) {
  273. throw new IllegalStateException("code=" + code + ", message=" + root.path("message").asText() + ", body=" + response.body());
  274. }
  275. JsonNode data = root.path("data");
  276. AgentAccountProfile profile = new AgentAccountProfile();
  277. profile.accountId = text(data, "uuid");
  278. profile.accountName = text(data, "name");
  279. profile.accountLevel = asInt(data.get("level"));
  280. profile.accountStatus = asInt(data.get("status"));
  281. return profile;
  282. } catch (Exception e) {
  283. throw new RuntimeException("fetch vivo secondary account failed: " + e.getMessage(), e);
  284. }
  285. }
  286. private TokenPayload fetchToken(Map<String, String> params, String path) {
  287. try {
  288. HttpRequest request = HttpRequest.newBuilder()
  289. .uri(URI.create(baseUrl + path + "?" + toQuery(params)))
  290. .GET()
  291. .timeout(Duration.ofSeconds(15))
  292. .build();
  293. HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString(StandardCharsets.UTF_8));
  294. if (response.statusCode() < 200 || response.statusCode() >= 300) {
  295. throw new IllegalStateException("HTTP status: " + response.statusCode() + ", body=" + response.body());
  296. }
  297. JsonNode root = objectMapper.readTree(response.body());
  298. int code = root.path("code").asInt(Integer.MIN_VALUE);
  299. if (code != 0) {
  300. throw new IllegalStateException("code=" + code + ", message=" + root.path("message").asText() + ", body=" + response.body());
  301. }
  302. JsonNode data = root.path("data");
  303. TokenPayload payload = new TokenPayload();
  304. payload.accessToken = text(data, "access_token");
  305. payload.refreshToken = text(data, "refresh_token");
  306. payload.tokenExpireAt = asLong(data.get("token_date"));
  307. payload.refreshTokenExpireAt = asLong(data.get("refresh_token_date"));
  308. if (payload.accessToken == null || payload.accessToken.isBlank()) {
  309. throw new IllegalStateException("missing access_token in vivo token response");
  310. }
  311. return payload;
  312. } catch (Exception e) {
  313. throw new RuntimeException("fetch vivo token failed: " + e.getMessage(), e);
  314. }
  315. }
  316. private VivoTokenRecord loadToken(String secondaryAccountId) {
  317. VivoTokenRecord cached = loadTokenFromRedis(secondaryAccountId);
  318. if (cached != null) {
  319. return cached;
  320. }
  321. if (coldStore == null) {
  322. return null;
  323. }
  324. VivoTokenRecord db = coldStore.getToken(secondaryAccountId);
  325. if (db != null) {
  326. cacheToken(db);
  327. }
  328. return db;
  329. }
  330. private VivoTokenRecord loadTokenFromRedis(String secondaryAccountId) {
  331. try {
  332. String payload = redis.opsForValue().get(tokenRedisKey(secondaryAccountId));
  333. if (payload == null || payload.isBlank()) {
  334. return null;
  335. }
  336. return objectMapper.readValue(payload, VivoTokenRecord.class);
  337. } catch (Exception e) {
  338. log.warn("[Vivo][Token] read redis failed | secondaryAccountId={} | error={}",
  339. secondaryAccountId, e.getMessage());
  340. return null;
  341. }
  342. }
  343. private void saveToken(VivoTokenRecord record) {
  344. cacheToken(record);
  345. if (coldStore != null) {
  346. coldStore.saveToken(record);
  347. }
  348. }
  349. private void cacheToken(VivoTokenRecord record) {
  350. try {
  351. redis.opsForValue().set(
  352. tokenRedisKey(record.getAccountId()),
  353. objectMapper.writeValueAsString(record),
  354. resolveRedisTtl(record)
  355. );
  356. } catch (Exception e) {
  357. log.warn("[Vivo][Token] write redis failed | secondaryAccountId={} | error={}",
  358. record.getAccountId(), e.getMessage());
  359. }
  360. }
  361. private Duration resolveRedisTtl(VivoTokenRecord record) {
  362. long now = System.currentTimeMillis();
  363. long expireAt = record.getRefreshTokenExpireAt() != null && record.getRefreshTokenExpireAt() > now
  364. ? record.getRefreshTokenExpireAt()
  365. : record.getTokenExpireAt() != null && record.getTokenExpireAt() > now
  366. ? record.getTokenExpireAt()
  367. : now + DEFAULT_REDIS_TTL.toMillis();
  368. long ttlMs = Math.max(expireAt - now, Duration.ofMinutes(5).toMillis());
  369. return Duration.ofMillis(ttlMs);
  370. }
  371. private String tokenRedisKey(String secondaryAccountId) {
  372. return tokenRedisKeyPrefix + secondaryAccountId;
  373. }
  374. private String advertiserRedisKey(String advertiserId) {
  375. return advertiserRedisKeyPrefix + advertiserId;
  376. }
  377. private ClientCredentials requireStoredCredentials(String secondaryAccountId) {
  378. if (secondaryAccountId == null || secondaryAccountId.isBlank()) {
  379. throw new IllegalArgumentException("vivo secondaryAccountId is required");
  380. }
  381. VivoTokenRecord record = loadToken(secondaryAccountId.trim());
  382. String clientId = record == null ? null : trimToNull(record.getClientId());
  383. String clientSecret = record == null ? null : trimToNull(record.getClientSecret());
  384. if (clientId == null || clientSecret == null) {
  385. throw new IllegalStateException("vivo clientId/clientSecret not maintained in DB for secondaryAccountId="
  386. + secondaryAccountId);
  387. }
  388. ClientCredentials credentials = new ClientCredentials();
  389. credentials.clientId = clientId;
  390. credentials.clientSecret = clientSecret;
  391. return credentials;
  392. }
  393. private ClientCredentials resolveAuthorizeCredentials(String secondaryAccountId, String clientId) {
  394. String normalizedClientId = trimToNull(clientId);
  395. if (normalizedClientId != null) {
  396. return requireClientConfig(normalizedClientId);
  397. }
  398. VivoTokenRecord existing = loadToken(secondaryAccountId);
  399. String storedClientId = existing == null ? null : trimToNull(existing.getClientId());
  400. String storedClientSecret = existing == null ? null : trimToNull(existing.getClientSecret());
  401. if (storedClientId != null && storedClientSecret != null) {
  402. ClientCredentials credentials = new ClientCredentials();
  403. credentials.clientId = storedClientId;
  404. credentials.clientSecret = storedClientSecret;
  405. return credentials;
  406. }
  407. List<VivoClientConfigRecord> enabledConfigs = coldStore == null ? List.of() : coldStore.listEnabledClientConfigs();
  408. if (enabledConfigs.size() == 1) {
  409. return requireClientConfig(enabledConfigs.get(0).getClientId());
  410. }
  411. if (enabledConfigs.isEmpty()) {
  412. throw new IllegalStateException("no enabled vivo client config found in vivo_client_configs");
  413. }
  414. throw new IllegalStateException("multiple enabled vivo client configs found; clientId is required for secondaryAccountId="
  415. + secondaryAccountId);
  416. }
  417. private ClientCredentials requireClientConfig(String clientId) {
  418. String normalizedClientId = trimToNull(clientId);
  419. if (normalizedClientId == null) {
  420. throw new IllegalArgumentException("vivo clientId is required");
  421. }
  422. VivoClientConfigRecord record = coldStore == null ? null : coldStore.getClientConfig(normalizedClientId);
  423. if (record == null) {
  424. throw new IllegalStateException("vivo clientId not maintained in vivo_client_configs: " + normalizedClientId);
  425. }
  426. if (Boolean.FALSE.equals(record.getEnabled())) {
  427. throw new IllegalStateException("vivo clientId disabled: " + normalizedClientId);
  428. }
  429. String clientSecret = trimToNull(record.getClientSecret());
  430. if (clientSecret == null) {
  431. throw new IllegalStateException("vivo clientSecret is empty for clientId=" + normalizedClientId);
  432. }
  433. ClientCredentials credentials = new ClientCredentials();
  434. credentials.clientId = normalizedClientId;
  435. credentials.clientSecret = clientSecret;
  436. return credentials;
  437. }
  438. private static boolean isUsable(String token, Long expireAt, long now) {
  439. return token != null && !token.isBlank() && expireAt != null && expireAt - now > REFRESH_AHEAD_MS;
  440. }
  441. private static String toQuery(Map<String, String> params) {
  442. StringBuilder sb = new StringBuilder();
  443. boolean first = true;
  444. for (Map.Entry<String, String> entry : params.entrySet()) {
  445. if (entry.getValue() == null || entry.getValue().isBlank()) continue;
  446. if (!first) sb.append('&');
  447. first = false;
  448. sb.append(urlEncode(entry.getKey())).append('=').append(urlEncode(entry.getValue()));
  449. }
  450. return sb.toString();
  451. }
  452. private static String randomNonce() {
  453. return UUID.randomUUID().toString().replace("-", "");
  454. }
  455. private static String urlEncode(String value) {
  456. return URLEncoder.encode(value, StandardCharsets.UTF_8);
  457. }
  458. private static String text(JsonNode node, String field) {
  459. JsonNode child = node == null ? null : node.get(field);
  460. if (child == null || child.isNull()) {
  461. return null;
  462. }
  463. String value = child.asText();
  464. return value == null || value.isBlank() ? null : value.trim();
  465. }
  466. private static Long asLong(JsonNode node) {
  467. if (node == null || node.isNull()) {
  468. return null;
  469. }
  470. if (node.isNumber()) {
  471. return node.longValue();
  472. }
  473. try {
  474. return Long.parseLong(node.asText().trim());
  475. } catch (Exception e) {
  476. return null;
  477. }
  478. }
  479. private static Integer asInt(JsonNode node) {
  480. if (node == null || node.isNull()) {
  481. return null;
  482. }
  483. if (node.isInt() || node.isLong()) {
  484. return node.intValue();
  485. }
  486. try {
  487. return Integer.parseInt(node.asText().trim());
  488. } catch (Exception e) {
  489. return null;
  490. }
  491. }
  492. private static String trimToNull(String value) {
  493. if (value == null) {
  494. return null;
  495. }
  496. String trimmed = value.trim();
  497. return trimmed.isEmpty() ? null : trimmed;
  498. }
  499. private static String trimTrailingSlash(String value) {
  500. if (value == null || value.isBlank()) {
  501. return "https://marketing-api.vivo.com.cn";
  502. }
  503. String result = value.trim();
  504. while (result.endsWith("/")) {
  505. result = result.substring(0, result.length() - 1);
  506. }
  507. return result;
  508. }
  509. private static class TokenPayload {
  510. private String accessToken;
  511. private String refreshToken;
  512. private Long tokenExpireAt;
  513. private Long refreshTokenExpireAt;
  514. }
  515. private static class AgentAccountProfile {
  516. private String accountId;
  517. private String accountName;
  518. private Integer accountLevel;
  519. private Integer accountStatus;
  520. }
  521. private static class ClientCredentials {
  522. private String clientId;
  523. private String clientSecret;
  524. }
  525. }