环境配置
- 配置uni-config-center\uni-id\config.json,
"mp-weixin": {
"oauth": {
"weixin": {
"appid": "wxefc8a1dc32c07d79",
"appsecret": "185cf5a667d964a0073342d5af596d11"
}
}
- 创建云函数wxLogin,并且右键管理公共模块依赖—“uni-id”
- manifest.json—>app模块配置—>OAuth(登录鉴权)—>微信登录,设置AppID和AppSecret
- manifest.json—>微信小程序配置—>微信小程序AppID(ES6转ES5)
- 在HBuilder X 中,菜单工具—>设置—>运行配置—>微信开发者工具路径
- 在微信开发者工具中,菜单设置—>安全设置—>开启服务端口
- 如果运行不能成功打开微信开发者工具,可以手动操作目录dist/mp-weixin
//云函数wxLogin
'use strict';
const uniID = require("uni-id")
exports.main = async (event, context) => {
return await uniID.loginByWeixin({
code: event.code
})
};
<template>
<view class="content">
<image class="logo" :src="userInfo.avatarUrl"></image>
<view class="text-area">
<text class="nickname">{{userInfo.nickName}}</text>
</view>
<button type="default" open-type="getUserInfo" @getuserinfo="wxLogin">微信登录</button>
</view>
</template>
<script>
export default {
data() {
return {
userInfo:{}
}
},
onLoad() {
},
methods: {
getCode() {
return new Promise((resolve, reject) => {
uni.login({
provider: "weixin",
success: (e) => {
resolve(e)
},
fail: (err) => {
reject(new Error("获取code失败"))
}
})
})
},
getOpenID(code) {
return uniCloud.callFunction({
name: "wxLogin",
data: {
code
}
})
},
getUserProfile() {
return new Promise((resolve, reject) => {
uni.getUserProfile({
desc: "获取你的昵称、头像、地区及性别",
success: (e) => {
resolve(e)
},
fail: (err) => {
reject(new Error("getUserProfile失败"))
}
})
})
},
async wxLogin() {
var that = this;
this.getCode().then(e => {
return this.getOpenID(e.code)
}).then(e => {
console.log(e);
const {
openid,
token,
tokenExpired
} = e.result;
uni.setStorageSync('openid', openid)
uni.setStorageSync('uni_id_token', token)
uni.setStorageSync('uni_id_token_expired', tokenExpired)
uni.showModal({
title: "温馨提示",
content: "亲,授权微信登录后才能正常使用小程序功能",
success: (e) => {
if (e.confirm) {
this.getUserProfile().then(e => {
console.log(e);
this.userInfo=e.userInfo
})
}
}
})
}).catch(err => console.log(err))
}
}
}
</script>
<style>
.content {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
}
.logo {
height: 200rpx;
width: 200rpx;
margin-top: 200rpx;
margin-left: auto;
margin-right: auto;
margin-bottom: 50rpx;
}
.text-area {
display: flex;
justify-content: center;
color: #00aa7f;
}
</style>
总结:
- 本地uni.login—>code—>uniCloud.callFunction(wxLogin)—>{openid,token,tokenExpired}—>
持久化保存token
uni.setStorageSync('uni_id_token', token)
uni.setStorageSync('uni_id_token_expired', tokenExpired)
- uni.getUserInfo接口在微信小程序已经作废,需要使用uni.getUserProfile,调用之前必须弹出用户同意弹窗才可以正常调用uni.getUserProfile
<button type="default" open-type="getUserInfo" @getuserinfo="wxLogin">微信登录</button>
uni.showModal({
title: "温馨提示",
content: "亲,授权微信登录后才能正常使用小程序功能",
success: (e) => {
if (e.confirm) {
this.getUserProfile().then(e => {
console.log(e);
this.userInfo=e.userInfo
})
}
}
})
- uni.getUserInfo 获取得到的 userInfo 为匿名数据,建议使用 uni.getUserProfile 获取用户信息。