取消
最近搜索
清空历史

代码样例-API密钥令牌

本文档包含获取密钥令牌(secret_token)的代码样例,供开发者参考。

开发提示

密钥令牌默认有效期为60分钟,您可以在会员中心-API设置里修改。

  • 您不必每次调用接口前都获取令牌,建议您本地保存获取到的secret_token,在合适的时候调用get_secret_token接口再次获取密钥令牌。
  • 您可以随时调用check_secret_token接口检查token有效性。

Python

Python获取密钥令牌实例
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import os
import sys
import json
import time
import requests

secret_id = 'o1fjh1re9o28876h7c08'
secret_key = 'jd1gzm6ant2u7pojhbtl0bam0xpzsm1c'
SECRET_PATH = './.secret'


def _get_secret_token():
    r = requests.post(url='https://auth.kdlapi.com/api/get_secret_token', data={'secret_id': secret_id, 'secret_key': secret_key})
    if r.status_code != 200:
        raise KdlException(r.status_code, r.content.decode('utf8'))
    res = json.loads(r.content.decode('utf8'))
    code, msg = res['code'], res['msg']
    if code != 0:
        raise KdlException(code, msg)
    secret_token = res['data']['secret_token']
    expire = str(res['data']['expire'])
    _time = '%.6f' % time.time()
    return secret_token, expire, _time


def _read_secret_token():
    with open(SECRET_PATH, 'r') as f:
        token_info = f.read()
    secret_token, expire, _time, last_secret_id = token_info.split('|')
    if float(_time) + float(expire) - 3 * 60 < time.time() or secret_id != last_secret_id:  # 还有3分钟过期或SecretId变化时更新
        secret_token, expire, _time = _get_secret_token()
        with open(SECRET_PATH, 'w') as f:
            f.write(secret_token + '|' + expire + '|' + _time + '|' + secret_id)
    return secret_token


def get_secret_token():
    if os.path.exists(SECRET_PATH):
        secret_token = _read_secret_token()
    else:
        secret_token, expire, _time = _get_secret_token()
        with open(SECRET_PATH, 'w') as f:
            f.write(secret_token + '|' + expire + '|' + _time + '|' + secret_id)
    return secret_token


class KdlException(Exception):
    """异常类"""

    def __init__(self, code=None, message=None):
        self.code = code
        if sys.version_info[0] < 3 and isinstance(message, unicode):
            message = message.encode("utf8")
        self.message = message
        self._hint_message = "[KdlException] code: {} message: {}".format(self.code, self.message)

    @property
    def hint_message(self):
        return self._hint_message

    @hint_message.setter
    def hint_message(self, value):
        self._hint_message = value

    def __str__(self):
        if sys.version_info[0] < 3 and isinstance(self.hint_message, unicode):
            self.hint_message = self.hint_message.encode("utf8")
        return self.hint_message


if __name__ == '__main__':
    secret_token = get_secret_token()
    print(secret_token)

Java

Java获取密钥令牌实例
import java.util.ArrayList;
import java.util.List;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import org.json.JSONException;
import org.json.JSONObject;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;


public class GetSecretToken {
    public String secretId = "o1fjh1re9o28876h7c08";
    public String secretKey = "jd1gzm6ant2u7pojhbtl0bam0xpzsm1c";
    public String secretPath = "./.secret";

    public String[] _getSecretToken() throws Exception {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost("https://auth.kdlapi.com/api/get_secret_token");
        List<NameValuePair> kvparams = new ArrayList<NameValuePair>();
        NameValuePair _secretId = new BasicNameValuePair("secret_id", secretId);
        NameValuePair _secretKey = new BasicNameValuePair("secret_key", secretKey);
        kvparams.add(_secretId);
        kvparams.add(_secretKey);
        httpPost.setEntity(new UrlEncodedFormEntity(kvparams, "UTF-8"));
        CloseableHttpResponse response = httpClient.execute(httpPost);
        int statusCode = response.getStatusLine().getStatusCode();
        String content = EntityUtils.toString(response.getEntity(), "UTF-8");
        if (statusCode != HttpStatus.SC_OK) {
            throw new Exception(statusCode + ": " + content);
        }
        String secretToken = null;
        String expireTime = null;
        try {
            JSONObject jsonObject = new JSONObject(content);
            int code = jsonObject.getInt("code");
            if (code != 0) {
                throw new Exception(jsonObject.getString("msg") + ", code: " + code);
            }
            JSONObject jsonData = jsonObject.getJSONObject("data");
            secretToken = jsonData.getString("secret_token");
            expireTime = String.valueOf(jsonData.getInt("expire") * 1000);
        } catch(JSONException e) {
            e.printStackTrace();
        }
        return new String[]{secretToken, expireTime, String.valueOf(System.currentTimeMillis()), secretId};
    }

    public String _readSecretToken() throws Exception {
        String[] tokenList = null;
        String _secretToken = null;
        String _tokenStr = null;
        String _lastSecretId = null;
        boolean needReset = false;
        File secretFile = new File(secretPath);
        if (!secretFile.exists()) {
            secretFile.createNewFile();
        }
        byte[] secretBytes = Files.readAllBytes(Paths.get(secretPath));
        _tokenStr = new String(secretBytes, "UTF-8");
        if (_tokenStr != null && _tokenStr.length() != 0) {
            tokenList = _tokenStr.split("\\|");
            _secretToken = tokenList[0];
            _lastSecretId = tokenList[3];
            long expireTime = Long.valueOf(tokenList[1]);
            long lastTime = Long.valueOf(tokenList[2]);
            // 还有3分钟过期或SecretId变化时更新
            if (lastTime + expireTime - 180 * 1000 < System.currentTimeMillis() || !_lastSecretId.equals(secretId)) {
                needReset = true;
            }
        } else {
            needReset = true;
        }
        if (needReset) {
            GetSecretToken getSecretToken = new GetSecretToken();
            tokenList = getSecretToken._getSecretToken();
            _tokenStr = String.join("|", tokenList);
            try (FileWriter tokenFileWriter = new FileWriter(secretPath)) {
                tokenFileWriter.write(_tokenStr);
            } catch (IOException e) {
                e.printStackTrace();
            }
            _secretToken = tokenList[0];
        }
        return _secretToken;
    }

    public static void main(String[] args) throws Exception {
        GetSecretToken getSecretToken = new GetSecretToken();
        String secretToken = getSecretToken._readSecretToken();
        System.out.println(secretToken);
    }
}

NodeJS

Nodejs获取密钥令牌实例
const axios = require('axios');
const fs = require('fs');
const querystring = require('querystring');


let secretId = 'o1fjh1re9o28876h7c08';
let secretKey = 'jd1gzm6ant2u7pojhbtl0bam0xpzsm1c';
let secretPath = './.secret';

function _getSecretToken () {
    return axios({
        url: 'https://auth.kdlapi.com/api/get_secret_token',
        method: 'post',
        data: querystring.stringify({
            secret_id: secretId,
            secret_key: secretKey,
        })
    }).then(response => {
        if (response.data.code !== 0) throw new Error(response.data.msg + ', code: ' + response.data.code);
        let secretToken = response.data.data.secret_token;
        let expireTime = response.data.data.expire;
        let lastTime = (new Date()).getTime();
        return [secretToken, parseInt(expireTime) * 1000, lastTime, secretId];
    }).catch(error => {
        throw error;
    });
}

async function _readSecretToken() {
    let readBuff = fs.readFileSync(secretPath, {encoding:'utf-8'});
    let tokenList = readBuff.split('|');
    let expireTime = parseInt(tokenList[1]);
    let lastTime = parseInt(tokenList[2]);
    let lastSecretId = parseInt(tokenList[3]);
    if (lastTime + expireTime - 180 * 1000 < (new Date()).getTime() || lastSecretId !== secretId) {  // 还有3分钟过期或SecretId变化时更新
        tokenList = await _getSecretToken();
        fs.writeFileSync(secretPath, tokenList.join('|'));
    }
    return tokenList;
}

async function getSecretToken() {
    try {
        let tokenList = await _readSecretToken();
        return tokenList[0];
    } catch {
        let tokenList = await _getSecretToken();
        fs.writeFileSync(secretPath, tokenList.join('|'));
        return tokenList[0];
    }
}

getSecretToken().then(secretToken => console.log(secretToken));

PHP

php获取密钥令牌实例
<?php 

$secretId = 'o1fjh1re9o28876h7c08';
$secretKey = 'jd1gzm6ant2u7pojhbtl0bam0xpzsm1c';
$secretPath = './.secret';


function _getSecretToken ()
{
    global $secretId, $secretKey;
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, "https://auth.kdlapi.com/api/get_secret_token");
    $data = array("secret_id" => $secretId, "secret_key" => $secretKey);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
    $response = json_decode(curl_exec($ch));
    curl_close($ch);
    if ($response->code !== 0) throw new Exception("Error: ".$response->msg.", code: ".$response->code.PHP_EOL);
    return array($response->data->secret_token, $response->data->expire, time(), $secretId);
}

function _writeSecretToken ($secretPath) 
{
    $tokenList = _getSecretToken();
    $secretFile = fopen($secretPath, "w");
    fwrite($secretFile, implode("|", $tokenList));
    fclose($secretFile);
    return $tokenList;
}

function _readSecretToken ($secretPath)
{
    global $secretId;
    $secretFile = fopen($secretPath, "r");
    $tokenList = explode("|", fread($secretFile, 1024));
    fclose($secretFile);
    $expireTime = $tokenList[1];
    $lastTime = $tokenList[2];
    $lastSecretId = $tokenList[3];
    if ($lastTime + $expireTime - 3 * 60 < time() || $lastSecretId !== $secretId) {  // 还有3分钟过期或SecretId变化时更新
        $tokenList = _writeSecretToken($secretPath);
    }
    return $tokenList;
}

function getSecretToken ()
{
    try 
    {
        global $secretPath;

        if (file_exists($secretPath)) $tokenList = _readSecretToken($secretPath);
        else $tokenList = _writeSecretToken($secretPath);
        return $tokenList[0];
    }
    catch (Exception $e) 
    {
        echo $e->getMessage();
    }
}

$token = getSecretToken();
echo $token.PHP_EOL;

?>
联系我们