每次请求API接口时,均需要提供4个HTTP Request Header,具体如下:
名称 | 类型 | 说明 |
---|---|---|
AppID | String | 平台 上分配的AppID |
Nonce | String | 随机数组成的字符串(用户自定义),长度限制为30个字节 |
Timestamp | String | 北京时间戳,从1970年1月1日0点0分0 秒开始到现在的毫秒数 |
Signature | String | 数据签名 |
依次使用 AppSecret(平台 分配)、Timestamp、Nonce 按如下伪代码逻辑生成用于签名的间接key,签名算法使用hmac sha256。 伪代码:
sign_key = hmac.new(AppSecret, Timestamp, sha256).digest()
signing_key = hmac.new(sign_key, Nonce, sha256).digest()
使用步骤1生成signing_key对签名字符串序列(“时间戳/随机数")按如下伪代码生成最终数据签名Signature。 伪代码:
string_to_sign = Timestamp + '/' + Nonce
signature = hmac.new(signing_key, string_to_sign), sha256).hexdigest()
说明:
如果调用的数据签名验证失败,接口调用会返回HTTP状态码401。
#!/usr/bin/env python
# coding: utf-8
import time, hashlib, hmac
import requests # pip install requests
import random
# ************* REQUEST VALUES *************
host = 'cn.hummer.yy.com'
endpoint = 'http://cn.hummer.yy.com:9530'
request_uri = '/user/get_token'
def sign(key, msg):
return hmac.new(key, msg.encode('utf-8'), hashlib.sha256).digest()
def getSignatureKey(key, timestamp, nonce):
# 签名顺序 timestamp nonce
kTimestamp = sign(key.encode('utf-8'), timestamp)
kSigning = sign(kTimestamp, nonce)
return kSigning
# AK SK
access_key = "XXXXXXXXXX"
secret_key = "XXXXXXXXXX"
# 时间戳, 北京时间毫秒
timestamp = str(int(time.time()*1000))
# 随机字符串, 最大长度30字节
nonce = str(random.randint(1, 10000))
# 签名序列 时间戳/随机数
string_to_sign = timestamp + '/' + nonce
# ************* TASK 2: CREATE SIGNING KEY *************
# Create the signing key using the function defined above.
# 第一步: 使用secretkey timestamp, nonce 生成用于签名的key
signing_key = getSignatureKey(secret_key, timestamp, nonce)
# ************* TASK 2: CREATE SIGNATURE *************
# Sign the string_to_sign using the signing_key
# 第二步: 使用签名的key对签名字符串签名生成signature
signature = hmac.new(signing_key, (string_to_sign).encode('utf-8'), hashlib.sha256).hexdigest()
# ************* TASK 3: ADD SIGNING INFORMATION TO THE REQUEST *************
# Create authorization header and add to request headers
authorization_header = {
"AppID": access_key,
"Nonce": nonce,
"Timestamp": timestamp,
"Signature": signature
}
headers = dict({'Host': host, 'Content-Type':"application/json"}, **authorization_header)
data = {"log_id": 1, "app_id": int(access_key) , "uid": int(access_key)}
# ************* SEND THE REQUEST *************
request_url = endpoint+request_uri
print('\nBEGIN REQUEST++++++++++++++++++++++++++++++++++++')
print('Request URL = ' + request_url)
r = requests.post(request_url, headers=headers, json=data)
print('\nRESPONSE++++++++++++++++++++++++++++++++++++')
print('Response code: %d\n' % r.status_code)
print(r.text)