正在加载页面,请稍候…

公开文档

签名鉴权

开放平台接口通过访问凭证鉴权。先用 AppId / AppSecret 获取 accessToken ,再在请求头中携带 O-Access-Token: {accessToken} 。

获取密钥

在控制台「应用管理 → 密钥」创建应用后获取 AppId 与 AppSecret ,请妥善保管,勿写入前端公开代码。

凭证有效期

accessToken 有过期时间。过期后需重新获取;建议在服务端缓存凭证,临近过期时再刷新。

请求约定

业务接口统一使用 Content-Type: application/json ,并将凭证放在 O-Access-Token Header 中。

鉴权流程

  1. 换取凭证 :调用 GET /ry/access/createAccessToken ,传入 appid 、 appSecret 。
  2. 保存 token :从响应中读取 accessToken 与 expirationDate ,缓存在服务端。
  3. 调用业务接口 :在 Header 中设置 O-Access-Token: {accessToken} ,按接口文档传参发起请求。

可直接复制到项目中的鉴权工具封装,包含获取凭证与带鉴权发起请求。

Java · 工具类

package org.jeecg.common.util.security;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Base64;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

public final class OpenApiSignUtil {

    private static final String HMAC_ALGORITHM = "HmacSHA256";
    private static final String SIGN_VERSION = "WEWIN-HMAC-SHA256";

    private OpenApiSignUtil() {
    }

    /**
     * 根据appsecret和当前AccessToken派生独立签名密钥。
     *
     * 返回Base64URL字符串,方便服务端存入Redis。
     */
    public static String deriveSigningKey(
            String appsecret,
            String accessToken) {

        byte[] key = appsecret.getBytes(StandardCharsets.UTF_8);

        String source = "wewin-openapi-sign-v1
"
                + accessToken;

        return base64Url(
                hmacSha256(
                        key,
                        source.getBytes(StandardCharsets.UTF_8)
                )
        );
    }

    /**
     * 提供给第三方客户端的签名方法。
     */
    public static String generateSignature(
            String appsecret,
            String appid,
            String accessToken,
            String httpMethod,
            String requestPath,
            Map<String, List<String>> queryParams,
            String contentType,
            long timestamp,
            String nonce,
            byte[] requestBody) {

        String signingKey = deriveSigningKey(
                appsecret,
                accessToken
        );

        return generateSignatureByKey(
                signingKey,
                appid,
                accessToken,
                httpMethod,
                requestPath,
                queryParams,
                contentType,
                timestamp,
                nonce,
                requestBody
        );
    }

    /**
     * 服务端根据Redis中的派生密钥计算签名。
     */
    public static String generateSignatureByKey(
            String signingKey,
            String appid,
            String accessToken,
            String httpMethod,
            String requestPath,
            Map<String, List<String>> queryParams,
            String contentType,
            long timestamp,
            String nonce,
            byte[] requestBody) {

        byte[] key = Base64.getUrlDecoder()
                .decode(signingKey);

        String canonicalRequest = buildCanonicalRequest(
                appid,
                accessToken,
                httpMethod,
                requestPath,
                queryParams,
                contentType,
                timestamp,
                nonce,
                requestBody
        );

        return base64Url(
                hmacSha256(
                        key,
                        canonicalRequest.getBytes(
                                StandardCharsets.UTF_8
                        )
                )
        );
    }

    /**
     * 使用恒定时间比较签名,降低时序攻击风险。
     */
    public static boolean verifySignature(
            String signingKey,
            String suppliedSignature,
            String appid,
            String accessToken,
            String httpMethod,
            String requestPath,
            Map<String, List<String>> queryParams,
            String contentType,
            long timestamp,
            String nonce,
            byte[] requestBody) {

        if (suppliedSignature == null
                || suppliedSignature.isEmpty()) {
            return false;
        }

        try {
            String expectedSignature =
                    generateSignatureByKey(
                            signingKey,
                            appid,
                            accessToken,
                            httpMethod,
                            requestPath,
                            queryParams,
                            contentType,
                            timestamp,
                            nonce,
                            requestBody
                    );

            byte[] expected = Base64.getUrlDecoder()
                    .decode(expectedSignature);

            byte[] supplied = Base64.getUrlDecoder()
                    .decode(suppliedSignature);

            return MessageDigest.isEqual(
                    expected,
                    supplied
            );

        } catch (Exception e) {
            return false;
        }
    }

    private static String buildCanonicalRequest(
            String appid,
            String accessToken,
            String httpMethod,
            String requestPath,
            Map<String, List<String>> queryParams,
            String contentType,
            long timestamp,
            String nonce,
            byte[] requestBody) {

        String canonicalQuery =
                buildCanonicalQuery(queryParams);

        String normalizedContentType =
                normalizeContentType(contentType);

        byte[] body = requestBody == null
                ? new byte[0]
                : requestBody;

        return SIGN_VERSION + "
"
                + nullToEmpty(appid) + "
"
                + sha256Hex(accessToken) + "
"
                + timestamp + "
"
                + nullToEmpty(nonce) + "
"
                + nullToEmpty(httpMethod).toUpperCase() + "
"
                + nullToEmpty(requestPath) + "
"
                + canonicalQuery + "
"
                + normalizedContentType + "
"
                + sha256Hex(body);
    }

    private static String buildCanonicalQuery(
            Map<String, List<String>> queryParams) {

        if (queryParams == null || queryParams.isEmpty()) {
            return "";
        }

        Map<String, List<String>> sorted =
                new TreeMap<>(queryParams);

        List<String> result = new ArrayList<>();

        for (Map.Entry<String, List<String>> entry
                : sorted.entrySet()) {

            List<String> values =
                    entry.getValue() == null
                            || entry.getValue().isEmpty()
                            ? Collections.singletonList("")
                            : new ArrayList<>(entry.getValue());

            Collections.sort(values);

            for (String value : values) {
                result.add(
                        urlEncode(entry.getKey())
                                + "="
                                + urlEncode(value)
                );
            }
        }

        return String.join("&", result);
    }

    private static String normalizeContentType(
            String contentType) {

        if (contentType == null || contentType.isEmpty()) {
            return "";
        }

        int index = contentType.indexOf(';');

        String result = index >= 0
                ? contentType.substring(0, index)
                : contentType;

        return result.trim().toLowerCase();
    }

    private static byte[] hmacSha256(
            byte[] key,
            byte[] content) {

        try {
            Mac mac = Mac.getInstance(HMAC_ALGORITHM);
            mac.init(
                    new SecretKeySpec(
                            key,
                            HMAC_ALGORITHM
                    )
            );

            return mac.doFinal(content);

        } catch (Exception e) {
            throw new IllegalStateException(
                    "HMAC-SHA256计算失败",
                    e
            );
        }
    }

    public static String sha256Hex(String value) {
        return sha256Hex(
                nullToEmpty(value).getBytes(
                        StandardCharsets.UTF_8
                )
        );
    }

    public static String sha256Hex(byte[] value) {
        try {
            MessageDigest digest =
                    MessageDigest.getInstance("SHA-256");

            byte[] result = digest.digest(value);

            return java.util.HexFormat.of()
                    .formatHex(result);

        } catch (NoSuchAlgorithmException e) {
            throw new IllegalStateException(
                    "当前JDK不支持SHA-256",
                    e
            );
        }
    }

    private static String base64Url(byte[] value) {
        return Base64.getUrlEncoder()
                .withoutPadding()
                .encodeToString(value);
    }

    private static String urlEncode(String value) {
        return URLEncoder.encode(
                        nullToEmpty(value),
                        StandardCharsets.UTF_8
                )
                .replace("+", "%20")
                .replace("*", "%2A")
                .replace("%7E", "~");
    }

    private static String nullToEmpty(String value) {
        return value == null ? "" : value;
    }
}
        

完整调用链路示例:先取 token,再请求业务接口。

Java · 示例
// 客户端生成签名
long timestamp = Instant.now().getEpochSecond();

String nonce = UUID.randomUUID()
        .toString()
        .replace("-", "");

byte[] body = JSON.toJSONString(requestData)
        .getBytes(StandardCharsets.UTF_8);

String signature =
        OpenApiSignUtil.generateSignature(
                appsecret,
                appid,
                accessToken,
                "POST",
                "/ry/open/erp/molist",
                queryParams,
                "application/json",
                timestamp,
                nonce,
                body
        );

// 设置请求头
headers.set("O-App-Id", appid);
headers.set("O-Access-Token", accessToken);
headers.set("O-Timestamp", String.valueOf(timestamp));
headers.set("O-Nonce", nonce);
headers.set("O-Sign-Version", "v1");
headers.set("O-Signature", signature);

常见问题

返回鉴权失败 / 40001?

请核对 AppId、AppSecret 是否正确,以及 O-Access-Token 是否为 前缀且 token 未过期。

token 要放在 Body 里吗?

不需要。统一放在请求头 O-Access-Token,Body 只传业务参数。