YzyApi.py 5.8 KB

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