Esempio n. 1
0
def get_user_info(js_code, userinfo, iv):
    api = WXAPPAPI(AppID, AppSecret)
    session_info = api.exchange_code_for_session_key(js_code)
    session_key = session_info.get('session_key')
    crypt = WXBizDataCrypt(AppID, session_key)
    user_info = crypt.decrypt(userinfo, iv)
    return user_info
Esempio n. 2
0
    def bind_mobile(self, sub_domain, token=None, encryptedData=None, iv=None, **kwargs):
        '''
        绑定手机号码
        '''
        try:
            res, wechat_user, entry = self._check_user(sub_domain, token)
            if res:
                return res

            access_token = request.env(user=1)['wxapp.access_token'].search([
                ('token', '=', token),
            ])
            config = request.env['wxapp.config'].sudo()

            encrypted_data = encryptedData
            if not encrypted_data or not iv:
                return self.res_err(300)

            app_id = config.get_config('app_id', sub_domain)
            secret = config.get_config('secret', sub_domain)

            if not app_id or not secret:
                return self.res_err(404)

            crypt = WXBizDataCrypt(app_id, access_token.session_key)
            user_info = crypt.decrypt(encrypted_data, iv)
            wechat_user.write({'mobile': user_info['phoneNumber']})

            return self.res_ok()

        except Exception as e:
            _logger.exception(e)
            return self.res_err(-1, e.name)
def get_weixin_user_info(data):

    # 获取前端传递过来的三个关键的值
    code = data['code']
    iv = data['iv']
    encrypted_data = data['encryptedData']

    # 用配置文件中的配置生成API接口
    api = WXAPPAPI(appid=APP_ID, app_secret=APP_SECRET)
    try:
        # 使用code换取session_key
        session_info = api.exchange_code_for_session_key(code)
    except OAuth2AuthExchangeError as e:
        print(e, '验证失败,请重试')
    session_key = session_info.get('session_key')

    # 使用session_key生成密钥
    crypt = WXBizDataCrypt(APP_ID, session_key)
    try:
        # 解密得到用户信息
        user_info = crypt.decrypt(encrypted_data, iv)
    except UnicodeDecodeError as e:
        print(e, '请从新获取用户授权')

    _data = format_user_info(user_info)

    return _data
Esempio n. 4
0
    def UserInfomation(request, session_key, encrypted_data, iv):

        crypt = WXBizDataCrypt(settings.WXAPP_ID, session_key)
        user_info = crypt.decrypt(encrypted_data, iv)
        print(user_info)
        openid = user_info.get('openId', None)
        nickname = user_info.get('nickName', None)
        print(nickname)
        gender = user_info.get('gender')
        city = user_info.get('city')
        province = user_info.get('province')
        country = user_info.get('country')
        vatarUrl = user_info.get('avatarUrl')

        user_info_dict = {
            'nickname': nickname,
            'gender': gender,
            'city': city,
            'province': province,
            'country': country,
            'vatarUrl': vatarUrl,
            'openid': openid
        }
        #if request.method == "POST":
        #   approach = request.POST.get('auth_approach')
        #if approach == 'wxapp':
        #   account = UserInfo.objects.create(user_info_dict)
        #   if not account:
        #       return False, ServerError('register_fail')
        print(user_info_dict)
        return user_info_dict
Esempio n. 5
0
def get_wxapp_userinfo(encrypted_data, iv, code):
    '''
        功能:
        通过encrypted_data, iv, code获取到微信用户的信息 user_info 和 session_key

        参数:
        encrypted_data  小程序端调用 wx.getUserInfo 获取 包括敏感数据在内的完整用户信息的加密数据
        iv 小程序端调用 wx.getUserInfo 获取 加密算法的初始向量
        code 小程序端调用 wx.login() 获取 临时登录凭证code 

        返回格式:
        user_info: {"openId":"xxxxxxx",.......}, session_key
    '''
    appid = 'wx15fa925381f617dd'
    secret = 'd3b2a8beb372b2165fee7e844d0282b0'
    api = WXAPPAPI(appid=appid, app_secret=secret)
    try:
        session_info = api.exchange_code_for_session_key(code=code)
    except OAuth2AuthExchangeError as e:
        print('111')
        print(e)
        # raise Unauthorized(e.code, e.description)
        return 401
    session_key = session_info.get('session_key')
    crypt = WXBizDataCrypt(appid, session_key)
    user_info = crypt.decrypt(encrypted_data, iv)
    return user_info, session_key
Esempio n. 6
0
def get_wxapp_userinfo(encrypted_data, iv, code):
    appid = 'wx4570344745a0bdc8'
    secret = 'cab82f01992be971923d56c3b0f86d45'
    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)
        abort(401)
    session_key = session_info.get('session_key')
    crypt = WXBizDataCrypt(appid, session_key)
    user_info = crypt.decrypt(encrypted_data, iv)
    return user_info, session_key
Esempio n. 7
0
 def decrypt(self, request):
     serializer = self.get_serializer(data=request.data)
     serializer.is_valid(raise_exception=True)
     wx_api = WXBizDataCrypt(
         appid=APP_ID, session_key=self.request.user.consumer.session_key)
     data = serializer.data
     try:
         result = wx_api.decrypt(data['encrypt_data'], data['iv'])
     except Exception as e:
         logger.exception("decrypt encrypt data error:{}".format(e))
         return Response(status=status.HTTP_400_BAD_REQUEST,
                         data={"encrypt_data": ['解密失败']})
     return Response(data=result, status=status.HTTP_200_OK)
def get_user_info(code, encryptedData, iv):
    # wx.login()接口success方法获得的响应,将响应中的code发送至第三方服务器,第三方服务器
    # 访问微信接口,获取session_key
    session_info = api.exchange_code_for_session_key(code=code)
    session_key = session_info.get('session_key')

    crypt = WXBizDataCrypt(WXAPP_APPID, session_key)

    # encryptedData 包含用户完整信息的加密数据
    # iv 加密算法的初始向量

    # 返回用户完整信息
    user_info = crypt.decrypt(encryptedData, iv)
    return user_info
Esempio n. 9
0
def onAppLogin(request):
    if request.method == "POST":
        code = request.POST.get("code")
        encrypted_data = request.POST.get("encryptedData")
        iv = request.POST.get("iv")

        api = WXAPPAPI(appid=WEIXIN_APPID, app_secret=WEIXIN_APPSECRET)
        session_info = api.exchange_code_for_session_key(code=code)

    # 获取session_info 后

    session_key = session_info.get('session_key')
    crypt = WXBizDataCrypt(WEIXIN_APPID, session_key)

    # encrypted_data 包括敏感数据在内的完整用户信息的加密数据
    # iv 加密算法的初始向量
    # 这两个参数需要js获取

    user_info = crypt.decrypt(encrypted_data, iv)
    openId = user_info.get("openId")

    try:
        user1 = myUser.objects.get(openId=openId)
        user1.loginDate = datetime.datetime.strftime(datetime.datetime.now(),
                                                     '%Y-%m-%d %H:%M:%S')
        user1.nickName = user_info.get('nickName')  # 保存昵称
        user1.header = user_info.get("avatarUrl")  # 保存头像
        user1.city = user_info.get("country") + ":::" + user_info.get(
            "province") + ":::" + user_info.get("city")  # 保存地区
        user1.save()
    except:
        user = myUser()
        user.openId = openId
        user.nickName = user_info.get('nickName')  # 保存昵称
        user.header = user_info.get("avatarUrl")  # 保存头像
        user.city = user_info.get("country") + ":::" + user_info.get(
            "province") + ":::" + user_info.get("city")  # 保存地区
        user.addDate = datetime.datetime.strftime(datetime.datetime.now(),
                                                  '%Y-%m-%d %H:%M:%S')
        user.six = user_info.get("gender")
        user.loginDate = datetime.datetime.strftime(datetime.datetime.now(),
                                                    '%Y-%m-%d %H:%M:%S')
        user.save()
        user1 = user

    token = jwt_login(user1, request, expire=60 * 60 * 24 * 7)
    user_info['token'] = token
    json_string = json.dumps(user_info)

    return HttpResponse(json_string)
Esempio n. 10
0
def get_wechat_user_info(app_id, secret, code, encrypted_data, iv):
    """
    :param app_id: 微信Appid
    :param secret: Secret
    :param code: 调用 wx.login 返回的code
    :param encrypted_data: 加密的用户数据
    :param iv: 解密秘钥
    :return: session_ley, user_info
    """
    session_info = get_wechat_session_info(app_id, secret, code)
    session_key = session_info.get('session_key')
    crypt = WXBizDataCrypt(app_id, session_key)
    # 解密得到 用户信息
    user_info = crypt.decrypt(encrypted_data, iv)
    return session_key, user_info
Esempio n. 11
0
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
Esempio n. 12
0
    def get(self, request):
        code = request.GET['code']
        encrypted_data = request.GET['encrypted_data']
        iv = request.GET['iv']
        session_info = api.exchange_code_for_session_key(code=code)

        # 获取session_info 后

        session_key = session_info.get('session_key')
        crypt = WXBizDataCrypt(APP_ID, session_key)

        # encrypted_data 包括敏感数据在内的完整用户信息的加密数据
        # iv 加密算法的初始向量
        # 这两个参数需要js获取
        user_info = crypt.decrypt(encrypted_data, iv)
        print(user_info)
        return Response('ok')
Esempio n. 13
0
def get_wxapp_userinfo(encrypted_data, iv, code):
    from weixin.lib.wxcrypt import WXBizDataCrypt
    from weixin import WXAPPAPI
    from weixin.oauth2 import OAuth2AuthExchangeError
    appid = 'wx73bdc6a0b793aa42'
    secret = 'd18f4ce06504cc4d7c2dbb0e06e03929'
    api = WXAPPAPI(appid=appid, app_secret=secret)
    try:
        # 使用 code  换取 session key
        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)
    print(user_info)
    return user_info
Esempio n. 14
0
def get_wxapp_userinfo(encrypted_data, iv, code):
    '''
    换取openid和session_key
    :param encrypted_data:
    :param iv:
    :param code:
    :return:
    '''
    api = WXAPPAPI(appid=APP_ID, app_secret=APP_SECRET)
    try:
        session_info = api.exchange_code_for_session_key(code=code)
    except OAuth2AuthExchangeError as e:
        return None
    session_key = session_info.get('session_key')
    crypt = WXBizDataCrypt(APP_ID, session_key)

    user_info = crypt.decrypt(encrypted_data, iv)
    return user_info
Esempio n. 15
0
def onAppLogin(request):
    if request.method == "POST":
        code = request.POST.get("code")
        encrypted_data = request.POST.get("encryptedData")
        iv = request.POST.get("iv")

        api = WXAPPAPI(appid=WEIXIN_APPID, app_secret=WEIXIN_APPSECRET)
        session_info = api.exchange_code_for_session_key(code=code)

    # 获取session_info 后

    session_key = session_info.get('session_key')
    crypt = WXBizDataCrypt(WEIXIN_APPID, session_key)

    # encrypted_data 包括敏感数据在内的完整用户信息的加密数据
    # iv 加密算法的初始向量
    # 这两个参数需要js获取

    user_info = crypt.decrypt(encrypted_data, iv)
    openId = user_info.get("openId")

    try:
        user1 = User.objects.get(username=openId)
    except:
        user = User()
        user.username = openId
        user.password = openId
        user.first_name = user_info.get('nickName')  # 保存昵称
        # user.date_joined = user_info.get("regtime")  # 保存注册时间
        user.email = user_info.get("avatarUrl")  # 保存头像
        user.last_name = user_info.get("country") + ":::" + user_info.get(
            "province") + ":::" + user_info.get("city")  # 保存地区
        user.save()
        user1 = user

    # import_string(jwt_settings['USER_TO_PAYLOAD'])
    token = jwt_login(user1, request, expire=60 * 60 * 24 * 7)
    user_info['token'] = token

    json_string = json.dumps(user_info)

    return HttpResponse(json_string)
Esempio n. 16
0
    def get(self):
        wxAPI = WXAPPAPI(appid=APP_ID, app_secret=APP_SECRET)

        print("string is: ", request.query_string)

        # BLACK MAGIC
        ##############################################
        # FIXME: Flask request parser takes + as space
        encrypted_data = request.args.get("encryptedData").replace(" ", "+")
        iv = request.args.get("iv").replace(" ", "+")
        ##############################################

        code = request.args.get("code")

        # print(data)
        # loginJSON = json.loads(data)
        # code = loginJSON["code"]
        # encrypted_data = loginJSON["encryptedData"]
        # iv = loginJSON["iv"]

        print("\ncode is : ", code)
        print("\ndata is : ", encrypted_data)
        print("\niv is : ", iv)

        session_info = wxAPI.exchange_code_for_session_key(code=code)

        # 获取session_info 后

        session_key = session_info.get('session_key')
        crypt = WXBizDataCrypt(APP_ID, session_key)

        # encrypted_data 包括敏感数据在内的完整用户信息的加密数据
        # iv 加密算法的初始向量
        # 这两个参数需要js获取
        try:
            user_info = crypt.decrypt(encrypted_data, iv)
            postJSON = stringParsing.userInfo2SQL(user_info)
            databaseOperations.replaceIntoDB("Users", postJSON)
        except:
            user_info = {"openId": session_info.get('openid')}
        return user_info
Esempio n. 17
0
 def validate(self, attrs):
     encrypted_data = attrs.get('encrypted_data')
     iv = attrs.get('iv')
     crypt = WXBizDataCrypt(settings.WX_APP_ID, self.user.access_token)
     try:
         user_info = crypt.decrypt(encrypted_data, iv)
     except Exception as e:
         raise ValidationError(e)
     profile, created = Profile.objects.update_or_create(
         user=self.user,
         defaults={
             'avatar_url': user_info.get('avatarUrl', ''),
             'city': user_info.get('city', ''),
             'country': user_info.get('country', ''),
             'gender': user_info.get('gender', ''),
             'language': user_info.get('language', ''),
             'nickname': user_info.get('nickName', ''),
             'province': user_info.get('province', ''),
         })
     logger.info('user: %s, profile: %s %s', self.user.id, profile.id,
                 'created' if created else 'updated')
     return {'profile': profile}
Esempio n. 18
0
 def post(self, request):
     params = get_parameter_dic(request)
     user_info = {}
     try:
         encryptedData = params['encrypteData'].replace(' ', '+')
         iv = params['iv'].replace(' ', '+')
         crypt = WXBizDataCrypt(
             get_app_config(params.get('name')).app_id,
             params.get('session_key'))
         user_info_raw = crypt.decrypt(encryptedData, iv)
         logger.info("user_info: {0}".format(user_info_raw))
         if user_info_raw:
             for k, v in self.fields.items():
                 user_info[k] = user_info_raw.get(v)
         user_info['is_auth'] = 'True'
         user = create_or_update_user_info(params.get('openid'), user_info)
         logger.info('用户授权成功' + str(request.user) + user.nick_name)
         return Response(
             {
                 'status':
                 1,
                 'mes':
                 '授权成功',
                 'user':
                 model_to_dict(
                     user,
                     fields=[
                         'nick_name', 'last_login', 'avatar_url', 'gender',
                         'city', 'province', 'country', 'login', 'unionId',
                         'company', 'restaurant', 'current_role',
                         'is_owner', 'is_client', 'is_manager'
                     ])
             },
             status=HTTP_200_OK)
     except:
         return Response({'status': 1, 'mes': '请检查参数'})
Esempio n. 19
0
def get_wx_user_info(app_id, secret, code, encrypted_data, iv):
    session_info = get_wechat_session_info(app_id, secret, code)
    session_key = session_info.get('session_key')
    crypt = WXBizDataCrypt(app_id, session_key)
    user_info = crypt.decrypt(encrypted_data, iv)
    return session_key, user_info
Esempio n. 20
0
encrypted_data = "EmFiCRyuktgZQbPovlIBe6ba3BH1y3kR/v4uR7+FynN1bU8O2bopG7xHfgHHQC/g8zeC62BAhGIG1pGn6RYSi9vQkXn1HbwTBHAmPmVkNohqAk6brplybBYp9WMSPn+gDwBuJRn/UhZKxvXl1U0MdF30ZQtcBzLKdRB+hsLiSTTviWEfPTFFB9V5IlEjoTquQdVAyzHFMi80Kmf976Ugj6BYGHpW1N5rkBC88DUbzF9lQF/rQG/on1b2rGaNB7/witT9t8SEp9RuJ4DZ5oKij14oXgI5Tkwv+50Gd13hxD1ASrpnF1mTOrHHZf8ETTuZJiYR6yIS2BTMJZeIj+tDxb36GAn5+AJACurexOk7w9w5bRQJhSQvV2fHC0x3e5aXtetHtcOiAzs6dPzgcH2DkCc/i/PPBlcPTiBPbU5WMICW0TDT6Q9GnP82rt7UFDRJilGDXWEgfTSyhUTBfgq94A=="
iv = "1u+JDApgTxfHzlVaKYnUpw=="

appid = WXAPP_ID
secret = WXAPP_SECRET
grant_type = GRANT_TYPE
api = WXAPPAPI(appid=appid, app_secret=secret)

api = api

session_info = api.exchange_code_for_session_key(code=code)
print(session_info)
session_key = session_info.get('session_key')
openid = session_info.get('openId')
print(session_key)
crypt = WXBizDataCrypt(appid, session_key)
print(crypt)
user_info = crypt.decrypt(encrypted_data, iv)
openid = user_info.get('openId')
nickname = user_info.get('nickname')
gender = user_info.get('gender')
language = user_info.get('language')
city = user_info.get('city')
province = user_info.get('province')
country = user_info.get('country')
vatarUrl = user_info.get('vatarUrl')
id = randint(1, 999999999999999)
SECRET_KEY = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCIE6a1NyEFe7qCDFrvWFZiAlY1ttE5596w5dLjNSaHlKGv8AXbKg/f8yKY9fKAJ5BKoeWEkPPjpn1t9QQAZYzqH9KNOFigMU8pSaRUxjI2dDvwmu8ZH6EExY+RfrPjQGmeliK18iFzFgBtf0eH3NAW3Pf71OZZz+cuNnVtE9lrYQIDAQAB"
# #session_key = 1
# user_info_dict = {'nickname': 'nickname', 'gender': 'gender', 'language': 'language', 'city': 'city',
#                   'province': 'province','country': 'country', 'vatarUrl': 'vatarUrl', 'id': 24324}
Esempio n. 21
0
def get_wechat_user_info(request):
    """

    :param request:
    :return:
    """
    data = json.loads(request.body)
    session_key = data.get('session_key')
    encrypted_data = data.get('encryptedData')
    iv = data.get('iv')

    crypt = WXBizDataCrypt(APP_ID, session_key)

    # encrypted_data 包括敏感数据在内的完整用户信息的加密数据
    # iv 加密算法的初始向量
    # 这两个参数需要js获取

    user_info = crypt.decrypt(encrypted_data, iv)
    watermark = user_info.pop('watermark')

    error_data = {'code': -1, 'data': {}, 'msg': 'not valid user info'}
    if not watermark:
        return JsonResponse(error_data)

    appid = watermark.get('appid')

    if appid != APP_ID:
        return JsonResponse(error_data)

    timestamp = watermark.get('timestamp', 0)
    user_info['timestamp'] = timestamp
    user_info['session_key'] = session_key

    openId = user_info.get('openId')

    if openId:
        wechat_users = WechatUserInfo.objects.filter(openId=openId,
                                                     is_valid=True)
        if wechat_users.count():
            # 已经存在
            wechat_user = wechat_users.first()
        else:
            # 首次用微信登录
            wechat_user = WechatUserInfo(**user_info)
            wechat_user.save()
            WechatUserInfo.create_user(wechat_user)
        user_profile = wechat_user.userprofile_set.get()
        user_profile_dict = user_profile.__dict__
        user_profile_dict['id'] = user_profile_dict['user_id']
        user_profile_dict.pop('_state')

        user_info.update(user_profile_dict)

    # 能够获取到openID,unionID,能够唯一识别是某一个微信用户了
    # 也就能够和本地系统的用户关联了
    resp_data = {
        'data': user_info,
        'code': 0,
    }

    return JsonResponse(resp_data)
Esempio n. 22
0
def get_decrypt_info(app_id, session_key, encrypted_data, iv):
    crypt = WXBizDataCrypt(app_id, session_key)
    _info = crypt.decrypt(encrypted_data, iv)
    return _info