第三方开放 API 示例文档
1. 概述
本文档基于《第三方开放 API 设计文档》,提供详细的 Java 实现示例,重点突出 API 验证机制和签名验证流程。通过具体的代码示例和流程图,帮助第三方开发者快速理解和集成 API。
1.1 文档目标
- API 验证示例:提供完整的 API 验证流程和代码实现
- 签名计算示例:详细的签名计算步骤和 Java 代码实现
- 业务流程展示:通过流程图清晰展示 API 调用过程
- 数据流转分析:详细分析签名验证过程中的数据流转
1.2 技术栈
- 开发语言:Java 8+
- 签名算法:HMAC-SHA256
- HTTP 客户端:OkHttp 3.x
- JSON 处理:Jackson 2.x
- 加密工具:Java 内置加密库
2. API 验证业务流程
3. Java 签名计算实现
3.1 签名工具类
package com.example.api.util;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;
/**
* API签名工具类
* 用于计算和验证HMAC-SHA256签名
*/
public class SignatureUtil {
private static final String HMAC_SHA256 = "HmacSHA256";
private static final String CHARSET = "UTF-8";
/**
* 计算HMAC-SHA256签名
*
* @param data 待签名的数据
* @param secret 签名密钥
* @return 十六进制签名字符串
* @throws Exception 签名计算异常
*/
public static String calculateSignature(String data, String secret) throws Exception {
try {
Mac mac = Mac.getInstance(HMAC_SHA256);
SecretKeySpec secretKeySpec = new SecretKeySpec(
secret.getBytes(StandardCharsets.UTF_8), HMAC_SHA256);
mac.init(secretKeySpec);
byte[] signatureBytes = mac.doFinal(data.getBytes(StandardCharsets.UTF_8));
return bytesToHex(signatureBytes).toLowerCase();
} catch (NoSuchAlgorithmException | InvalidKeyException e) {
throw new Exception("签名计算失败", e);
}
}
/**
* 构造签名字符串
* 格式:{HTTP方法}\n{URI路径}\n{请求体}\n{时间戳}\n{随机数}\n{API密钥}
*
* @param method HTTP方法
* @param uri URI路径
* @param body 请求体
* @param timestamp 时间戳
* @param nonce 随机数
* @param apiKey API密钥
* @return 构造的签名字符串
*/
public static String buildSignatureString(String method, String uri, String body,
String timestamp, String nonce, String apiKey) {
StringBuilder sb = new StringBuilder();
sb.append(method).append("\n");
sb.append(uri).append("\n");
sb.append(body != null ? body : "").append("\n");
sb.append(timestamp).append("\n");
sb.append(nonce).append("\n");
sb.append(apiKey);
return sb.toString();
}
/**
* 验证签名
*
* @param expectedSignature 期望的签名
* @param actualSignature 实际的签名
* @return 签名是否匹配
*/
public static boolean verifySignature(String expectedSignature, String actualSignature) {
if (expectedSignature == null || actualSignature == null) {
return false;
}
return expectedSignature.equals(actualSignature);
}
/**
* 字节数组转十六进制字符串
*/
private static String bytesToHex(byte[] bytes) {
StringBuilder result = new StringBuilder();
for (byte b : bytes) {
result.append(String.format("%02x", b));
}
return result.toString();
}
}
3.2 API 客户端实现
package com.example.api.client;
import com.example.api.util.SignatureUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import okhttp3.*;
import java.io.IOException;
import java.time.Instant;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
/**
* 第三方API客户端
* 封装API调用和签名验证逻辑
*/
public class ApiClient {
private final String baseUrl;
private final String apiKey;
private final String secret;
private final OkHttpClient httpClient;
private final ObjectMapper objectMapper;
public ApiClient(String baseUrl, String apiKey, String secret) {
this.baseUrl = baseUrl;
this.apiKey = apiKey;
this.secret = secret;
this.objectMapper = new ObjectMapper();
this.httpClient = new OkHttpClient.Builder()
.connectTimeout(30, TimeUnit.SECONDS)
.readTimeout(60, TimeUnit.SECONDS)
.writeTimeout(60, TimeUnit.SECONDS)
.build();
}
/**
* 发送GET请求
*/
public ApiResponse get(String path) throws Exception {
return sendRequest("GET", path, null);
}
/**
* 发送POST请求
*/
public ApiResponse post(String path, Object requestBody) throws Exception {
String jsonBody = requestBody != null ? objectMapper.writeValueAsString(requestBody) : null;
return sendRequest("POST", path, jsonBody);
}
/**
* 发送PUT请求
*/
public ApiResponse put(String path, Object requestBody) throws Exception {
String jsonBody = requestBody != null ? objectMapper.writeValueAsString(requestBody) : null;
return sendRequest("PUT", path, jsonBody);
}
/**
* 发送DELETE请求
*/
public ApiResponse delete(String path) throws Exception {
return sendRequest("DELETE", path, null);
}
/**
* 发送API请求的核心方法
*/
private ApiResponse sendRequest(String method, String path, String body) throws Exception {
// 1. 准备请求参数
String timestamp = String.valueOf(Instant.now().getEpochSecond());
String nonce = generateNonce();
String fullPath = path.startsWith("/") ? path : "/" + path;
// 2. 构造签名字符串
String signatureString = SignatureUtil.buildSignatureString(
method, fullPath, body, timestamp, nonce, apiKey);
// 3. 计算签名
String signature = SignatureUtil.calculateSignature(signatureString, secret);
// 4. 构造HTTP请求
Request.Builder requestBuilder = new Request.Builder()
.url(baseUrl + fullPath)
.addHeader("X-API-Key", apiKey)
.addHeader("X-Signature", signature)
.addHeader("X-Timestamp", timestamp)
.addHeader("X-Nonce", nonce)
.addHeader("Content-Type", "application/json")
.addHeader("X-Request-ID", UUID.randomUUID().toString());
// 5. 设置请求体
if (body != null && !body.isEmpty()) {
requestBuilder.method(method, RequestBody.create(
MediaType.parse("application/json"), body));
} else {
requestBuilder.method(method, null);
}
Request request = requestBuilder.build();
// 6. 发送请求
try (Response response = httpClient.newCall(request).execute()) {
String responseBody = response.body() != null ? response.body().string() : "";
return ApiResponse.builder()
.code(response.code())
.message(response.message())
.body(responseBody)
.success(response.isSuccessful())
.build();
} catch (IOException e) {
throw new Exception("API请求失败", e);
}
}
/**
* 生成32位随机字符串作为Nonce
*/
private String generateNonce() {
return UUID.randomUUID().toString().replace("-", "");
}
}
3.3 API 响应封装类
package com.example.api.client;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Builder;
import lombok.Data;
/**
* API响应封装类
*/
@Data
@Builder
public class ApiResponse {
@JsonProperty("code")
private int code;
@JsonProperty("message")
private String message;
@JsonProperty("data")
private Object data;
@JsonProperty("timestamp")
private String timestamp;
@JsonProperty("requestId")
private String requestId;
private String body;
private boolean success;
/**
* 判断请求是否成功
*/
public boolean isSuccess() {
return success && code >= 200 && code < 300;
}
/**
* 获取错误信息
*/
public String getErrorMessage() {
if (isSuccess()) {
return null;
}
return String.format("API调用失败: %d - %s", code, message);
}
}
4. API 验证服务端实现
4.1 签名验证拦截器
package com.example.api.interceptor;
import com.example.api.util.SignatureUtil;
import com.example.api.service.ApiKeyService;
import com.example.api.service.NonceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.Instant;
/**
* API签名验证拦截器
* 在请求处理前进行签名验证
*/
@Component
public class SignatureValidationInterceptor implements HandlerInterceptor {
@Autowired
private ApiKeyService apiKeyService;
@Autowired
private NonceService nonceService;
private static final int TIMESTAMP_TOLERANCE = 300; // 5分钟
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
Object handler) throws Exception {
try {
// 1. 提取请求头参数
String apiKey = request.getHeader("X-API-Key");
String signature = request.getHeader("X-Signature");
String timestamp = request.getHeader("X-Timestamp");
String nonce = request.getHeader("X-Nonce");
// 2. 基础参数验证
if (!validateBasicParams(apiKey, signature, timestamp, nonce)) {
sendErrorResponse(response, 400, "缺少必需的请求头参数");
return false;
}
// 3. API Key验证
if (!apiKeyService.isValidApiKey(apiKey)) {
sendErrorResponse(response, 401, "API Key无效或已过期");
return false;
}
// 4. 时间戳验证
if (!validateTimestamp(timestamp)) {
sendErrorResponse(response, 401, "请求时间戳超时");
return false;
}
// 5. Nonce防重放检查
if (!nonceService.checkAndStoreNonce(nonce)) {
sendErrorResponse(response, 401, "检测到重放攻击");
return false;
}
// 6. 签名验证
if (!validateSignature(request, apiKey, signature, timestamp, nonce)) {
sendErrorResponse(response, 401, "签名验证失败");
return false;
}
// 7. 权限验证
if (!apiKeyService.hasPermission(apiKey, request.getRequestURI(), request.getMethod())) {
sendErrorResponse(response, 403, "权限不足");
return false;
}
return true;
} catch (Exception e) {
sendErrorResponse(response, 500, "服务器内部错误");
return false;
}
}
/**
* 基础参数验证
*/
private boolean validateBasicParams(String apiKey, String signature,
String timestamp, String nonce) {
return apiKey != null && !apiKey.isEmpty() &&
signature != null && !signature.isEmpty() &&
timestamp != null && !timestamp.isEmpty() &&
nonce != null && !nonce.isEmpty();
}
/**
* 时间戳验证
*/
private boolean validateTimestamp(String timestamp) {
try {
long requestTime = Long.parseLong(timestamp);
long currentTime = Instant.now().getEpochSecond();
return Math.abs(currentTime - requestTime) <= TIMESTAMP_TOLERANCE;
} catch (NumberFormatException e) {
return false;
}
}
/**
* 签名验证
*/
private boolean validateSignature(HttpServletRequest request, String apiKey,
String signature, String timestamp, String nonce) {
try {
// 获取请求体
String body = getRequestBody(request);
// 构造签名字符串
String signatureString = SignatureUtil.buildSignatureString(
request.getMethod(),
request.getRequestURI(),
body,
timestamp,
nonce,
apiKey
);
// 获取Secret
String secret = apiKeyService.getSecretByApiKey(apiKey);
if (secret == null) {
return false;
}
// 重新计算签名
String calculatedSignature = SignatureUtil.calculateSignature(signatureString, secret);
// 对比签名
return SignatureUtil.verifySignature(calculatedSignature, signature);
} catch (Exception e) {
return false;
}
}
/**
* 获取请求体内容
*/
private String getRequestBody(HttpServletRequest request) {
// 这里需要从request中读取请求体
// 实际实现中可能需要使用HttpServletRequestWrapper来缓存请求体
return "";
}
/**
* 发送错误响应
*/
private void sendErrorResponse(HttpServletResponse response, int code, String message)
throws Exception {
response.setStatus(code);
response.setContentType("application/json;charset=UTF-8");
String errorResponse = String.format(
"{\"code\":%d,\"message\":\"%s\",\"timestamp\":\"%s\"}",
code, message, Instant.now().toString()
);
response.getWriter().write(errorResponse);
}
}
4.2 API Key 服务
package com.example.api.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import java.util.concurrent.TimeUnit;
/**
* API Key管理服务
*/
@Service
public class ApiKeyService {
@Autowired
private RedisTemplate<String, String> redisTemplate;
private static final String API_KEY_PREFIX = "api_key:";
private static final String API_KEY_CACHE_TTL = "300"; // 5分钟
/**
* 验证API Key是否有效
*/
public boolean isValidApiKey(String apiKey) {
String cacheKey = API_KEY_PREFIX + apiKey;
String cached = redisTemplate.opsForValue().get(cacheKey);
if (cached != null) {
return "valid".equals(cached);
}
// 从数据库查询API Key
boolean isValid = queryApiKeyFromDatabase(apiKey);
// 缓存结果
redisTemplate.opsForValue().set(cacheKey, isValid ? "valid" : "invalid",
Long.parseLong(API_KEY_CACHE_TTL), TimeUnit.SECONDS);
return isValid;
}
/**
* 获取API Key对应的Secret
*/
public String getSecretByApiKey(String apiKey) {
// 从数据库或缓存中获取Secret
return querySecretFromDatabase(apiKey);
}
/**
* 检查API Key是否有访问指定资源的权限
*/
public boolean hasPermission(String apiKey, String resource, String method) {
// 实现权限检查逻辑
return true; // 简化实现
}
/**
* 从数据库查询API Key
*/
private boolean queryApiKeyFromDatabase(String apiKey) {
// 实际实现中查询数据库
return true; // 简化实现
}
/**
* 从数据库查询Secret
*/
private String querySecretFromDatabase(String apiKey) {
// 实际实现中查询数据库
return "your-secret-key"; // 简化实现
}
}
4.3 Nonce 防重放服务
package com.example.api.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import java.util.concurrent.TimeUnit;
/**
* Nonce防重放服务
*/
@Service
public class NonceService {
@Autowired
private RedisTemplate<String, String> redisTemplate;
private static final String NONCE_PREFIX = "nonce:";
private static final int NONCE_TTL = 300; // 5分钟
/**
* 检查并存储Nonce
* @param nonce 随机数
* @return true表示Nonce未被使用,false表示已被使用
*/
public boolean checkAndStoreNonce(String nonce) {
String cacheKey = NONCE_PREFIX + nonce;
// 检查Nonce是否已存在
Boolean exists = redisTemplate.hasKey(cacheKey);
if (Boolean.TRUE.equals(exists)) {
return false; // Nonce已被使用
}
// 存储Nonce,设置过期时间
redisTemplate.opsForValue().set(cacheKey, "used", NONCE_TTL, TimeUnit.SECONDS);
return true;
}
/**
* 清理过期的Nonce
*/
public void cleanExpiredNonces() {
// Redis会自动清理过期的key,这里可以添加额外的清理逻辑
}
}
5. 使用示例
5.1 客户端使用示例
package com.example.api.example;
import com.example.api.client.ApiClient;
import com.example.api.client.ApiResponse;
import com.fasterxml.jackson.databind.ObjectMapper;
/**
* API客户端使用示例
*/
public class ApiClientExample {
public static void main(String[] args) {
// 初始化API客户端
ApiClient client = new ApiClient(
"https://api.example.com",
"a1b2c3d4e5f6789012345678901234567890abcd",
"your-secret-key"
);
try {
// 示例1:查询用户信息
System.out.println("=== 查询用户信息 ===");
ApiResponse userResponse = client.get("/v1/users/123");
System.out.println("响应码: " + userResponse.getCode());
System.out.println("响应内容: " + userResponse.getBody());
// 示例2:创建订单
System.out.println("\n=== 创建订单 ===");
OrderRequest orderRequest = new OrderRequest();
orderRequest.setUserId("123");
orderRequest.setProductId("456");
orderRequest.setQuantity(2);
orderRequest.setPrice(99.99);
ApiResponse orderResponse = client.post("/v1/orders", orderRequest);
System.out.println("响应码: " + orderResponse.getCode());
System.out.println("响应内容: " + orderResponse.getBody());
// 示例3:更新订单状态
System.out.println("\n=== 更新订单状态 ===");
OrderUpdateRequest updateRequest = new OrderUpdateRequest();
updateRequest.setStatus("shipped");
ApiResponse updateResponse = client.put("/v1/orders/789", updateRequest);
System.out.println("响应码: " + updateResponse.getCode());
System.out.println("响应内容: " + updateResponse.getBody());
} catch (Exception e) {
System.err.println("API调用失败: " + e.getMessage());
e.printStackTrace();
}
}
// 订单请求类
static class OrderRequest {
private String userId;
private String productId;
private int quantity;
private double price;
// getter和setter方法
public String getUserId() { return userId; }
public void setUserId(String userId) { this.userId = userId; }
public String getProductId() { return productId; }
public void setProductId(String productId) { this.productId = productId; }
public int getQuantity() { return quantity; }
public void setQuantity(int quantity) { this.quantity = quantity; }
public double getPrice() { return price; }
public void setPrice(double price) { this.price = price; }
}
// 订单更新请求类
static class OrderUpdateRequest {
private String status;
public String getStatus() { return status; }
public void setStatus(String status) { this.status = status; }
}
}
5.2 签名计算详细示例
package com.example.api.example;
import com.example.api.util.SignatureUtil;
/**
* 签名计算详细示例
*/
public class SignatureExample {
public static void main(String[] args) {
try {
// 示例参数
String method = "POST";
String uri = "/v1/users";
String body = "{\"name\":\"张三\",\"email\":\"zhangsan@example.com\"}";
String timestamp = "1640995200";
String nonce = "abc123def456ghi789jkl012mno345pqr";
String apiKey = "a1b2c3d4e5f6789012345678901234567890abcd";
String secret = "your-secret-key";
System.out.println("=== 签名计算示例 ===");
System.out.println("HTTP方法: " + method);
System.out.println("URI路径: " + uri);
System.out.println("请求体: " + body);
System.out.println("时间戳: " + timestamp);
System.out.println("随机数: " + nonce);
System.out.println("API Key: " + apiKey);
System.out.println("Secret: " + secret);
// 构造签名字符串
String signatureString = SignatureUtil.buildSignatureString(
method, uri, body, timestamp, nonce, apiKey);
System.out.println("\n=== 构造的签名字符串 ===");
System.out.println(signatureString);
// 计算签名
String signature = SignatureUtil.calculateSignature(signatureString, secret);
System.out.println("\n=== 计算结果 ===");
System.out.println("HMAC-SHA256签名: " + signature);
// 验证签名
boolean isValid = SignatureUtil.verifySignature(signature, signature);
System.out.println("签名验证结果: " + (isValid ? "通过" : "失败"));
} catch (Exception e) {
System.err.println("签名计算失败: " + e.getMessage());
e.printStackTrace();
}
}
}
6. 错误处理示例
6.1 常见错误场景
package com.example.api.example;
import com.example.api.client.ApiClient;
import com.example.api.client.ApiResponse;
/**
* 错误处理示例
*/
public class ErrorHandlingExample {
public static void main(String[] args) {
ApiClient client = new ApiClient(
"https://api.example.com",
"invalid-api-key", // 故意使用无效的API Key
"your-secret-key"
);
try {
ApiResponse response = client.get("/v1/users/123");
if (response.isSuccess()) {
System.out.println("请求成功: " + response.getBody());
} else {
System.out.println("请求失败:");
System.out.println("错误码: " + response.getCode());
System.out.println("错误信息: " + response.getMessage());
System.out.println("详细错误: " + response.getErrorMessage());
}
} catch (Exception e) {
System.err.println("API调用异常: " + e.getMessage());
}
}
}
7. 测试和调试
7.1 单元测试示例
package com.example.api.test;
import com.example.api.util.SignatureUtil;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
/**
* 签名工具类单元测试
*/
public class SignatureUtilTest {
@Test
public void testCalculateSignature() throws Exception {
String data = "test data";
String secret = "test secret";
String signature = SignatureUtil.calculateSignature(data, secret);
assertNotNull(signature);
assertEquals(64, signature.length()); // HMAC-SHA256输出64个十六进制字符
}
@Test
public void testBuildSignatureString() {
String method = "GET";
String uri = "/v1/users";
String body = "";
String timestamp = "1640995200";
String nonce = "test-nonce";
String apiKey = "test-api-key";
String signatureString = SignatureUtil.buildSignatureString(
method, uri, body, timestamp, nonce, apiKey);
String expected = "GET\n/v1/users\n\n1640995200\ntest-nonce\ntest-api-key";
assertEquals(expected, signatureString);
}
@Test
public void testVerifySignature() throws Exception {
String data = "test data";
String secret = "test secret";
String signature1 = SignatureUtil.calculateSignature(data, secret);
String signature2 = SignatureUtil.calculateSignature(data, secret);
assertTrue(SignatureUtil.verifySignature(signature1, signature2));
String wrongSignature = "wrong signature";
assertFalse(SignatureUtil.verifySignature(signature1, wrongSignature));
}
}
8. 最佳实践
8.1 安全建议
密钥管理:
- 使用环境变量或配置文件存储 API Key 和 Secret
- 定期轮换密钥
- 不要在代码中硬编码密钥
时间同步:
- 确保客户端和服务器时间同步
- 使用 NTP 服务同步时间
错误处理:
- 实现完善的错误处理机制
- 记录详细的错误日志
- 不要在生产环境中暴露敏感信息
8.2 性能优化
连接池:
- 使用 HTTP 连接池提高性能
- 合理设置连接超时时间
缓存策略:
- 对 API Key 验证结果进行缓存
- 合理设置缓存过期时间
重试机制:
- 实现指数退避重试机制
- 区分可重试和不可重试的错误
9. 总结
本文档提供了完整的第三方 API 集成示例,重点突出了:
- API 验证流程:详细的验证步骤和实现代码
- 签名计算:完整的 HMAC-SHA256 签名计算实现
- 业务流程:清晰的业务流程图和数据流转图
- 代码示例:可直接使用的 Java 代码实现
- 错误处理:完善的错误处理和测试示例
通过遵循本文档的示例和最佳实践,第三方开发者可以快速、安全地集成 API 服务。
