DukeDuke
主页
项目文档
技术文档
  • 单机版
  • 微服务
  • 代办项目
  • 优鲜项目
项目管理
关于我们
主页
项目文档
技术文档
  • 单机版
  • 微服务
  • 代办项目
  • 优鲜项目
项目管理
关于我们
  • 技术文档

    • 网络原理

      • 交换机
      • 路由器
      • TCP/IP协议
      • HTTP 与 HTTPS
    • 软件架构

      • 什么是软件架构
      • 分层架构
      • 微服务架构
      • 事件驱动架构
      • 领域驱动设计(DDD)
      • 架构图
      • 高并发系统
    • Vue3

      • Vue3简介
      • Vue3响应式系统
      • Vue3组合式API
      • Vue3生命周期
      • Vue3模板语法
      • Vue3组件系统
      • Vue3 路由系统
      • Vue3 状态管理
      • Vue3 性能优化
      • Vue3 TypeScript 支持
      • Vue3 项目实战
      • VUE 面试题大全
      • Node.js 安装
    • JAVA

      • JVM

        • 认识JVM
        • JVM类加载器
        • 运行时数据区
        • 执行引擎
        • 本地方法接口
        • 本地方法库
        • JVM垃圾回收
        • JVM性能监控
        • JVM调优
      • 设计模式
        • 单例模式
        • 工厂模式
        • 策略模式
        • 适配器模式
        • 建造者模式
        • 原型模式
        • 装饰器模式
        • 代理模式
        • 外观模式
        • 享元模式
        • 组合模式
        • 桥接模式
      • Java多线程

        • Java 线程基础详解
        • Java 线程池详解
        • Java ThreadLocal 详解
        • Java volatile 详解
        • Java 线程间通信详解
        • Java 线程安全详解
        • Java 线程调度详解
        • Java 线程优先级详解

        • Java 线程中断详解
        • Java 线程死锁详解
      • Java反射
      • Java 面试题

        • Java 基础概念面试题
        • Java 面向对象编程面试题
        • Java 集合框架面试题
        • Java 多线程与并发面试题
        • JVM 与内存管理面试题
        • Java I/O 与 NIO 面试题
        • Java 异常处理面试题
        • Java 反射与注解面试题
        • Java Spring 框架面试题
        • Java 数据库与 JDBC 面试题
        • Java 性能优化面试题
        • Java 实际项目经验面试题
        • Java 高级特性面试题
        • Java 面试准备建议
    • Python

      • Python简介
      • Python安装
      • Python hello world
      • Python基础语法
      • Python数据类型
      • Python数字
      • Python字符串
      • Python列表
      • Python元组
      • Python字典
      • Python日期时间
      • Python文件操作
      • Python异常处理
      • Python函数
      • Python类
      • Python模块
      • Python包
      • Python多线程
      • Python面向对象
      • Python爬虫
      • Django web框架
      • Python 面试题

        • Python 面试题导航
        • Python 基础概念
        • Python 面向对象编程
        • Python 数据结构
        • Python 高级特性
        • Python 框架
        • Python 性能优化
        • Python 项目经验
    • Spring

      • Spring
      • Springboot
      • Spring Security 安全框架
      • SpringBoot 中的事件详解
      • SpringBoot 中的定时任务详解
      • SpringBoot 自动装配原理与源码解释
    • Mybatis

      • Mybatis
      • Mybatis-Plus
    • 数据库

      • Redis

        • Redis简介
        • Redis(单机)安装
        • Redis配置
        • Redis数据结构
        • RDB、AOF 和混合持久化机制
        • Redis内存管理
        • Redis缓存一致性
        • Redis缓存穿透
        • Redis缓存击穿
        • Redis缓存雪崩
        • Redis Lua脚本
        • Redis主从复制
        • Redis哨兵模式
        • Redis集群
        • Redis数据分片
        • Redis CPU使用率过高
        • Redis面试题
      • MySQL

        • MySQL简介
        • MySQL安装
        • MySQL配置
        • MYSQL日常维护
        • MYSQL优化-慢查询
        • MYSQL优化-索引
        • MYSQL数据库设计规范
    • 消息队列

      • RocketMQ
      • Kafka
      • RabbitMQ
      • 消息队列面试题
    • 微服务

      • SpringCloud 微服务
      • Eureka 注册中心
      • Nacos 注册中心
      • Gateway 网关
      • Feign 服务调用
      • Sentinel 限流 与 熔断
      • Seata 分布式事务
      • CAP 理论
      • Redis 分布式锁
      • 高并发系统设计
    • ELK日志分析系统

      • Elasticsearch 搜索引擎
      • Logstash 数据处理
      • Kibana 可视化
      • ELK 实战
    • 开放API

      • 开放API设计
      • 开放API示例项目
    • 人工智能

      • 人工智能简介
      • 机器学习

      • 深度学习

      • 自然语言处理

      • 计算机视觉

        • CUDA与cuDNN详细安装
        • Conda 安装
        • Pytorch 深度学习框架
        • yolo 目标检测
        • TensorRT 深度学习推理优化引擎
        • TensorFlow 机器学习
        • CVAT 图像标注
        • Windows 下安装 CUDA、cuDNN、TensorRT、TensorRT-YOLO 环境
        • Windows10+CUDA+cuDNN+TensorRT+TensorRT-YOLO 部署高性能YOLO11推理
    • 大数据

      • 大数据简介
      • Hadoop 数据存储
      • Flume 数据采集
      • Sqoop 数据导入导出
      • Hive 数据仓库
      • Spark 数据处理
      • Flink 数据处理
      • Kafka 数据采集
      • HBase 数据存储
      • Elasticsearch 搜索引擎
    • 图像处理

      • 图像处理简介
      • 医学图像web呈现
      • 医学图像处理
      • 切片细胞分离问题
    • 服务器&运维

      • Linux 系统

        • Linux 系统管理
        • Linux 网络管理
        • Linux 文件管理
        • Linux 命令大全
      • Nginx Web 服务器

        • Nginx 安装 与 配置
        • Nginx 负载均衡
        • Nginx SSL证书配置
        • Nginx Keepalived 高可用
      • Docker 容器

        • Docker 简介
        • Docker 安装与配置
        • Docker 命令
        • Docker 部署 Nginx
        • Docker 部署 MySQL
        • Docker 部署 Redis
      • 服务器

        • 塔式服务器
        • 机架式服务器
        • 刀片服务器
      • Git 版本控制
      • Jenkins 持续集成
      • Jmeter 性能测试
      • Let's Encrypt 免费SSL证书
    • 简历

      • 项目经理简历
      • 开发工程师简历

第三方开放 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 安全建议

  1. 密钥管理:

    • 使用环境变量或配置文件存储 API Key 和 Secret
    • 定期轮换密钥
    • 不要在代码中硬编码密钥
  2. 时间同步:

    • 确保客户端和服务器时间同步
    • 使用 NTP 服务同步时间
  3. 错误处理:

    • 实现完善的错误处理机制
    • 记录详细的错误日志
    • 不要在生产环境中暴露敏感信息

8.2 性能优化

  1. 连接池:

    • 使用 HTTP 连接池提高性能
    • 合理设置连接超时时间
  2. 缓存策略:

    • 对 API Key 验证结果进行缓存
    • 合理设置缓存过期时间
  3. 重试机制:

    • 实现指数退避重试机制
    • 区分可重试和不可重试的错误

9. 总结

本文档提供了完整的第三方 API 集成示例,重点突出了:

  1. API 验证流程:详细的验证步骤和实现代码
  2. 签名计算:完整的 HMAC-SHA256 签名计算实现
  3. 业务流程:清晰的业务流程图和数据流转图
  4. 代码示例:可直接使用的 Java 代码实现
  5. 错误处理:完善的错误处理和测试示例

通过遵循本文档的示例和最佳实践,第三方开发者可以快速、安全地集成 API 服务。

最近更新:: 2025/9/5 10:30
Contributors: Duke
Prev
开放API设计