YzyApi.py 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185
  1. #!/usr/bin/python3
  2. # -*- coding: utf-8 -*-
  3. import random
  4. import string
  5. import hashlib
  6. import time
  7. import base64
  8. import json
  9. from utils.redis_util import *
  10. import requests
  11. from exceptions import YzyException
  12. # 应用名称:茂名市智慧应急平台
  13. # https://open.weixin.qq.com/connect/Oauth2/authorize?appid=wld341060039&redirect_uri=https://www.baidu.com/#/&response_type=code&scope=snsapi_base&agentid=1004302&state=xxxxxx#wechat_redirect
  14. YZY_HOST = "http://19.15.0.128:8080"
  15. # YZY_HOST = "https://xtbg.digitalgd.com.cn"
  16. YZY_AGENTID = 1004302
  17. YZY_CORPID = "wld341060039"
  18. YZY_CORPSECRET = "5_8aOBBjioNbP7KDwjyBKmwnJ05-y1WbaJlt4irM1eA"
  19. YZY_ACCESS_TOKEN_REDIS_KEY = "YZY_ACCESS_TOKEN_REDIS_KEY"
  20. YZH_PASSID = "yzy_demo"
  21. YZH_PASSTOKEN = "WjKat55cv6PrJtpCHld0trrHsv1mbCqL"
  22. def __get_access_token():
  23. url = "{}/ebus/yzyapi/cgi-bin/gettoken?corpid={}&corpsecret={}".format(YZY_HOST, YZY_CORPID, YZY_CORPSECRET)
  24. print('yzy url:', url)
  25. timestamp = str(int(time.time()))
  26. nonce = ranstr(20)
  27. signature = calcResponseSign(timestamp, YZH_PASSTOKEN, nonce)
  28. headers = {
  29. 'Content-Type': 'application/json;charset=UTF-8',
  30. "x-tif-signature": signature,
  31. "x-tif-timestamp": timestamp,
  32. "x-tif-nonce": nonce,
  33. "x-tif-paasid": YZH_PASSID
  34. }
  35. response = requests.get(url, headers=headers, timeout=15)
  36. print('yzy return:', response.text)
  37. if response.status_code == 200 :
  38. result = response.json()
  39. errcode = int(result['errcode'])
  40. if errcode == 0:
  41. return result['access_token']
  42. else:
  43. raise YzyException(errcode=errcode, errmsg=result['errmsg'])
  44. def get_cache_access_token():
  45. access_token = redis_get(YZY_ACCESS_TOKEN_REDIS_KEY)
  46. if access_token is None:
  47. access_token = __get_access_token()
  48. redis_set_with_time(YZY_ACCESS_TOKEN_REDIS_KEY, access_token, 3600)
  49. return access_token
  50. def get_user_info(code: str):
  51. access_token = get_cache_access_token()
  52. url = "{}/ebus/yzyapi/cgi-bin/user/getuserinfo?access_token={}&code={}".format(YZY_HOST, access_token, code)
  53. return __post_url__(url, {})
  54. def send_text_message(users, content: str):
  55. access_token = get_cache_access_token()
  56. url = "{}/ebus/yzyapi/cgi-bin/message/send?access_token={}".format(YZY_HOST, access_token)
  57. data = {
  58. "touser": "|".join(users),
  59. "msgtype" : "text",
  60. "agentid" : YZY_AGENTID,
  61. "text": {
  62. "content": content
  63. }
  64. }
  65. return __post_url__(url, data)
  66. def send_textcard_message(users, title: str, description: str, detail_url: str):
  67. access_token = get_cache_access_token()
  68. url = "{}/ebus/yzyapi/cgi-bin/message/send?access_token={}".format(YZY_HOST, access_token)
  69. touser = ""
  70. if isinstance(users, list) == True:
  71. touser = "|".join(users)
  72. else:
  73. touser = str(users)
  74. data = {
  75. "touser": touser,
  76. "msgtype" : "textcard",
  77. "agentid" : YZY_AGENTID,
  78. "textcard": {
  79. "title": title,
  80. "description": description,
  81. "url": detail_url
  82. }
  83. }
  84. return __post_url__(url, data)
  85. def __post_url__(url, data):
  86. print('yzy url:', url)
  87. print('yzy data:', data)
  88. json_str = json.dumps(data, ensure_ascii=False)
  89. data = json_str.encode('utf-8')
  90. timestamp = str(int(time.time()))
  91. nonce = ranstr(20)
  92. signature = calcResponseSign(timestamp, YZH_PASSTOKEN, nonce)
  93. headers = {
  94. 'Content-Type': 'application/json;charset=UTF-8',
  95. "x-tif-signature": signature,
  96. "x-tif-timestamp": timestamp,
  97. "x-tif-nonce": nonce,
  98. "x-tif-paasid": YZH_PASSID
  99. }
  100. response = requests.post(url, data=data,headers=headers, timeout=5)
  101. print('yzy return:', response.text)
  102. if response.status_code == 200 :
  103. result = response.json()
  104. return result
  105. '''
  106. errcode = int(result['errcode'])
  107. if errcode == 0:
  108. return True
  109. else:
  110. raise YzyException(errcode=errcode, errmsg=result['errmsg'])
  111. '''
  112. def ranstr(num):
  113. salt = ''.join(random.sample(
  114. string.ascii_letters + string.digits, num))
  115. return salt
  116. #
  117. #
  118. # 生成校验码
  119. #
  120. #
  121. def authentication(timestamp, token, nonce, uid, uinfo, ext, signature):
  122. sign_data_sha256 = calcRequestSign(
  123. timestamp, token, nonce, uid, uinfo, ext)
  124. return sign_data_sha256 == signature.upper()
  125. #
  126. #
  127. # 计算校验码
  128. #
  129. #
  130. def calcResponseSign(timestamp, token, nonce):
  131. sign_data = "{}{}{}{}".format(timestamp, token, nonce, timestamp)
  132. return hashlib.sha256(
  133. sign_data.encode("utf8")
  134. ).hexdigest().upper()
  135. #
  136. #
  137. # 计算校验码
  138. #
  139. #
  140. def calcRequestSign(timestamp, token, nonce, uid, uinfo, ext):
  141. sign_data = "{}{}{},{},".format(
  142. timestamp, token, nonce, uid)
  143. if len(uinfo) == 0:
  144. sign_data = sign_data + ","
  145. else:
  146. sign_data = sign_data + uinfo + ","
  147. if len(ext) == 0:
  148. sign_data = sign_data
  149. else:
  150. sign_data = sign_data + ext
  151. sign_data = sign_data + timestamp
  152. return hashlib.sha256(
  153. sign_data.encode("utf8")
  154. ).hexdigest().upper()