YzyApi.py 5.9 KB

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