签名机制
<h5>签名机制</h5>
<ol>
<li>设所有发送或者接收到的数据为集合M,将集合M内非空参数值的参数按照参数名ASCII码从小到大排序(字典序),使用URL键值对的格式(即key1=value1&key2=value2…)拼接成字符串stringA。</li>
<li>在stringA最后拼接上秘钥得到stringSignTemp字符串,并对stringSignTemp进行MD5运算,再将得到的字符串所有字符转换为大写,得到sign值signValue。</li>
</ol>
<h5>签名示例</h5>
<pre><code class="language-java">const appKey = 'app_key1111'; #商户秘钥
const nonceStr = 'nonceStr'; #随机字符串每次请求应不同。
#HTTP 参数:
{ "channel": 18, "guid": "2088901111111130",month: "201903" }
#加入nonce_str:
{ "channel": 18, "guid": "2088901111111130",month: "201903","nonceStr":nonceStr }
#排序后转成params,最后加入appKey:
channel=18&guid=2088901111111130&month=201903&nonceStr=nonce_str&key=appKey1111
#MD5运算转换为大写得到sign,填充到参数中:
0B46C3DF9A05C299CEF5E4849034F955</code></pre>
<h5>签名实现</h5>
<pre><code class="language-java">public static String getSign(Map<String, Object> params, String appKey) {
params.put("nonceStr", generateRandomStr(8));//随机字符串,每次请求应不同。
StringBuffer sb = new StringBuffer();
SortedSet<String> keys = new TreeSet<>(params.keySet());
for (String key : keys) {
sb.append(key + "=" + params.get(key) + "&");
}
sb.append("key=" + appKey);
return md5(sb.toString()).toUpperCase();
}</code></pre>