Links

签名生成步骤说明

第一步:
设所有发送或者接收到的数据为集合M,将集合M内非空参数值的参数按照参数名ASCII码从小到大排序(字典序),使用URL键值对的格式(即key1=value1&key2=value2…)拼接成字符串stringA。
特别注意以下重要规则:
  1. 1.
    参数名ASCII码从小到大排序(字典序);
  2. 2.
    app_id,timestamp为必填参数;timestamp为最近五分钟毫秒级时间戳,超过5分钟失效;
  3. 3.
    如果参数的值为空不参与签名;
  4. 4.
    参数名区分大小写;
  5. 5.
    传送的sign参数不参与签名,将生成的签名与该sign值作校验。
第二步:
在stringA最后拼接上key得到stringSignTemp字符串,并对stringSignTemp进行HMAC-SHA256运算,再将得到的字符串所有字符转换为大写,得到sign值signValue。
伪代码举例
假设传送的参数如下: channelId: mttest timestamp : 1516320000000 body : test
第一步:对参数按照key=value的格式,并按照参数名ASCII字典序排序如下:
stringA="channelId=mttest&body=test&timestamp=1516320000000";
第二步:拼接API密钥:
stringSignTemp=stringA+"&secret=my_test_secret"
sign=hash_hmac("sha256",stringSignTemp,key).toUpperCase()="6A9AE1657590FD6257D693A078E1C3E4BB6BA4DC30B23E0EE2496E54170DACD6" //注:HMAC-SHA256签名方式
示例代码
@Test
public void deductBalance() throws IOException {
JTextField field ;
String url = "http://localhost:8088/channel/deductBalance";
//Java中的TreeMap会自动将key按照以ASCII字典进行排序
TreeMap<String,Object> params = Maps.newTreeMap();
params.put("orderId","my_order_id");
params.put("channelId","test91021071617412");
long timestamp = System.currentTimeMillis();
params.put("timestamp",timestamp);
String channelSign = getChannelSign(params, secret);
params.put("sign",channelSign);
System.out.println(url);
System.out.println(JSON.toJSONString(params));
String result = HttpUtils.sendRequestBody(url, params);
System.out.println(result);
}
public static String getChannelSign(Map<String, Object> params,String secret) {
StringBuilder result = new StringBuilder();
if (params != null) {
for (Object key : params.keySet()) {
Object value = params.get(key);
result.append(key).append("=").append(value).append("&");
}
String tempString = result + "secret=" + secret;
try {
System.out.println(tempString);
String sign = EncryptUtils.sha256_HMAC(tempString, secret).toUpperCase();
System.out.println(sign);
return sign;
} catch (Exception e) {
e.printStackTrace();
}
}
return null;
}
代码中参与加密的参数及顺序为:channelId=test91021071617412&orderId=my_test_id&timestamp=1547987604644&secret=my_secret