中国站
帮助中心 > 通信 > API文档 > 代码示例 > Python

Python

  1. import requests
  2. import json
  3. import random
  4. import urllib
  5. import time
  6. import base64
  7. import hmac
  8. from hashlib import sha1
  9. def hash_hmac(key, code, sha1):
  10. hmac_code = hmac.new(key.encode(), code.encode(), sha1)
  11. return hmac_code.digest()
  12. def send():
  13. url = 'https://api.yisu.com/sms/sendSms'
  14. accessId = '*****'
  15. accessSecret = '*****'
  16. params = {
  17. 'accessId': accessId,
  18. 'templateCode' : 100001,
  19. 'nonce': random.randint(10000000, 99999999),
  20. 'phone' : '13800000000',
  21. 'timestamp' : int(time.time()),
  22. 'templateVars' : json.dumps({"code":"123123","min":5}, separators=(',', ':'))
  23. }
  24. params_keys = list(params.keys())
  25. params_keys.sort()
  26. params_str = ""
  27. for key in params_keys:
  28. params_str += key + '=' + str(params[key]) + '&'
  29. params_str = params_str[:-1]
  30. sign = base64.b64encode(hash_hmac(accessSecret, params_str, sha1))
  31. params['signature'] = str(sign,'utf-8')
  32. res = requests.post(url, data=params, verify=False)
  33. print(res.text)
  34. if __name__ == '__main__':
  35. send()