注: 此规则仅当后台开启客户端动态签名项才生效。
- 对除signature外的全部参数签名,先字典升序后hash :
sha1(private_key,timestamp,nonce,param1...)
① PHP版本
<?php /** * 签名类 * Class Signature */ class Signature{ private $nonce; private $timestamp; private $private_key = 'aef2l3gze982ew'; public function __construct() { $this->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<String, String> 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<Map.Entry<String, String>> list = new ArrayList<>(map.entrySet()); list.sort(Map.Entry.comparingByValue()); StringBuilder tempStr = new StringBuilder(); for (Map.Entry<String, String> mapping : list) { tempStr.append(mapping.getValue()); } return sha1(tempStr.toString()); } // test public static void main(String[] args) { Map<String, String> 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链接示例: