- 积分
- 534
- 金钱
- 431
- 威望
- 0
- 贡献
- 0
- HASS币
- 0
高级会员
- 积分
- 534
- 金钱
- 431
- HASS币
- 0
|
楼主 |
发表于 2024-5-31 12:52:51
|
显示全部楼层
import hashlib
import hmac
import base64
import time
from uuid import uuid4
import requests
# 配置参数
app_key = "666666"
app_secret = "your_app_secret" # 你的 API 密钥
method = "POST"
accept = "application/json; charset=utf-8"
content_type = "application/json"
url_path = "/thing/properties/set"
url = "https://api.link.aliyun.com" + url_path
payload = "{\"id\":\"1a139d60-26d4-4292-b92f-1861b91fb75d\",\"params\":{\"items\":{\"PowerSwitch\":0},\"iotId\":\"508sTj1pdL0G89o1pJ5u000000\"},\"request\":{\"language\":\"zh-CN\",\"iotToken\":\"51a05280cdd3150c8a09d83905faa54e\",\"apiVer\":\"1.0.2\"},\"version\":\"1.0\"}"
params = {
'x-ca-request-id': "1a139d60-26d4-4292-b92f-1861b91fb75d"
}
# 计算 content-md5
content_md5 = base64.b64encode(hashlib.md5(payload.encode('utf-8')).digest()).decode('utf-8')
# 生成时间戳和随机 nonce
timestamp = str(int(time.time() * 1000))
nonce = str(uuid4())
# 准备签名字符串
sign_headers = 'x-ca-key,x-ca-timestamp,x-ca-signature-method,x-ca-nonce'
headers_to_sign = {
'x-ca-key': app_key,
'x-ca-timestamp': timestamp,
'x-ca-signature-method': 'HmacSHA1',
'x-ca-nonce': nonce
}
sign_str = method + '\n' + content_md5 + '\n' + content_type + '\n' + accept + '\n'
for key in sign_headers.split(','):
sign_str += key + ':' + headers_to_sign[key] + '\n'
sign_str += url_path
# 计算签名
signature = base64.b64encode(hmac.new(app_secret.encode('utf-8'), sign_str.encode('utf-8'), hashlib.sha1).digest()).decode('utf-8')
# 准备请求头
headers = {
'User-Agent': "ALIYUN-ANDROID-DEMO",
'Accept': accept,
'Content-Type': content_type,
'Content-MD5': content_md5,
'x-ca-key': app_key,
'x-ca-timestamp': timestamp,
'x-ca-signature-method': 'HmacSHA1',
'x-ca-nonce': nonce,
'x-ca-signature': signature,
'x-ca-signature-headers': sign_headers
}
# 发送请求
response = requests.post(url, params=params, data=payload, headers=headers)
# 打印响应
print(response.text)
|
|