YzyApi.py 6.1 KB

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