# 签名计算方法

# 个人免登场景的签名计算方法

签名算法为HmacSHA256,签名数据是当前时间戳timestamp,密钥是appId对应的appSecret,使用密钥对timestamp计算签名值。

发送HTTP请求时需要把signature进行urlEncode,如果您使用的是HTTP封装方法,请确保不要重复urlEncode。

# 签名参数说明

参数 说明
accessKey 扫码登录应用的appId
timestamp 当前时间戳,单位是毫秒
signature 通过appSecret计算出来的签名值, 该参数值在HTTP请求参数中需要urlEncode(因为签名中可能包含特殊字符+)

签名计算代码示例(Java)

// 根据timestamp, appSecret计算签名值
String stringToSign = timestamp
Mac mac = Mac.getInstance("HmacSHA256");
mac.init(new SecretKeySpec(appSecret.getBytes("UTF-8"), "HmacSHA256"));
byte[] signatureBytes = mac.doFinal(stringToSign.getBytes("UTF-8"));
String signature = new String(Base64.encodeBase64(signatureBytes));
String urlEncodeSignature = urlEncode(signature);

签名计算代码示例(PHP)

    // 根据timestamp, appSecret计算签名值
    $s = hash_hmac('sha256', 'timestamp', 'appSecret', true);
    $signature = base64_encode($s);
    var_dump($signature);
    $urlencode_signature = urlencode($signature);
    var_dump($urlencode_signature);

urlEncode代码示例(Java)

    // encoding参数使用utf-8
    public static String urlEncode(String value, String encoding) {
    if (value == null) {
        return "";
    }
    try {
        String encoded = URLEncoder.encode(value, encoding);
        return encoded.replace("+", "%20").replace("*", "%2A")
            .replace("~", "%7E").replace("/", "%2F");
    } catch (UnsupportedEncodingException e) {
        throw new IllegalArgumentException("FailedToEncodeUri", e);
    }
}

签名例子参考:

timestamp=1587046137901

appSecret=testappSecret

signature=H0k8f/z0hSFhOYvyHGcul4lyI9Fim3g76+67bDt/4BY=

urlEncode后的signature=H0k8f%2Fz0hSFhOYvyHGcul4lyI9Fim3g76%2B67bDt%2F4BY%3D

CURL示例

curl 'https://yach-oapi.zhiyinlou.com/sns/getuserinfo_bycode?signature=xxxxxx&timestamp=1527130370219&accessKey=dingxxxxyyy' -H "Content-Type:application/json" -X POST --data '{"tmp_auth_code":"tmp_auth_code"}'
上次更新: 7/4/2020, 1:59:59 AM
foo