uni-app获取用户信息及实现登陆

1,300 阅读1分钟

1.获取code

onLoad() {
    uni.login({
        success:res=>{
            this.code=res.code
        }
    })
},

2.获取用户信息 注意:getUserProfile里面只能有同步操作,有异步要换为同步

getUserProfile() {
    if(!this.agree){
            const _this = this
            uni.getUserProfile({
                    desc: "注册",
                    success: async (res) => {
                            uni.setStorageSync('avatarUrl', res.userInfo.avatarUrl);
                            uni.setStorageSync('NickName',res.userInfo.nickName);
                            uni.setStorageSync('sex', res.userInfo.gender);
                            let code_ = _this.code
                            await http.Post(getApp().globalData.api + '/v1/miniprogram/login', {
                                    'code': code_,
                                    'weixin_name':res.userInfo.nickName,
                                    'weixin_avatar':res.userInfo.avatarUrl,
                                    'sex':res.userInfo.gender
                            }, (ress) => {
                                    const response=ress.data
                                    if(response.code == 0){
                                            uni.setStorageSync('userToken', response.data.token);
                                            uni.switchTab({
                                                    url:'../index/index'
                                            })
                                    }else{
                                            uni.showToast({
                                                    title:'登陆失败!',
                                                    icon:'error'
                                            })
                                    }

                            })
                    },
                    fail: (err) => {
                            uni.showToast({
                                    title:'获取用户信息失败!',
                                    icon:'error'
                            })
                    }
            })
    }else{
            uni.showToast({
                    title:'请勾选用户协议',
                    icon:'none'
            })
    }
    }