def verify_wxapp(encrypted_data, iv, code): user_info = get_wxapp_userinfo(encrypted_data, iv, code) openid = user_info.get('openId', None) if openid: auth = Account.get_by_wxapp(openid) if not auth: raise Unauthorized('wxapp_not_registered') return auth raise Unauthorized('invalid_wxapp_code')
def get_wxapp_userinfo(encrypted_data, iv, code): from weixin.lib.wxcrypt import WXBizDataCrypt from weixin import WXAPPAPI from weixin.oauth2 import OAuth2AuthExchangeError appid = Config.WXAPP_ID secret = Config.WXAPP_SECRET api = WXAPPAPI(appid=appid, app_secret=secret) try: session_info = api.exchange_code_for_session_key(code=code) except OAuth2AuthExchangeError as e: raise Unauthorized(e.code, e.description) session_key = session_info.get('session_key') crypt = WXBizDataCrypt(appid, session_key) user_info = crypt.decrypt(encrypted_data, iv) return user_info
async def post(self, request): is_validate, token = create_token(request) if not is_validate: raise Unauthorized('unauthorized', 'Invalid token', '用户未注册') return token, 201