django-微信小程序登录
Posted zyxzyy
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了django-微信小程序登录相关的知识,希望对你有一定的参考价值。
小程序登录逻辑
前端通过调用wx.login()获取code, 将code和用户基本信息发送到后端,后端通过request.get向微信服务器发送get请求获取用户openid和session_key,手动添加jwt-token,利用jwt自动校验用户是否登录
小程序前端触发login事件
<button class="confirm-btn" open-type="getUserInfo" bindgetuserinfo="login" wx:if="{{regFlag==false}}">授权登录</button>
js代码:login事件接收的参数 e.detail.userInfo保存了用户基本信息,调用wxlogin方法获取用户的code,发送到后端
login:function( e ){ var that = this; if( !e.detail.userInfo ){ app.alert( { ‘content‘:‘登录失败,请再次点击~~‘ } ); return; } var data = e.detail.userInfo; wx.login({ success:function( res ){ if( !res.code ){ app.alert( { ‘content‘:‘登录失败,请再次点击~~‘ } ); return; } data[‘code‘] = res.code; wx.request({ url:app.buildUrl( ‘/member/login‘ ), header:app.getRequestHeader(), method:‘POST‘, data:data, success:function( res ){ if( res.data.code != 200 ){ app.alert( { ‘content‘:res.data.msg } ); return; } app.setCache( "token",res.data.data.token ); that.goToIndex(); } }); } }); }
后端代码:
用户模型类继承自django自带的用户模型,新增三个用户信息字段
class User(AbstractUser): USER_GENDER_CHOICES = ( (0, ‘女‘), (1, ‘男‘), )
sex = models.SmallIntegerField(choices=USER_GENDER_CHOICES, default=1, verbose_name="性别") avatar = models.CharField(max_length=50, default="", null=True, blank=True, verbose_name="头像") openid = models.CharField(max_length=64, db_index=True, verbose_name=‘openid‘) class Meta: db_table = ‘tb_users‘ verbose_name = ‘用户‘ verbose_name_plural = verbose_name
类视图:发送请求获取用户的openid,用openid来查询是否用户已经存在,不存在创建信的用户,统一手动签发jwt_token返回
class WechatLoginView(APIView): """ 微信登录逻辑 """ def post(self, request): # 前端发送code到后端,后端发送网络请求到微信服务器换取openid code = request.data.get(‘code‘) if not code: return Response({‘message‘: ‘缺少code‘}, status=status.HTTP_400_BAD_REQUEST) url = "https://api.weixin.qq.com/sns/jscode2session?appid={0}&secret={1}&js_code={2}&grant_type=authorization_code" .format(settings.APP_ID, settings.APP_KEY, code) r = requests.get(url) res = json.loads(r.text) openid = res[‘openid‘] if ‘openid‘ in res else None # session_key = res[‘session_key‘] if ‘session_key‘ in res else None if not openid: return Response({‘message‘: ‘微信调用失败‘}, status=status.HTTP_503) # 判断用户是否第一次登录 try: user = User.objects.get(openid=openid) except Exception: # 微信用户第一次登陆,新建用户 username = request.data.get(‘nickname‘) sex = request.data.get(‘sex‘) avatar = request.data.get(‘avatar‘) user = User.objects.create(username=username, sex=sex, avatar=avatar) user.set_password(openid) # 手动签发jwt jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER payload = jwt_payload_handler(user) token = jwt_encode_handler(payload) resp_data = { "user_id": user.id "username": user.username, "avatar": user.avatar, "token": token, } return Response(resp_data)
补充:jwt的配置
REST_FRAMEWORK = { ‘DEFAULT_AUTHENTICATION_CLASSES‘: ( ‘rest_framework_jwt.authentication.JSONWebTokenAuthentication‘, ‘rest_framework.authentication.SessionAuthentication‘, ‘rest_framework.authentication.BasicAuthentication‘, ), } JWT_AUTH = { # 指明token的有效期 ‘JWT_EXPIRATION_DELTA‘: datetime.timedelta(days=7), }
以上是关于django-微信小程序登录的主要内容,如果未能解决你的问题,请参考以下文章