tools.py 1010 B

1234567891011121314151617181920212223242526272829303132
  1. # -*- coding: utf-8 -*-
  2. from weixin.lib.wxcrypt import WXBizDataCrypt
  3. from weixin import WXAPPAPI
  4. from weixin.oauth2 import OAuth2AuthExchangeError
  5. def get_wx_session_info(app_id, secret, code):
  6. api = WXAPPAPI(appid=app_id, app_secret=secret)
  7. try:
  8. session_info = api.exchange_code_for_session_key(code=code)
  9. except OAuth2AuthExchangeError as e:
  10. raise e
  11. return session_info
  12. def get_wx_user_info(app_id, secret, code, encrypted_data, iv):
  13. session_info = get_wx_session_info(app_id, secret, code)
  14. session_key = session_info.get('session_key')
  15. crypt = WXBizDataCrypt(app_id, session_key)
  16. user_info = crypt.decrypt(encrypted_data, iv)
  17. if 'openId' not in user_info:
  18. open_id = session_info.get('openid')
  19. user_info['openId'] = open_id
  20. return session_key, user_info
  21. def get_decrypt_info(app_id, session_key, encrypted_data, iv):
  22. crypt = WXBizDataCrypt(app_id, session_key)
  23. _info = crypt.decrypt(encrypted_data, iv)
  24. return _info