===== 帮我吧im客户端动态签名规则说明 =====
>注: 此规则仅当后台开启客户端动态签名项才生效。
===1. URL必传参数:===
* signature 签名token
* timestamp 13位时间戳
* nonce 随机数
===2. 签名规则说明:===
- 对除signature外的全部参数签名,先字典升序后hash :
sha1(private_key,timestamp,nonce,param1...)
* private_key: 秘钥(在后台设置中生成和重置)
* timestamp 时间戳1小时内有效
* 其余参数根据实际需要传递
* 中文参数UTF-8编码,必须urlencode
===3. 签名代码示例===
① PHP版本
nonce = time();
$this->timestamp = $this->getUnixMicroTime();
}
//获取13位时间戳
protected function getUnixMicroTime() {
$time = microtime(1);
return floor($time * 1000);
}
//生成签名
public function makeSignature(array $params){
$params['private_key'] = $this->private_key;
$params['timestamp'] = $this->timestamp;
$params['nonce'] = $this->nonce;
$tmpArr = array_values($params);
sort($tmpArr, SORT_STRING);
return $tmpStr = sha1(implode($tmpArr));
}
}
//参数需要根据实际情况传递
$params = [
'vendorID'=>128789,
'uid'=>'u6_128789_1234567890' //如过您使用的是api方式对接自定义字段(authaccount)导入第三方系统账号时,uid 格式是 u6_vendorID_{第三方系统账号}
];
$signObj = new Signature();
$signature = $signObj->makeSignature($params);
② JAVA版本
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.*;
public class Signature {
private static final String PC_PRIVATE_KEY = "pc_key";
private static final String H5_PRIVATE_KEY = "h5_key";
public static String sha1(String str) {
char[] hexDigits = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
try {
MessageDigest mdTemp = MessageDigest.getInstance("SHA1");
mdTemp.update(str.getBytes(StandardCharsets.UTF_8));
byte[] md = mdTemp.digest();
int j = md.length;
char[] buf = new char[j * 2];
int k = 0;
for (byte byte0 : md) {
buf[k++] = hexDigits[byte0 >>> 4 & 0xf];
buf[k++] = hexDigits[byte0 & 0xf];
}
return new String(buf);
} catch (Exception e) {
return null;
}
}
public static String makeSignature(Map map, Boolean isFromPC) {
map.put("private_key", Boolean.TRUE.equals(isFromPC) ? PC_PRIVATE_KEY : H5_PRIVATE_KEY);
map.put("timestamp", String.valueOf(System.currentTimeMillis())); // 1660726411772
map.put("nonce", String.valueOf(new Random().nextInt(Integer.MAX_VALUE))); // 123456
List> list = new ArrayList<>(map.entrySet());
list.sort(Map.Entry.comparingByValue());
StringBuilder tempStr = new StringBuilder();
for (Map.Entry mapping : list) {
tempStr.append(mapping.getValue());
}
return sha1(tempStr.toString());
}
// test
public static void main(String[] args) {
Map map = new HashMap<>();
map.put("vendorID", "128789");
map.put("uid", "u2_128789_1234567890");
String signature = makeSignature(map, Boolean.TRUE);
System.out.println(signature);
}
}
4. 最终生成的带签名的url链接示例:
''https://www.bangwo8.com/osp2016/chat/pc/index.php?vendorID=128789&uid=u6_128789_1234567890×tamp=1566385123983&nonce=862739&signature=588370c3a10858fde89e16cc26ea775e0f87129c''