(二十五)微信小程序的登陆 实际逻辑
在微信小程序中我们需要有一个openid来做临时的‘认证’
小程序端
<input placeholder="请输入手机号" bindinput="inputPhone" value="{{phone}}"></input> <button open-type="getUserInfo" bindgetuserinfo="doSubmit" >登录</button>
我们不用但是可以写上
data: { phone: null }, inputPhone: function (e) { this.setData({ phone: e.detail.value }) }, doSubmit: function (e) { // 先获取 openid wx.login({ wx.login 可以获取一个临时的凭证 success: (result) => { // 获取一个临时凭证result.code(只能用一次/5分钟) wx.request({ url: 'http://127.0.0.1:8002/login/', data: { phone: this.data.phone, wx_code: result.code }, method: 'POST', dataType: 'json', responseType: 'text', success: (res) => { console.log('登录成功'); } }) } }) },
后端接口
# 用户表 class UserInfo(models.Model): """ 用户表 """ phone = models.CharField(verbose_name='手机号',max_length=32) token = models.CharField(verbose_name='Token',max_length=32) openid = models.CharField(verbose_name='微信唯一标识',max_length=32)
# url from django.conf.urls import url from django.contrib import admin from app01.views import login urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^login/', login.LoginView.as_view()), ]
# views.py
1. 根据传过来的phone去数据库中查找,有就更新,没有就创建
2. 创建的时候要phone(已经传过来了),token我们自己先uuid测试,openid是个关键 需要去一个网址获取【下面的网址】
from app01 import models from rest_framework.views import APIView from rest_framework.response import Response import requests import uuid # Create your views here. class LoginView(APIView): def post(self,request,*args,**kwargs): phone = request.data.get('phone') wx_code = request.data.get('wx_code') # openid的获取:需要拿着wx_code去微信申请 # https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/login.html info = { 'appid': "你自己的微信小程序id", # 微信小程序 'secret': "你自己的微信小程序的key", # 微信小程序 'js_code': wx_code, 'grant_type': "authorization_code", } result = requests.get(url='https://api.weixin.qq.com/sns/jscode2session', params=info) openid = result.json()['openid'] exists = models.UserInfo.objects.filter(phone=phone).exists() token = str(uuid.uuid4()) if not exists: models.UserInfo.objects.create( phone=phone, token=token, openid=openid ) else: models.UserInfo.objects.filter(phone=phone).update(token=token, openid=openid) return Response({'token':token})
前端
success: (res) => { console.log('登录成功'); // 登陆成功之后 可以有一大堆操作,放在全局或者本地 }
这里我们就不在赘述