Browse Source

fix(lingxing): 令牌接口按官方文档修正出入参

原实现与文档不符,联调时必然失败。

入参:
- Content-Type 由 application/json 改为 multipart/form-data(文档要求,curl 用 --form)
- HttpRequest 新增 contentType 字段,OkHttpTransport 按类型选择 MediaType;
  未指定时保持 JSON,不影响其它请求

出参:
- 先校验业务码 code == "200",失败抛 AuthException 并带 msg(HTTP 层仍返回 200)
- expires_in 按文档为秒,expiresAt 改用注入的 Clock 计算(原来用 Instant.now())
- 删除 data.0.access_token / 顶层 access_token 的猜测性兜底
- 缺 access_token 时抛带上下文的 AuthException,而不是 NullPointerException

测试:
- 新增 LingxingTokenClientTest,覆盖 multipart 构造、成功解析、业务错误码、
  缺 token、HTTP 5xx 五条路径
- token 夹具改为文档示例结构(code 为字符串 "200"),新增 auth_failed 夹具

Co-Authored-By: Claude <noreply@anthropic.com>
feature/supplier-lingxing
chenchuchuan 3 weeks ago
parent
commit
37cc2dbc58
  1. 22
      http/src/main/java/common/ecommerce/http/HttpRequest.java
  2. 22
      http/src/main/java/common/ecommerce/http/OkHttpTransport.java
  3. 2
      lingxing/src/main/java/common/ecommerce/lingxing/LingxingAdapter.java
  4. 96
      lingxing/src/main/java/common/ecommerce/lingxing/LingxingTokenClient.java
  5. 3
      lingxing/src/test/java/common/ecommerce/lingxing/LingxingLiveSmokeTest.java
  6. 95
      lingxing/src/test/java/common/ecommerce/lingxing/LingxingTokenClientTest.java
  7. 5
      lingxing/src/test/resources/fixtures/lingxing/token/auth_failed.json
  8. 4
      lingxing/src/test/resources/fixtures/lingxing/token/success.json

22
http/src/main/java/common/ecommerce/http/HttpRequest.java

@ -14,6 +14,7 @@ public final class HttpRequest { @@ -14,6 +14,7 @@ public final class HttpRequest {
private final String url;
private final Map<String, String> headers;
private final String body;
private final String contentType;
private final String operation;
private HttpRequest(Builder b) {
@ -21,6 +22,7 @@ public final class HttpRequest { @@ -21,6 +22,7 @@ public final class HttpRequest {
this.url = Objects.requireNonNull(b.url, "url");
this.headers = Collections.unmodifiableMap(new LinkedHashMap<String, String>(b.headers));
this.body = b.body;
this.contentType = b.contentType;
this.operation = b.operation;
}
@ -52,13 +54,24 @@ public final class HttpRequest { @@ -52,13 +54,24 @@ public final class HttpRequest {
return body;
}
/**
* 请求体类型,如 {@code application/json}、{@code application/x-www-form-urlencoded}。
*
* <p>为 null 时由传输层按 {@code application/json} 处理(历史行为)。
* 部分平台令牌接口要求 {@code multipart/form-data},见 {@link #contentType()} 的调用方。</p>
*/
public String contentType() {
return contentType;
}
/** 操作名,如 salesOrders.pull / token.refresh。 */
public String operation() {
return operation;
}
public Builder toBuilder() {
return builder().method(method).url(url).headers(headers).body(body).operation(operation);
return builder().method(method).url(url).headers(headers).body(body)
.contentType(contentType).operation(operation);
}
public static final class Builder {
@ -67,6 +80,7 @@ public final class HttpRequest { @@ -67,6 +80,7 @@ public final class HttpRequest {
private String url;
private Map<String, String> headers = new LinkedHashMap<String, String>();
private String body;
private String contentType;
private String operation;
public Builder method(String method) {
@ -98,6 +112,12 @@ public final class HttpRequest { @@ -98,6 +112,12 @@ public final class HttpRequest {
return this;
}
/** 设置请求体类型;不设置时传输层按 JSON 处理。 */
public Builder contentType(String contentType) {
this.contentType = contentType;
return this;
}
public Builder operation(String operation) {
this.operation = operation;
return this;

22
http/src/main/java/common/ecommerce/http/OkHttpTransport.java

@ -38,8 +38,7 @@ public final class OkHttpTransport implements HttpTransport { @@ -38,8 +38,7 @@ public final class OkHttpTransport implements HttpTransport {
String method = request.method().toUpperCase();
okhttp3.RequestBody body = null;
if (request.body() != null) {
body = okhttp3.RequestBody.create(request.body(),
okhttp3.MediaType.parse("application/json; charset=utf-8"));
body = okhttp3.RequestBody.create(request.body(), mediaType(request));
}
if ("POST".equals(method)) {
rb.post(body == null ? okhttp3.RequestBody.create(new byte[0], null) : body);
@ -67,4 +66,23 @@ public final class OkHttpTransport implements HttpTransport { @@ -67,4 +66,23 @@ public final class OkHttpTransport implements HttpTransport {
.retryable(true), e));
}
}
/**
* 请求体类型。未显式指定时按 JSON 处理(历史行为);
* 表单类类型原样使用,不加 charset。
*/
private static okhttp3.MediaType mediaType(HttpRequest request) {
String contentType = request.contentType();
if (contentType == null) {
return okhttp3.MediaType.parse("application/json; charset=utf-8");
}
String lower = contentType.toLowerCase(java.util.Locale.ROOT);
if (lower.startsWith("application/x-www-form-urlencoded")
|| lower.startsWith("multipart/form-data")) {
return okhttp3.MediaType.parse(contentType);
}
return lower.contains("charset")
? okhttp3.MediaType.parse(contentType)
: okhttp3.MediaType.parse(contentType + "; charset=utf-8");
}
}

2
lingxing/src/main/java/common/ecommerce/lingxing/LingxingAdapter.java

@ -71,7 +71,7 @@ public final class LingxingAdapter implements SalesOrderCapable, AggregatorCapab @@ -71,7 +71,7 @@ public final class LingxingAdapter implements SalesOrderCapable, AggregatorCapab
this.secretProvider = secretProvider;
this.clock = clock;
this.mapper = new LingxingOrderMapper(json);
final LingxingTokenClient tokenClient = new LingxingTokenClient(transport, json, baseUrl);
final LingxingTokenClient tokenClient = new LingxingTokenClient(transport, json, baseUrl, clock);
// 领星 access_token 约 2h,提前 10 分钟续期
this.tokenManager = new TokenManager(tokenStore, lockProvider, clock, 600) {
@Override

96
lingxing/src/main/java/common/ecommerce/lingxing/LingxingTokenClient.java

@ -1,5 +1,7 @@ @@ -1,5 +1,7 @@
package common.ecommerce.lingxing;
import common.ecommerce.error.AuthException;
import common.ecommerce.error.ChannelException;
import common.ecommerce.http.HttpRequest;
import common.ecommerce.http.HttpResponse;
import common.ecommerce.http.HttpTransport;
@ -7,6 +9,7 @@ import common.ecommerce.http.JsonCodec; @@ -7,6 +9,7 @@ import common.ecommerce.http.JsonCodec;
import common.ecommerce.http.Responses;
import common.ecommerce.spi.AccessToken;
import java.time.Clock;
import java.time.Instant;
import java.util.LinkedHashMap;
import java.util.Map;
@ -14,54 +17,107 @@ import java.util.Map; @@ -14,54 +17,107 @@ import java.util.Map;
/**
* 领星令牌获取:{@code POST /api/auth-server/oauth/access-token}。
*
* <p>请求体字段名以官方文档为准(appId/appSecret),这里集中在一处便于联调调整。</p>
* <p>按官方文档(2026-10 核对):</p>
* <ul>
* <li>请求头 {@code Content-Type: multipart/form-data}</li>
* <li>表单参数 {@code appId} / {@code appSecret}</li>
* <li>响应 {@code code == "200"} 为成功,{@code data} 含
* {@code access_token} / {@code refresh_token} / {@code expires_in}(秒)</li>
* <li>失败时 HTTP 仍是 200,靠 {@code code} 区分,{@code data} 为 null</li>
* </ul>
*/
public final class LingxingTokenClient {
/** 成功状态码(字符串,文档示例为 "200")。 */
static final String SUCCESS_CODE = "200";
/** 固定 boundary:请求体可预测,便于契约测试断言。 */
private static final String BOUNDARY = "----commonEcommerceLingxingBoundary";
private static final String MULTIPART_CONTENT_TYPE = "multipart/form-data; boundary=" + BOUNDARY;
private final HttpTransport transport;
private final JsonCodec json;
private final String baseUrl;
private final Clock clock;
public LingxingTokenClient(HttpTransport transport, JsonCodec json, String baseUrl) {
public LingxingTokenClient(HttpTransport transport, JsonCodec json, String baseUrl, Clock clock) {
this.transport = transport;
this.json = json;
this.baseUrl = baseUrl;
this.clock = clock;
}
public AccessToken fetch(String appId, String appSecret) {
Map<String, String> body = new LinkedHashMap<String, String>();
body.put("appId", appId);
body.put("appSecret", appSecret);
Map<String, String> form = new LinkedHashMap<String, String>();
form.put("appId", appId);
form.put("appSecret", appSecret);
HttpRequest req = HttpRequest.builder()
.method("POST")
.url(baseUrl + LingxingConstants.PATH_ACCESS_TOKEN)
.header("Content-Type", "application/json")
.body(json.toJson(body))
.contentType(MULTIPART_CONTENT_TYPE)
.body(multipartBody(form))
.operation("token.refresh")
.build();
HttpResponse resp = transport.execute(req);
Responses.throwIfNotSuccess(resp, "token.refresh");
String token = json.stringAt(resp.body(), "data.access_token");
if (token == null) {
// 兼容部分版本的 data 为数组
token = json.stringAt(resp.body(), "data.0.access_token");
String code = json.stringAt(resp.body(), "code");
if (!SUCCESS_CODE.equals(code)) {
throw new AuthException(ChannelException.builder()
.message("lingxing token rejected: code=" + code
+ ", msg=" + json.stringAt(resp.body(), "msg"))
.operation("token.refresh")
.provider(LingxingConstants.ADAPTER_ID)
.platformCode(code)
.rawResponse(resp.body()));
}
String accessToken = json.stringAt(resp.body(), "access_token");
if (accessToken == null) {
accessToken = token;
String token = json.stringAt(resp.body(), "data.access_token");
if (token == null || token.trim().isEmpty()) {
throw new AuthException(ChannelException.builder()
.message("lingxing token response has no data.access_token")
.operation("token.refresh")
.provider(LingxingConstants.ADAPTER_ID)
.rawResponse(resp.body()));
}
String refreshToken = json.stringAt(resp.body(), "data.refresh_token");
String expiresIn = json.stringAt(resp.body(), "data.expires_in");
long seconds = expiresIn == null ? 7199L : Long.parseLong(expiresIn);
return AccessToken.builder()
.value(accessToken)
.refreshToken(refreshToken)
.expiresAt(Instant.now().plusSeconds(seconds))
.value(token)
.refreshToken(json.stringAt(resp.body(), "data.refresh_token"))
.expiresAt(Instant.now(clock).plusSeconds(expiresInSeconds(resp.body())))
.tokenType("Bearer")
.build();
}
/** {@code expires_in} 单位为秒;缺失或非法时按文档示例值兜底。 */
private long expiresInSeconds(String body) {
String raw = json.stringAt(body, "data.expires_in");
if (raw == null || raw.trim().isEmpty()) {
return 7199L;
}
try {
return Long.parseLong(raw.trim());
} catch (NumberFormatException e) {
throw new AuthException(ChannelException.builder()
.message("lingxing token expires_in is not a number: " + raw)
.operation("token.refresh")
.provider(LingxingConstants.ADAPTER_ID)
.rawResponse(body));
}
}
/** multipart/form-data 请求体;字段值不做转义,appId/appSecret 只含安全字符。 */
private static String multipartBody(Map<String, String> form) {
StringBuilder sb = new StringBuilder();
for (Map.Entry<String, String> e : form.entrySet()) {
sb.append("--").append(BOUNDARY).append("\r\n")
.append("Content-Disposition: form-data; name=\"").append(e.getKey()).append("\"\r\n")
.append("\r\n")
.append(e.getValue() == null ? "" : e.getValue()).append("\r\n");
}
sb.append("--").append(BOUNDARY).append("--\r\n");
return sb.toString();
}
}

3
lingxing/src/test/java/common/ecommerce/lingxing/LingxingLiveSmokeTest.java

@ -64,7 +64,8 @@ class LingxingLiveSmokeTest { @@ -64,7 +64,8 @@ class LingxingLiveSmokeTest {
/** 第 1 步:只验证认证。失败说明 appId/appSecret 字段名或环境不对,与订单接口无关。 */
@Test
void tokenCanBeFetched() {
AccessToken token = new LingxingTokenClient(transport, json, BASE_URL).fetch(APP_KEY, APP_SECRET);
AccessToken token = new LingxingTokenClient(transport, json, BASE_URL, Clock.systemUTC())
.fetch(APP_KEY, APP_SECRET);
System.out.println("[token] " + token.fingerprint() + " expiresAt=" + token.expiresAt());
assertNotNull(token.value());
}

95
lingxing/src/test/java/common/ecommerce/lingxing/LingxingTokenClientTest.java

@ -0,0 +1,95 @@ @@ -0,0 +1,95 @@
package common.ecommerce.lingxing;
import common.ecommerce.error.AuthException;
import common.ecommerce.http.HttpRequest;
import common.ecommerce.http.JacksonJsonCodec;
import common.ecommerce.spi.AccessToken;
import common.ecommerce.testkit.FakeTransport;
import common.ecommerce.testkit.Fixtures;
import common.ecommerce.testkit.Responses;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.time.Clock;
import java.time.Instant;
import java.time.ZoneOffset;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* 领星令牌接口契约测试:按官方文档核对出入参。
*/
class LingxingTokenClientTest {
private static final String BASE_URL = LingxingConstants.DEFAULT_BASE_URL;
private static final Clock CLOCK = Clock.fixed(Instant.parse("2026-10-30T00:00:00Z"), ZoneOffset.UTC);
private FakeTransport transport;
private LingxingTokenClient client;
@BeforeEach
void setUp() {
transport = FakeTransport.create();
client = new LingxingTokenClient(transport, new JacksonJsonCodec(), BASE_URL, CLOCK);
}
@Test
void requestUsesMultipartFormWithAppIdAndSecret() {
transport.route(LingxingConstants.PATH_ACCESS_TOKEN, "POST",
r -> Responses.ok(Fixtures.load(getClass(), "lingxing", "token", "success")));
client.fetch("my-app-id", "my-secret");
HttpRequest req = transport.lastRequest();
assertEquals("POST", req.method());
assertTrue(req.url().endsWith(LingxingConstants.PATH_ACCESS_TOKEN), req.url());
assertTrue(req.contentType().startsWith("multipart/form-data"), req.contentType());
assertTrue(req.body().contains("name=\"appId\"\r\n\r\nmy-app-id"), req.body());
assertTrue(req.body().contains("name=\"appSecret\"\r\n\r\nmy-secret"), req.body());
}
@Test
void parsesTokenFromDataObject() {
transport.route(LingxingConstants.PATH_ACCESS_TOKEN, "POST",
r -> Responses.ok(Fixtures.load(getClass(), "lingxing", "token", "success")));
AccessToken token = client.fetch("id", "secret");
assertEquals("lx-access-token-abc", token.value());
assertEquals("lx-refresh-token-xyz", token.refreshToken());
assertEquals("Bearer", token.tokenType());
// expires_in=7199 秒,基于注入时钟计算
assertEquals(Instant.parse("2026-10-30T01:59:59Z"), token.expiresAt());
}
@Test
void businessErrorCodeThrowsAuthException() {
transport.route(LingxingConstants.PATH_ACCESS_TOKEN, "POST",
r -> Responses.ok(Fixtures.load(getClass(), "lingxing", "token", "auth_failed")));
AuthException ex = assertThrows(AuthException.class, () -> client.fetch("id", "bad"));
assertTrue(ex.getMessage().contains("2001001"), ex.getMessage());
assertTrue(ex.getMessage().contains("app not exist"), ex.getMessage());
assertEquals("2001001", ex.platformCode());
}
@Test
void missingTokenThrowsInsteadOfNpe() {
transport.route(LingxingConstants.PATH_ACCESS_TOKEN, "POST",
r -> Responses.ok("{\"code\":\"200\",\"msg\":\"OK\",\"data\":{}}"));
AuthException ex = assertThrows(AuthException.class, () -> client.fetch("id", "secret"));
assertTrue(ex.getMessage().contains("data.access_token"), ex.getMessage());
}
@Test
void httpErrorMapsToException() {
transport.route(LingxingConstants.PATH_ACCESS_TOKEN, "POST",
r -> Responses.status(500, "boom"));
assertThrows(common.ecommerce.error.TransientException.class,
() -> client.fetch("id", "secret"));
}
}

5
lingxing/src/test/resources/fixtures/lingxing/token/auth_failed.json

@ -0,0 +1,5 @@ @@ -0,0 +1,5 @@
{
"code": "2001001",
"msg": "app not exist",
"data": null
}

4
lingxing/src/test/resources/fixtures/lingxing/token/success.json

@ -1,6 +1,6 @@ @@ -1,6 +1,6 @@
{
"code": 0,
"msg": "success",
"code": "200",
"msg": "OK",
"data": {
"access_token": "lx-access-token-abc",
"refresh_token": "lx-refresh-token-xyz",

Loading…
Cancel
Save