无论是用微信开发者工具还是uniapp开发小程序,基本上所有情况之下,登录是必不可少的。
简洁明了,直接开始
1.个人资料的获取
现在通过 uni.getUserProfile 获取的个人信息基本上回返回 灰色头像及" 微信用户",要想获得用户的微信头像和昵称,我们可以换个方法(这里但指头像和昵称,不含性别等其他)
头像
<button class="avatar-wrapper" open-type="chooseAvatar" @chooseavatar="onChooseAvatar" style="width: 120rpx;">
<view class="avatar" style="width: 120rpx; height: 120rpx; margin-left: -30rpx;">
<image class="avatar-img" :src="avatarUrl" style="width: 100%; height: 100%;"></image>
</view>
</button>
data() {
return {
avatarUrl:"",
nickName: '' ,
UserInfo:[],
};
},
//选择头像函数
onChooseAvatar(e) {
console.log('微信头像信息', e)
// 将数据赋值
const { avatarUrl } = e.detail
this.avatarUrl = avatarUrl
},
昵称
<view class="">
<input type="nickname" placeholder="获取昵称" @focus="onNicknameInput"/>
</view>
onNicknameInput 函数是为了获取到微信的昵称并保存,它和获取到的头像
2.关联unicloud ,并创建一个名为 user 的表
详细教程移步
https://blog.csdn.net/qq_40531408/article/details/126068789
3.创建login云函数
'use strict';
//小程序的AppID 和 AppSecret
const appid = "********************"
const secret = "********************"
// 创建user数据表实例
const db = uniCloud.database()
const user = db.collection('user')//你的表名
// 生成token和校验token公共模块
const {getToken,verifyToken} = require('wx-common')
exports.main = async (event, context) => {
//获取用户openid和session_key
const res = await uniCloud.httpclient.request('https://api.weixin.qq.com/sns/jscode2session', {
method: 'GET',
data: {
appid: appid,
secret: secret,
js_code: event.code,// 客户端传递过来的code
grant_type: 'authorization_code'
},
dataType: 'json'
})
//判断请求用户openid和session_key是否成功
if (res.status === 200) {
//成功返回的openid和session_key
const wx_openid = res.data.openid
const wx_session_key = res.data.session_key
// 生成token
const token = getToken(wx_openid)
//查询数据库判断用户是否已经注册 根据openid查找
const res_user = await user.where({
openid: wx_openid
}).get()
//用户未注册存储用户信息
if (res_user.data && res_user.data.length === 0) {
user.add({
avatarUrl: event.userinfo.avatarUrl,
nickName: event.userinfo.nickName,
gender: event.userinfo.gender,
openid: wx_openid,
session_key: wx_session_key,
mobile:"",
token:token
})
} else {
//用户已经存在更新token和session_key
user.where({
openid: wx_openid
}).update({
session_key: wx_session_key,
token:token
})
}
//将需要的个人信息返回到客户端例如:头像 昵称 等
return user.where({
openid: wx_openid
}).field({
avatarUrl: true,
gender: true,
nickName: true,
mobile:true,
token:true,
}).get()
} else {
//获取用户openid和session_key失败响应客户端
return {
msg: '获取微信服务失败',
code: 500
}
}
};
4.在cloudfunctions目录下的common下新建新建公共模块wx-common
在wx-common目录下 npm i jsonwebtoken 下载依赖
下载后如图所示
5.在wx-common index.js 文件中
// 生成token方法
const jwt = require('jsonwebtoken')
// 密匙
const secret = '***'
//生成token
function getToken(value) {
// sign(加密数据,加密辅助,过期时间(单位/s))
return jwt.sign({value}, secret, {expiresIn: 10800});
}
//解密token
function verifyToken(token) {
try {
return jwt.verify(token,secret)
}catch(e) {
return false
}
}
//导出方法
module.exports = {
getToken,
verifyToken
}
6.在需要使用公共模块的云函数右键管理公共模块或扩展依赖
点击确定并上传部署
7.新建login 页面
<template>
<view>
<!--pages/about/about.wxml-->
<!-- 获取用户头像或昵称 -->
<view class="v1" style="margin-top: 100rpx;">
<view class="v2" style="margin-top: 40rpx;">
<button class="avatar-wrapper" open-type="chooseAvatar" @chooseavatar="onChooseAvatar" style="width: 120rpx;">
<view class="avatar" style="width: 120rpx; height: 120rpx; margin-left: -30rpx;">
<image class="avatar-img" :src="avatarUrl" style="width: 100%; height: 100%;"></image>
</view>
</button>
<view class="" style="margin-left: 150rpx; margin-top: 70rpx;display: flex;">
<view class="" style="width: 100rpx;margin-top:36rpx ; margin-left: 11rpx;">
昵称
</view>
<view class="">
<input type="nickname" placeholder="获取昵称" @focus="onNicknameInput"/>
</view>
</view>
<view class="denglu">
<button open-type="getUserInfo" @getuserinfo="getUserInfo" >登录</button>
</view>
</view>
</view>
</view>
</view>
</template>
//
onNicknameInput(e){
console.log(e);
this.nickName= e.detail.value
},
getUserInfo() {
uni.showModal({
title:"使用微信一键登录",
showCancel:true,
cancelColor:"#000000",
confirmColor:"#42b983",
success:(success) => {
if(success.confirm) {
uni.showLoading({
title:'登录中...'
})
uni.getUserProfile({
desc:'获取用户信息,进行登录',
success: (res) => {
//调用登录函数
this.UserInfo=res.userInfo
if(this.UserInfo.nickName=="微信用户")
{
this.UserInfo.nickName=this.nickName,
this.UserInfo.avatarUrl=this.avatarUrl
}
if(this.UserInfo.nickName!="微信用户")
{
this.getLogin(this.UserInfo)
}
}
})
}
if(success.cancel) {
uni.showToast({
title: '用户取消登录!',
icon:'none',
duration: 2000
});
}
}
})
},
// 微信登录
getLogin(userInfo) {
uni.login({
provider:'weixin',
success: (res) => {
// 调用云函数
uniCloud.callFunction({
name:'login', // 云函数名称
data:{ // 需要传递给云函数的参数
userinfo:userInfo,
code:res.code
}
}).then(ress => {
console.log(ress);
console.log();
//判断是否返回了用户数据
if(ress.result.affectedDocs != 0) {
console.log(ress.result.data);
//存储用户信息
// 存储token
uni.setStorage({
key:'Token',
data:ress.result.data[0].token
})
// token
// 设置默认的过期时长,例如3小时
const defaultExpiresIn = 3 * 3600 * 1000;
uni.setStorageSync("expiresIn", new Date().getTime() + defaultExpiresIn);
uni.setStorage({
key:'UserInfo',
data:this.UserInfo
})
uni.showToast({
title:'登录成功',
icon:'none',
duration: 2000
});
setTimeout(() => {
// 跳转首页
uni.switchTab({
url:'/pages/first/first'
})
},2000)
}else {
uni.showToast({
title:'登录失败',
icon:'none',
duration: 2000
});
}
uni.hideLoading()
}).catch(err => {
console.log(err);
uni.showToast({
title:'登录失败',
icon:'none',
duration: 2000
});
})
}
})
},
在传递UserInfo对象时,我将获取到的灰色头像和统一昵称重新设置为获取的微信头像和昵称,这个方法看起来不大聪明的样子,但作为白白的我只能想到这个方法了(可怜兮兮)