先看代码,您将看到以下效果,复制使用即可,部分地方需要修改,已备注。
如您满意请给莫成尘点个Fabulous
<template>
<view>
<view class="Administration">
<view class="welcome">
我们这个小程序欢迎您!
</view>
<view class="fondyour">
请确认授权以下信息
</view>
<view class="fondyourson">
获取你的公开信息 (昵称,头像等)
</view>
<!-- 依据微信要求 使用getUserInfo 来获取用户授权-->
<button class="isbtn" open-type="getUserInfo" @getuserinfo="getUserList">
微信授权
</button>
</view>
</view>
</template>
<script>
//请注意 这是我封装的接口调用
// import { GetOpenId , Login } from "../../API"
// API.js中 这两个函数 如下定义
// //获取用户信息信息
// let base = 'https://接口地址.cn/api';
// export const GetOpenId = params => { return Get(`${base}/user/getSessionKey`,params).then(res => res.data); };
// //登录
// export const Login = params => { return Get(`${base}/user/login`,params).then(res => res.data); };
export default {
data() {
return {
userMsg:'', //用户信息
}
},
methods: {
getUserList(res) {
const _this = this;
uni.setStorageSync('usermsg', res); // 获取到用户授权后 会得到用户公开信息
_this.userMsg = res.detail
console.log('用户公开信息',res)
if(_this.userMsg){
uni.login({ //调用登陆方法 获取code
success(res) {
console.log('code信息',res)
let params = {
code:res.code
}
uni.setStorageSync('usercode', res); //当然也可以存起来
// 这个地方就获取到了 几乎您所需要的一切登陆需要的信息
//当然 有可能获取失败 我们的做法是
//清除历史记录 如果没有历史记录 会让用户重新授权一次
// 这里调用您的接口方法
// 比如 请求网络数据 下面是您可能用到的数据
// GetOpenId(params).then(res=>{ //GetOpenId 是我自己封装的函数 获取openid
// if(res.code==1){
// uni.setStorageSync('useOpenId', res.data); //存储openid
// let data = {
// openid:res.data.openid,
// session_key:res.data.session_key,
// encrypted_data:_this.userMsg.encryptedData,
// iv:_this.userMsg.iv,
// }
// Login(data).then(rep=>{ // 一个获取token的接口函数
// if(rep.code==1){
// uni.setStorageSync('token', rep.data.token);
// wx.showToast({
// title: '登录成功',
// icon: 'success',
// duration: 1000,
// })
// setTimeout(()=>{ //登陆成功 返回上一页
// uni.navigateBack({
// delta:-1
// })
// },1000)
// }else{
// wx.showToast({
// title: rep.msg.msg,
// icon: 'none',
// duration: 1000,
// })
// wx.clearStorage()
// setTimeout(()=>{ //token 获取失败 清除Storage 返回上一页
// wx.switchTab({
// url: '../Mine/Mine'
// })
// },1000)
// }
// })
// }else{
// wx.showToast({
// title: '请求失败,请重试',
// icon: 'none',
// duration: 1500,
// })
// wx.clearStorage()
// setTimeout(()=>{ //token 获取失败 清除Storage 返回上一页
// wx.switchTab({
// url: '../Mine/Mine'
// })
// },1000)
// }
// })
}
})
}
}
}
}
</script>
<style scoped lang="scss">
.Administration{
width: 74%;
height: auto;
padding-top:120rpx;
margin-left:13%;
}
.welcome{
font-size:30rpx;
font-weight:600;
color:#000;
}
.fondyour{
font-size:22rpx;
color:#000;
font-weight:600;
margin-top:35rpx;
}
.fondyourson{
color:rgba(159,160,160,1);
font-size:20rpx;
margin-top:10rpx;
}
.isbtn{
height: 70rpx;
line-height:70rpx;
font-size:30rpx;
background: #339900;
color:#fff;
margin-top:60rpx;
}
</style>
附加和可能出现的有用信息已添加注释
其他有关uniapp的疑问或者此方法不理解的地方您可留言,我会尽快回复并帮您解决。