1. 创建uniapp的uniCloud数据库,绑定云数据库。参考https://uniapp.dcloud.io/uniCloud/concepts/space。
2. uniapp微信小程序中授权的登陆。
2.1 创建tool.js文件:
export default{
getTokenValue(options) { //1.获取用户的token
let {
success,
fail,
complete
} = options
var _this = this;
uni.login({ //获取微信用户的code值
provider: 'weixin',
success(r) {
if (r.code) {
uni.getUserInfo({ //获取微信用户的encryptedData,iv值
provider: 'weixin',
success(res) {
let data={
code: r.code,
signature: res.signature,
encrypted_data: res.encryptedData,
iv: res.iv,
userInfo:res.userInfo
}
uniCloud.callFunction({
name: 'ace-login',
data: data,
}).then((result) => {
console.log('微信授权成功',result);
if(result.success && result.result && result.result.status===1){
_this.uniSetStorage('token',result.result.token)
_this.uniSetStorage('userInfo',result.result.userInfo)
complete && complete()
success ? success() : false
}else{
_this.uniShowToast({
title: "用户登陆失败",
icon: "none"
})
}
}).catch((err) => {
console.log(err);
})
},
fail:(err)=>{
_this.uniShowToast({
title: "获取用户信息失败",
icon: "none"
})
complete ? complete() : false
}
});
} else {
_this.uniShowToast({
title: "获取微信登录login的code失败!",
icon: "none"
})
complete ? complete() : false
}
}
});
},
uniShowToast(options) { //2.提升框
let {
title,
icon,
mask,
duration,
image
} = options
uni.showToast({
title: title,
icon: icon ? icon : "success",
image: image ? image : "",
mask: mask ? mask : false,
duration: duration ? duration : 1500,
complete: () => {
setInterval(() => {
uni.hideToast();
}, 30000)
}
});
},
isGetLocation(type = "scope.userInfo", success = null, fail = null) { //3. 判断是否授权
let _this = this
uni.getSetting({
success(res) {
if (!res.authSetting[type]) {
_this.getAuthorizeInfo(type, success, fail)
} else {
if(type==='scope.getUserInfo'){
if(_this.uniGetStorage("token")){
success ? success() : false
}else{
_this.getTokenValue({
success:()=>{
success ? success() : false
}
})
}
}else{
success ? success() : false
}
}
}
});
},
getAuthorizeInfo(type, success, fail) { //4. 进行授权
let _this = this
uni.authorize({
scope: type,
success() {
if(type==='scope.getUserInfo'){
if(_this.uniGetStorage("token")){
success ? success() : false
}else{
_this.getTokenValue({
success:()=>{
success ? success() : false
}
})
}
}else{
success ? success() : false
}
},
fail() {
if (fail) {
fail()
} else {
_this.uniShowToast({
title: "你拒绝了授权!",
icon: "none"
})
console.log("你拒绝了授权")
}
}
})
},
}
2.2 main.js中全局引入tool.js文件:
import tool from "@/common/js/tool.js"
Vue.prototype.$tool=tool
2.3 在my.vue页面中使用:
onLoad(){
this.init()
},
methods:{
init(){
this.$tool.isGetLocation('scope.userInfo',()=>{
//已经授权,获取用户信息成功
},()=>{
//没有授权,需要主动授权
})
},
}
2.4 主动授权页面:
{{status==='userInfo'?'授权登陆':'授权地址位置'}}
请授权头像等信息,以便我们为您提供更好的服务
3. uniapp微信小程序中uniCloud处理云数据库登陆:
在cloudfunctions-aliyun下创建ace-login/index.js文件。
下载jwt-simple第三方库引入jwt.js。
在ace-login/index.js中:
const crypto = require('crypto') //node自带模块
const jwt = require('./jwt.js') //引入jwt-simple中的
const loginConfig = {
AppId: '', //微信小程序AppId
AppSecret: '' //微信小程序AppSecret
}
const passSecret = 'abc' //用于用户数据库密码加密的密钥,使用一个比较长的随机字符串即可
const tokenExp = 8000000
const db = uniCloud.database()
exports.main = async (event, context) => {
let data = {
appid: loginConfig.AppId,
secret: loginConfig.AppSecret,
js_code: event.code,
grant_type: 'authorization_code'
}
const res = await uniCloud.httpclient.request('https://api.weixin.qq.com/sns/jscode2session', { //向微信发送请求获取用户openId
method: 'GET',
data,
dataType: 'json'
})
const success = res.status === 200 && res.data && res.data.openid
if (!success) {
return {
status: -2,
msg: '从微信获取登录信息失败'
}
}
const {
openid
} = res.data
let openidObj = {
openid
}
const userInfo = event.userInfo
let tokenSecret = crypto.randomBytes(16).toString('hex'),
token = jwt.encode(openidObj, tokenSecret)
const userInDB = await db.collection('ace-user').where({
openid
}).get()
let userUpdateResult
if (userInDB.data && userInDB.data.length === 0) {
userUpdateResult = await db.collection('ace-user').add({ //没有该用户就新增
...openidObj,
...userInfo,
tokenSecret,
exp: Date.now() + tokenExp
})
} else {
userUpdateResult = await db.collection('ace-user').doc(userInDB.data[0]._id).set({ //有该用户就修改
...openidObj,
...userInfo,
tokenSecret,
exp: Date.now() + tokenExp
})
}
if (userUpdateResult.id || userUpdateResult.updated === 1) {
const userVal = await db.collection('ace-user').where({
openid
}).get()
return {
status: 1,
token,
userInfo:userVal.data[0], //该用户的信息
msg: '登录成功'
}
}
return {
status: -1,
msg: '微信登录'
}
}