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.

199 lines
7.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>待联调确认</b>:文档只给了 {@code code} 的取值(200 / 500 / 503 / 504),
* 没给响应体结构。所以这里同时兼容三种常见形态:</p>
* <ul>
* <li>{@code data.access_token} + {@code data.expires_in}(OAuth 标准)</li>
* <li>{@code data.expiry}(绝对时刻)</li>
* <li>{@code token} 直接放顶层</li>
* </ul>
* <p>都取不到时按 500 处理并带出原始报文(截断)。</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>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) {
throw validation("edayun token response has no code", body);
}
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();
}
/** 三种形态都试一遍;都取不到就失败,不猜。 */
private String tokenOf(EdayunTokenDtos.TokenResponse parsed, String body) {
if (parsed.data != null && hasText(parsed.data.accessToken)) {
return parsed.data.accessToken.trim();
}
// 顶层 token(部分网关会把 data 拍平)
String topLevel = json.stringAt(body, "token");
if (hasText(topLevel)) {
return topLevel.trim();
}
throw validation("edayun token response has no access token"
+ " (looked for data.access_token and token)", body);
}
/**
* 过期时刻。
*
* <p>优先 {@code data.expires_in}(相对秒),其次 {@code data.expiry}(绝对),
* 都没有就按 {@link EdayunConstants#DEFAULT_TOKEN_TTL_SECONDS} 兜底并标注待确认。</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;
}
}
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) + "...";
}
}