文章目录
- 涉及到的微信官方文档
- login.wxml
- 效果
- login.wxml
- login.js
- 效果
- login.js
- util.js
- 后端(使用django)
- urls.py
- views.py
流程:
1. wx.getUserProfile() 会调出获取用户微信的页面
2. 当用户点击“允许”后,wx.login() 带着code去后端通过向微信发起请求获取用户的openid,最后登录
涉及到的微信官方文档
https://api.weixin.qq.com/sns/jscode2session
wx.login
wx.getUserProfile
微信小程序查看AppID或重置AppSecret
login.wxml
效果
login.wxml
<van-button round slot="button" size="large" color="#008800" bind:tap="wechat_login">微信登录</van-button>
login.js
效果
wx.getUserProfile()会调出获取用户微信的页面
login.js
wechat_login(){//getUserProfile()-》wx.login获取到该微信用户的openid,之后去数据库中查询是否有该openid的用户,有就该用户登录成功,token赋值,之后跳转首页wx.getUserProfile({desc: '用于微信登录', // 声明获取用户个人信息后的用途,后续会展示在弹窗中,请谨慎填写success: (res) => {//用户点击“允许”app.globalData.wechatUserInfo=res.userInfo//去后端获取用户的openid,并与该账号密码绑定,最后登录util.getUserOpenid()}})},
util.js
function getUserOpenid() {//获取该微信号的openidwx.login({success (res) {if (res.code) {//发起网络请求wx.request({url: 'http://127.0.0.1:8000/api/getWechatId/',method: "GET",data: {code: res.code},success:resquest=>{console.log("request")console.log(resquest.data)if(resquest.data.status==200){app.globalData.userInfo=resquest.data.resultsconsole.log("openid")console.log(app.globalData.userInfo.openid)wx.showToast({title: resquest.data.msg,icon: 'success'})//登录成功,跳转首页wx.switchTab({url: '/pages/index/index',})}else{wx.showToast({title: "登录失败",icon: 'error'})}}})} else {console.log('登录失败!' + res.errMsg)}}})
}
后端(使用django)
urls.py
urlpatterns = [path('api/getWechatId/',WechatView.as_view())
]
views.py
class WechatView(APIView):authentication_classes = [RecordAuthentication, ] # 权限校验def get(self, request):code = request.query_params.get("code")print("code " + code)url = "https://api.weixin.qq.com/sns/jscode2session"url += "?appid=xxx" # 换成自己的appidurl += "&secret=xxx" # 换成自己的appSecreturl += "&js_code=" + codeurl += "&grant_type=authorization_code"url += "&connect_redirect=1"import requests, jsonr = requests.get(url) # 向微信发送请求,获得微信用户的openidkey = json.loads(r.text) # 转成json格式openid = key.get("openid") # openid是该用户在该小程序中的唯一标识print("openid " + openid)if not request.user:# 选择微信登录# 根据openid到user表中查出该用户,如果没有,为其创建一个用户user=User.objects.filter(openid=openid).first()token = str(uuid.uuid4())if(user):# 存在该用户user.token=tokenuser.save()user_serializer = UserModelSerializer(user)else:# 没有此用户user.username="momo"user.password="123456"user.openid=openiduser.token = tokenuser.save()user_serializer = UserModelSerializer(user)return Response({'status': '200','msg': '登录成功!','results': user_serializer.data})else:# 登录状态下实现绑定微信userid=request.user.iduser=User.objects.filter(id=userid).first()user.openid=openiduser.save()return Response({'status': '200','msg': '绑定成功!','openid': openid})