尝试使用万能红外遥控器通过接口控制空调。目前postman已经调通。
调通的接口文本:
Code: Select all
url = "https://openapi.tuyacn.com/v1.0/devices/6cb0efdfcfd228ef8baai2/commands"
body= json.dumps({
  "commands": [
    {
      "code": "PowerOff"
    }
  ]
})
headers = {
  'client_id': '5yw7u9j445wfxpsw5e35',
  'access_token': 'd1aead51031ddba6bf31ee96e038a771',
  'sign': 'C8659450EC11AE1A9ACC1FFDBEF238673951ABF516A75E62CA7CB5495C89FBEC',
  't': '1713080039881',
  'sign_method': 'HMAC-SHA256',
  'Content-Type': 'application/json',
  'nonce': '',
  'stringToSign': ''
}
但在转换成python脚本的时候遇到问题,我基于同样的access_token和t已经可以生成相同的sign了,但是调用接口返回 sign invalid 。
我的python脚本:
Code: Select all
import time
import hmac
import hashlib
import requests
ACCESS_ID = "5yw7u9j445wfxpsw5e35"
token = "d1aead51031ddba6bf31ee96e038a771"
timestamp = int(time.time() * 1000)
#timestamp = 1713080039881
url = "https://openapi.tuyacn.com/v1.0/devices/6cb0efdfcfd228ef8baai2/commands"
signstr = "POST\nf935b82a0bdb9902f68d673da0c4595ca7c1213898d778a6d48bd2c24a2008bd\n\n/v1.0/devices/6cb0efdfcfd228ef8baai2/commands"
fullstr = f"{ACCESS_ID}{token}{timestamp}{signstr}".encode('utf-8')
comsignature = hmac.new(secret, fullstr, hashlib.sha256).hexdigest().upper()
payload = json.dumps({
  "commands": [
    {
      "code": "PowerOff"
    }
  ]
})
headers = {
  'client_id': ACCESS_ID,
  'access_token': token,
  'sign': comsignature,
  't': f"{timestamp}",
  'sign_method': 'HMAC-SHA256',
  'Content-Type': 'application/json',
  'nonce': '',
  'stringToSign': ''
}
response = requests.request("POST", url, headers=headers, data=payload)
我基于同样的access_token和t生成的header:
{'client_id': '5yw7u9j445wfxpsw5e35',
 'access_token': 'd1aead51031ddba6bf31ee96e038a771',
 'sign': 'C8659450EC11AE1A9ACC1FFDBEF238673951ABF516A75E62CA7CB5495C89FBEC',
 't': '1713080039881',
 'sign_method': 'HMAC-SHA256',
 'Content-Type': 'application/json',
 'nonce': '',
 'stringToSign': ''}
已经实现了和前面基于postman pre_request scripts生成的接口内容一致,但替换成timestamp = int(time.time() * 1000)后,如何运行都是sign invalid 。