前言

使用阿里云产品,调用API接口一般有两种方式,使用APPCODE或使用ak、sk生成认证签名。
第二种比较复杂,今天记录一下。

代码

  1. 调用阿里云接口,需要在headers中添加签名(X-Ca-Signature字段)
  2. 以whois查询接口为例 (http://whois.market.alicloudapi.com/icredit_ai_seo/whois/v1)
  3. 阿里云生成认证字符串文档
  4. 以nodejs为例
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    const AppKey = 'your AK';
    const AppSecret = 'your SK';
    const domainName = 'your domain name';

    const apiUrl = `http://whois.market.alicloudapi.com/icredit_ai_seo/whois/v1?STRING=${domainName}`;

    const headers = {
    'Accept': 'application/json',
    'X-Ca-Key': AppKey,
    'X-Ca-Signature': getALYSignature(domainName, AppSecret, '/icredit_ai_seo/whois/v1')
    };
    1
    2
    3
    4
    5
    6
    7
    8
    9
    // path 除根路径以外的其它部分
    function getALYSignature(domainName, AppSecret, path) {
    let StringToSign = 'GET' + '\n' + 'application/json' + '\n' + '\n' + '\n' + '\n' + path + '?STRING=' + domainName;
    return crypto
    .createHmac('sha256', AppSecret)
    .update(StringToSign)
    .digest()
    .toString('base64'); // 这里使用base64 不是hex
    }

总结

  1. 使用阿里云的whois接口时,有的域名查询需要加**www.**才可以查询,有的不需要(规律我也找不到)。
  2. 通常返回结果为空时,都是查询出错了。错误代码一般都在返回的headers中,对照官方文档查看即可。