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
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
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
def get_login_session(request): ##从客户端传来的登录信息获取user info if request.method == 'POST': code = request.POST['code'] #encryptedData = data['username'] #iv = data['password'] APP_ID = 'wx95f100449fab36b3' APP_SECRET = 'c0914c97100735c291193be50dbbebab' api = WXAPPAPI(appid=APP_ID, app_secret=APP_SECRET) session_info = api.exchange_code_for_session_key(code=code) # 获取session_info 后 session_key = session_info.get('session_key') openid = session_info.get('openid') #crypt = WXBizDataCrypt(WXAPP_APPID, session_key) # encrypted_data 包括敏感数据在内的完整用户信息的加密数据 # iv 加密算法的初始向量 # 这两个参数需要js获取 #user_info = crypt.decrypt(encryptedData, iv) #openid = user_info.get('openId', None) success_json = {'rtnCode' : 0, 'rtnMsg' : 'create order success', '3rd_session' : ''} if openid: trd_session = os.popen('head -n 80 /dev/urandom | tr -dc A-Za-z0-9 | head -c 168').read() ##生成168位随机数当作key time = current_datetime() sessionObj = SessionOpenId(trd_session=trd_session,session_key=session_key, openId=openid, time=time) sessionObj.save() print(openid) print(session_key) success_json['3rd_session'] = trd_session return HttpResponse(json.dumps(success_json), content_type="application/json")
def get_openid_session(code): api = WXAPPAPI(appid=APP_ID, app_secret=APP_SECRET) try: session_info = api.exchange_code_for_session_key(code=code) # 获取session_info logging.info( "get session_info from wechat server: {}".format(session_info)) status = 200 if "errcode" not in session_info else 400 resp_body = {'statusCode': status} except: resp_body = {'statusCode': 400} if status == 200: # 创建3_rd session thrid_session = str(uuid.uuid1()) logging.info("create thrid_session: {}".format(thrid_session)) resp_body["session"] = thrid_session # 设置session的到期时间,这边设置为30min session_info["expire_time"] = time.time() + 1800 SESSION_CACHE[thrid_session] = session_info return resp_body
def get_wx_app_token(app_id, secret,grant_type): api = WXAPPAPI(appid=app_id, app_secret=secret,grant_type=grant_type) try: get_token = api.client_credential_for_access_token() except OAuth2AuthExchangeError as e: raise e return get_token
def get_wx_session_info(app_id, secret, code): api = WXAPPAPI(appid=app_id, app_secret=secret) try: session_info = api.exchange_code_for_session_key(code=code) except OAuth2AuthExchangeError as e: raise e return session_info
def code2session_key(code): api = WXAPPAPI(appid=appid, app_secret=appsecret) try: return api.exchange_code_for_session_key(code) except Exception as e: #import pdb; pdb.set_trace() return e.__dict__
def wechat_login(request): if request.method == "POST": if request.body: received_data = json.loads(request.body.decode('utf-8')) code = received_data.get('code', None) logger.info("Code: {0}".format(code)) user_info = received_data.get('user_info', None) logger.info("user_info: {0}".format(user_info)) if code: api = WXAPPAPI(appid=GeneralConfig.wx_app_id, app_secret=GeneralConfig.wx_app_secret) try: session_info = api.exchange_code_for_session_key(code=code) openid = session_info.get('openid', None) logger.info("openid: {0}".format(openid)) if openid: queryset = Client.objects.filter(openid=openid) if queryset.exists(): account = queryset.first() else: account = create_user_by_openid(openid=openid) logger.info("account: {0}".format(account)) if account: if user_info: account.nickname = user_info['nickName'] account.gender = user_info['gender'] account.language = user_info['language'] account.city = user_info['city'] account.province = user_info['province'] account.country = user_info['country'] account.avatar = user_info['avatarUrl'] account.save() logger.info("Account saved: pk={0}".format( account.pk)) # 基于 Client 生成 jwt 的 token is_sync = False if account.nickname: is_sync = True return JsonResponse( { 'jwt': token_generate(payload={"pk": account.pk}), 'is_sync': is_sync }, status=status.HTTP_200_OK) return JsonResponse( {'err': '数据库连接失败'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR) return JsonResponse({'err': '提供的数据验证失败'}, status=status.HTTP_400_BAD_REQUEST) except Exception as err: return JsonResponse( {'err': str(err)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR) return JsonResponse({'err': '访问方式不对'}, status=status.HTTP_400_BAD_REQUEST)
def get_session_info(appcode, appid, appsecret): api = WXAPPAPI(appid=appid, app_secret=appsecret) session_info = api.exchange_code_for_session_key(code=appcode) session_key = session_info.get('session_key') open_id = session_info.get('openid') print("sessionid=%s openid=%s" % (session_key, open_id)) return (session_key, open_id)
def jscode2session(): api = WXAPPAPI(appid="wxfb39705a144d0144", app_secret="e8cd29ee68a6131d3bb7fdd98b5022f4") data = request.args code = data.get('jsCode') nickNmae = data.get('nickNmae') session_info = api.exchange_code_for_session_key(code=code) session_info['expires_in'] = '7200' openid = session_info.get("openid") user = Models.User.filter_by(wx_openid=openid).first() if not user: Models.User.create(openid, nickNmae) return jsonify({"result": True, "data": session_info})
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
def GetSessionKey(code): appid = settings.WXAPP_ID secret = settings.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') openid = session_info.get('openid') # print(openid) # print(session_key) return session_key, openid
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)
def post(self): APP_ID = current_app.config.get('APP_ID') APP_SECRET = current_app.config.get('APP_SECRET') wx_api = WXAPPAPI(appid=APP_ID, app_secret=APP_SECRET) args = parser.parse_args() code = args.get('code', None) if code: session_info = wx_api.exchange_code_for_session_key(code=code) session_key = session_info.get('session_key') openId = session_info.get('openid') return jsonify({'sessionKey': session_key, 'openId': openId}) else: return jsonify({'error': 'No 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
def get_login_session(request): ##从客户端传来的登录信息获取user info if request.method == 'POST': code = request.POST['code'] #encryptedData = data['username'] #iv = data['password'] api = WXAPPAPI(appid=APP_ID, app_secret=APP_SECRET) session_info = api.exchange_code_for_session_key(code=code) # 获取session_info 后 session_key = session_info.get('session_key') openid = session_info.get('openid') print(openid) print(session_key) success_json = { 'rtnCode': 0, 'rtnMsg': 'create user info success', 'trd_session': '' } trd_session = os.popen( 'head -n 80 /dev/urandom | tr -dc A-Za-z0-9 | head -c 168').read( ) ##生成168位随机数当作key time = current_datetime() print('aaaaaaaaaaaaaaaaaaaaaaa') print(time) try: sessionObj = SessionOpenId.objects.get(openId=openid) except: if openid: #trd_session = os.popen('head -n 80 /dev/urandom | tr -dc A-Za-z0-9 | head -c 168').read() ##生成168位随机数当作key sessionObj = SessionOpenId(trd_session=trd_session, session_key=session_key, openId=openid, time=time) sessionObj.save() success_json['trd_session'] = trd_session return HttpResponse(json.dumps(success_json), content_type="application/json") else: # sessionObj.update(trd_session=trd_session) sessionObj.trd_session = trd_session sessionObj.time = time sessionObj.save() success_json['trd_session'] = trd_session success_json['rtnMsg'] = 'Update user info success' return HttpResponse(json.dumps(success_json), content_type="application/json")
def weixin_login(request): code = request.POST['code'] nickname = request.POST['nickname'] avatarurl = request.POST['avatarurl'] if code: try: api = WXAPPAPI(appid=APP_ID, app_secret=APP_SECRET) session_info = api.exchange_code_for_session_key(code=code) session_key = session_info.get('session_key') openid = session_info.get('openid') if session_key: try: auth = VRAuth.objects.get(openid=openid) if auth: auth.wxcover = avatarurl auth.wxname = nickname auth.save() else: auth = VRAuth.objects.create( username=nickname, password=make_password('123456'), wxname=nickname, wxcover=avatarurl, openid=openid) except VRAuth.DoesNotExist: auth = VRAuth.objects.create( username=nickname, password=make_password('123456'), wxname=nickname, wxcover=avatarurl, openid=openid) result = { 'status': 0, 'msg': u'登录成功', 'code': code, 'session_key': session_key, 'openid': openid } return HttpResponse(json.dumps(result), content_type='application/json') else: result = {'status': -1, 'msg': u'无法获取session_key,登录失败'} return HttpResponse(json.dumps(result), content_type='application/json') except Exception, e: result = {'status': -1, 'msg': u'code参数不正确,登录失败.' + e.message} return HttpResponse(json.dumps(result), content_type='application/json')
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
def create(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) wx_api = WXAPPAPI(appid=APP_ID, app_secret=APP_SECRET) data = serializer.data try: session_info = wx_api.exchange_code_for_session_key(data['code']) except Exception as e: logger.warning("exchange code error:{}".format(e)) return Response(data={"code": ["登录失败"]}, status=status.HTTP_400_BAD_REQUEST) if session_info: openid = session_info['openid'] user, _ = User.objects.get_or_create( defaults={"password": make_password(PASSWORD)}, username=openid) user_profile, _ = Consumer.objects.update_or_create( user=user, defaults={ 'openid': openid, 'session_key': session_info['session_key'], 'user_name': data['user_name'], "sex": data['sex'], "avatar_url": data['avatar_url'] }) if data.get("sell_user"): # if data.get("recommend_id") and not user_profile.sell_user: sell_user = Consumer.objects.get(id=data.get("sell_user")) user_profile.sell_user = sell_user user_profile.save() logger.info("user_id:{}, sell_user_id:{}".format( user_profile, sell_user)) serializer = JSONWebTokenSerializer(data={ "username": openid, "password": PASSWORD }) serializer.is_valid(raise_exception=True) user = serializer.object.get("user") or request.user token = serializer.object.get("token") response_data = jwt_response_payload_handler(token, user, request) return Response(response_data, status=status.HTTP_200_OK) return Response(data={"code": ['认证异常']}, status=status.HTTP_400_BAD_REQUEST)
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)
def post(self, request): user_info = dict() code = request.data.get('code') logger.info("Code: {0}".format(code)) user_info_raw = request.data.get('user_info', {}) if isinstance(user_info_raw, str): user_info_raw = json.loads(user_info_raw) if not isinstance(user_info_raw, dict): user_info_raw = {} logger.info("user_info: {0}".format(user_info_raw)) if code: api = WXAPPAPI(appid=settings.WX_APP_ID, app_secret=settings.WX_APP_SECRET) try: session_info = api.exchange_code_for_session_key(code=code) except OAuth2AuthExchangeError: session_info = None if session_info: openid = session_info.get('openid', None) if openid: if user_info_raw: for k, v in self.fields.items(): user_info[k] = user_info_raw.get(v) user = create_or_update_user_info(openid, user_info) if user: token = JfwTokenObtainPairSerializer.get_token( user).access_token return Response( { 'jwt': str(token), 'user': model_to_dict(user, fields=[ 'company', 'restaurant', 'current_role', 'is_owner', 'is_client', 'is_manager' ]) }, status=HTTP_200_OK) return Response({'jwt': None, 'user': {}}, status=HTTP_204_NO_CONTENT)
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
def get_user_openid(): # POST请求数据 # encrypted_data = request.form['encryptedData'] # iv = request.form['iv'] code = request.form['code'] # app配置秘钥 appid = configs.wxapp['appid'] app_secret = configs.wxapp['appsecret'] if not code: resp = make_response('Weixin Code Error', 502) return resp if not appid or not app_secret: resp = make_response('Server Internal Error', 500) return resp api = WXAPPAPI(appid= appid, app_secret= app_secret) session_info= api.exchange_code_for_session_key(code=code) if not session_info: resp = make_response('Weixin API Error', 502) return resp if not isinstance(session_info,dict): resp = make_response('Session Key Error', 500) return resp open_id = session_info.get('openid') # session_key = session_info.get('session_key') # crypt = WXBizDataCrypt(appid, session_key) # user_info = crypt.decrypt(encrypted_data, iv) # resp = make_response(jsonify(session_info),) # return resp is_open_id_in_dase = True if UserInfo.query.filter_by(open_id=open_id).first() else False if not is_open_id_in_dase: resp = make_response(jsonify(session_info), 401) return resp else: resp = make_response(jsonify(session_info), 201) return resp
def wechat_auth(request): """ :param request: :return: """ data = json.loads(request.body) code = data.get('code') api = WXAPPAPI(appid=APP_ID, app_secret=APP_SECRET) session_key = '' if code: session_info = api.exchange_code_for_session_key(code=code) # 获取session_info 后 session_key = session_info.get('session_key') resp_data = { 'data': { 'session_key': session_key, }, 'msg': 'hello world', 'code': 0, } return JsonResponse(resp_data)
from weixin import WXAPPAPI from weixin.lib.wxcrypt import WXBizDataCrypt from django.conf import settings wx_api = WXAPPAPI(appid=settings.WEIXIN["APP_ID"], app_secret=settings.WEIXIN["APP_SECRET"]) def get_session_info(code): session_info = wx_api.exchange_code_for_session_key(code=code) return session_info
import time import jwt from random import randint code = "003ArLh01OFWh22zW8i01XTGh01ArLhB" WXAPP_ID = 'wxc066d762e4dd7357' WXAPP_SECRET = '7bba3ab00edb1c153139f3d75a0020ed' WXAPP_TOKE = '' GRANT_TYPE = 'authorization_code' 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')
from weixin import WXAPPAPI from weixin.lib.wxcrypt import WXBizDataCrypt from custom_user.models import User WXAPP_APPID = '' WXAPP_SECRET = '' api = WXAPPAPI(appid=WXAPP_APPID, app_secret=WXAPP_SECRET) 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 def verify_wx(encryptedData, iv, code): user_info = get_user_info(encryptedData, iv, code) openid = user_info.get('openId', 'None') if openid:
#! -*- coding: utf-8 -*- from os import environ from datetime import datetime from weixin import WXAPPAPI from weixin.helper import smart_bytes appid = environ.get("WXAPP_APPID", "appid") secret = environ.get("WXAPP_SECRET", "secret") api = WXAPPAPI(appid=appid, app_secret=secret, grant_type="client_credential") token = api.client_credential_for_access_token().get("access_token") print(token) # send template template_id = "" openid = "" form_id = "0e282a55bc674d9abf9aa2e33eed2768" imageId = "" json_body = { "touser": openid, "template_id": template_id, "page": "/pages/history/detail/detail?id=%s" % imageId, "form_id": form_id, "data": { "keyword1": { # 时间 "value": datetime.now().strftime("%Y-%m-%d %H:%M:%S") }, "keyword2": { # 备注
def post(self, request): params = get_parameter_dic(request) name = params.get('name') code = params.get('code') app = get_app_config(name) if code: api = WXAPPAPI(appid=app.app_id, app_secret=app.secret) try: session_info = api.exchange_code_for_session_key(code=code) except OAuth2AuthExchangeError: session_info = None if session_info: openid = session_info.get('openid', None) session_key = session_info.get('session_key', None) user = create_or_update_user_info(openid, None) logger.info('用户id:{}'.format(user.id)) try: deal_ip(request, user) except: logger.info("分析ip地址失败", user.id) record_time(user) token = TokenObtainPairSerializer.get_token(user).access_token login_record = RecordLogin.objects.create(user=user, game=app) login_record.save() try: GameInfo.objects.get(user_id=user, game_id=app) except: GameInfo.objects.create(user_id=user, game_id=app) if user.is_auth is True: logger.info('用户登录成功' + user.nick_name) user = model_to_dict( user, fields=[ 'nick_name', 'last_login', 'avatar_url', 'gender', 'city', 'province', 'country', 'login', 'id', 'company', 'restaurant', 'current_role', 'is_owner', 'is_client', 'is_manager', 'openid' ]) else: user = {'openid': openid, 'session_key': session_key} logger.info('用户登录成功' + openid) return Response({ 'status': 1, 'jwt': str(token), 'user': user }, status=HTTP_200_OK) # if openid: # try: # user = MyUser.objects.get(openid=openid) # except: # try: # encryptedData = \ # params.get('encryptedData').replace(' ', '+') # iv = \ # params.get('iv').replace(' ', '+') # except: # return Response({'error': '缺少解密参数!'}) # crypt = WXBizDataCrypt(app.app_id, 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 = create_or_update_user_info(openid, user_info) # game_info = GameInfo.objects.create(user_id=user, game_id=app) # if user: # token = TokenObtainPairSerializer.get_token(user).access_token # record_time(user) # # response = Response() # # response.set_cookie('app',app.id) # # logger.info('cookie:{}'.format(request.COOKIES)) # return Response( # { # 'status': 1, # 'jwt': str(token), # 'user': model_to_dict( # user, # fields=[ # 'nick_name', 'last_login', 'avatar_url', 'gender', # 'city', 'province', 'country', 'login', # 'company', 'restaurant', 'current_role', # 'is_owner', 'is_client', 'is_manager' # ]) # }, # status=HTTP_200_OK) else: logger.info('用户登录失败') return Response({'status': 0, 'mes': 'code失效!'}) return Response({ 'status': 0, 'mes': '没有信息' }, status=HTTP_204_NO_CONTENT)