You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

217 lines
8.4 KiB

package common.ecommerce.edayun.auth;
import common.ecommerce.edayun.EdayunConstants;
import common.ecommerce.edayun.dto.EdayunTokenDtos;
import common.ecommerce.edayun.http.EdayunRequestFactory;
import common.ecommerce.http.HttpRequest;
import common.ecommerce.http.HttpResponse;
import common.ecommerce.http.JsonCodec;
import common.ecommerce.http.HttpTransport;
import common.ecommerce.shared.error.ValidationException;
import common.ecommerce.shared.spi.AccessToken;
import common.ecommerce.warehouse.error.WarehouseException;
import java.time.Clock;
import java.time.Instant;
/**
* 易达云获取 token({@code POST /oauth/token})。
*
* <p>凭据用 OMS 授权账号:{@link common.ecommerce.shared.spi.ChannelSecret#clientId()}
* / {@link common.ecommerce.shared.spi.ChannelSecret#clientSecret()}。
* appKey 不参与这一步(它是业务请求头的字段)。</p>
*
* <p><b>实测(2026-11-12,PR 环境)</b>:成功响应的 body 是扁平结构,没有 {@code code}:</p>
* <pre>
* HTTP 200
* {"access_token":"0dabff46-...","token_type":"bearer","scope":"server"}
* </pre>
*
* <p>token 是<b>永久</b>的(文档:「目前设计上是永久的,建议留个窗口刷新」),
* 响应里没有有效期字段。所以 {@code expiresAt} 是个估算值——用于让
* {@code TokenManager} 定期重登一次,而不是真的到期。</p>
*
* <p>兼容分支:若网关把结果包一层 {@code data} 或返回 {@code code},
* 也按对应形态解析(生产环境确认后可删)。</p>
*/
public final class EdayunTokenClient {
private static final String OP_FETCH = "token.fetch";
private final HttpTransport transport;
private final JsonCodec json;
private final EdayunRequestFactory requestFactory;
private final Clock clock;
public EdayunTokenClient(HttpTransport transport, JsonCodec json, Clock clock) {
this.transport = transport;
this.json = json;
this.clock = clock;
this.requestFactory = new EdayunRequestFactory(json);
}
/**
* 换取令牌。
*
* @param baseUrl 本次调用的基址
* @param clientId OMS 授权用户名
* @param clientSecret OMS 授权密码
*/
public AccessToken fetch(String baseUrl, String clientId, String clientSecret) {
HttpRequest req = requestFactory.token(baseUrl, clientId, clientSecret, OP_FETCH);
HttpResponse resp = transport.execute(req);
requireHttpOk(resp);
String body = resp.body();
EdayunTokenDtos.TokenResponse parsed;
try {
parsed = json.fromJson(body, EdayunTokenDtos.TokenResponse.class);
} catch (RuntimeException e) {
throw validation("edayun token response is not json", body);
}
requireBusinessOk(parsed, body);
String token = tokenOf(parsed, body);
return AccessToken.builder()
.value(token)
.expiresAt(expiresAtOf(parsed))
.build();
}
/** HTTP 层:非 2xx 直接失败。 */
private void requireHttpOk(HttpResponse resp) {
int status = resp.statusCode();
if (status >= 200 && status < 300) {
return;
}
throw toException(status, resp.body());
}
private WarehouseException toException(int status, String body) {
boolean retryable = status >= 500 && status != 504;
return WarehouseException.builder()
.message("edayun token request failed: http " + status
+ ", body=" + truncate(body))
.operation(OP_FETCH)
.provider(EdayunConstants.ADAPTER_ID)
.platformCode(String.valueOf(status))
.rawResponse(truncate(body))
.retryable(retryable)
.build();
}
/**
* 业务码:200 成功;500 失败;503 网关无效;504 超时。
*
* <p><b>实测该接口不返回 {@code code}</b>——HTTP 200 + body 里有 access_token
* 就是成功。所以 {@code code} 缺失时不算失败,交给后续的 token 存在性校验;
* 只有显式给了非 200 的 code 才判失败。</p>
*
* <p>503 通常是网关问题、504 是超时,都值得重试;500 是明确失败,不重试。</p>
*/
private void requireBusinessOk(EdayunTokenDtos.TokenResponse parsed, String body) {
if (parsed == null) {
throw validation("edayun token response is empty", body);
}
Integer code = parsed.code;
if (code == null) {
// 实测:扁平结构没有 code,视为成功,由 tokenOf 校验 token 是否存在
return;
}
if (code == EdayunConstants.CODE_SUCCESS) {
return;
}
throw WarehouseException.builder()
.message("edayun token business error: code=" + code
+ ", message=" + parsed.message)
.operation(OP_FETCH)
.provider(EdayunConstants.ADAPTER_ID)
.platformCode(String.valueOf(code))
.rawResponse(truncate(body))
.retryable(code == EdayunConstants.CODE_GATEWAY_INVALID
|| code == EdayunConstants.CODE_TIMEOUT)
.build();
}
/**
* 取 token:实测是顶层 {@code access_token};兼容 {@code data.access_token}
* 与顶层 {@code token}。都取不到就失败,不猜。
*/
private String tokenOf(EdayunTokenDtos.TokenResponse parsed, String body) {
if (hasText(parsed.accessToken)) {
return parsed.accessToken.trim();
}
if (parsed.data != null && hasText(parsed.data.accessToken)) {
return parsed.data.accessToken.trim();
}
String topLevel = json.stringAt(body, "token");
if (hasText(topLevel)) {
return topLevel.trim();
}
throw validation("edayun token response has no access token"
+ " (looked for access_token, data.access_token and token)", body);
}
/**
* 过期时刻(<b>估算</b>)。
*
* <p>实测响应<b>没有有效期字段</b>,文档也说 token「目前设计上是永久的,
* 建议留个窗口刷新」。所以这里返回一个估算值,作用只是让 {@code TokenManager}
* 定期重登一次,避免真出问题时卡死。</p>
*
* <p>若将来响应里出现 {@code data.expires_in} 或 {@code data.expiry},
* 优先用真值。</p>
*/
private Instant expiresAtOf(EdayunTokenDtos.TokenResponse parsed) {
Instant now = Instant.now(clock);
EdayunTokenDtos.TokenResponse.TokenData data = parsed.data;
if (data != null && data.expiresIn != null && data.expiresIn > 0) {
return now.plusSeconds(data.expiresIn);
}
if (data != null && hasText(data.expiry)) {
Instant absolute = parseAbsolute(data.expiry.trim());
if (absolute != null) {
return absolute;
}
}
// 文档:token 永久,建议定期刷新。按兜底周期重登一次。
return now.plusSeconds(EdayunConstants.DEFAULT_TOKEN_TTL_SECONDS);
}
/** 绝对时刻:兼容 ISO-8601 与毫秒 / 秒数字。 */
private static Instant parseAbsolute(String raw) {
try {
return Instant.parse(raw);
} catch (RuntimeException ignored) {
// 继续试数字
}
try {
long n = Long.parseLong(raw);
// 10 位按秒、13 位按毫秒
return raw.length() <= 10 ? Instant.ofEpochSecond(n) : Instant.ofEpochMilli(n);
} catch (RuntimeException ignored) {
return null;
}
}
private static ValidationException validation(String message, String body) {
return new ValidationException(WarehouseException.builder()
.message(message)
.operation(OP_FETCH)
.provider(EdayunConstants.ADAPTER_ID)
.rawResponse(truncate(body))
.retryable(false));
}
private static boolean hasText(String v) {
return v != null && !v.trim().isEmpty();
}
/** 响应可能含 token 与密码,异常里只留很短一段。 */
private static String truncate(String body) {
if (body == null) {
return null;
}
return body.length() <= 300 ? body : body.substring(0, 300) + "...";
}
}