微信小程序获取用户信息(附代码、流程图)
本篇文章主要总结了微信小程序开发获取用户信息的整个流程步骤。补充了网上很多碎片化的代码本人梳理了思路写下了这篇文章。思路1、在js文件中设置userinfo、hasUserinfo、canIUseGetUserProfile数据2、先判断本地缓存 wx.getStorageSync() 是否含有用户的数据如果有就用缓存里的数据没有就进行第三步3、在界面添加登录按钮用户点击按钮调用wx.getUserProfile()函数来提示用户授权登录授权成功后把用户头像数据和名称数据保存到缓存区里并且改变全局变量的值学习更多人工智能的知识给大家整理了学习网站人工智能学习网站普通人也能通俗易懂得理解前沿技术为自己以后不被淘汰做准备流程图自己大概画了一下大概的流程但希望对您有帮助考虑到一些新手我将完整代码发给大家大家按照代码对应写入对应位置即可wxmlview classbanner view classtopContainer view catchtapshowBcgImgArea image classuserinfo-avatar modeaspectFill src{{userinfo.avatarUrl}}/image /view view text classuserinfo-nickname{{userinfo.nickName}}/text /view /view button wx:if{{!hasUserInfo canIUseGetUserProfile}} open-typegetUserInfo bindtapgetUserProfile classuserLogin 点击登录 /button /viewjs注意avatarUrl:../../images/ckbg1.png这行代码意思是当没有获取到用户信息时页面展示头像的路径自己要先准备好一张图片放在images文件夹下并填好头像路径data: { //用户基本信息(头像、昵称) userinfo: { avatarUrl:../../images/ckbg1.png, nickName:未授权 }, //是否已经获取用户信息 hasUserInfo: false, //是否可以调用获取信息得函数 canIUseGetUserProfile: false, }, //第一次获取用户信息 getUserProfile : function(e){ wx.getUserProfile({ desc: 获取您的微信个人信息, success:(res){ this.setData({ userinfo:res.userInfo, hasUserInfo:true }) wx.setStorageSync(userinfo, res.userInfo) }, fail:function(e){ wx.showToast({ title: 你选择了取消, icon: none, duration: 1500, mask: true }) } }) }, onLoad: function(n) { this.setData({ canIUseGetUserProfile : true }) }, onShow: function() { //获取用户的本地缓存数据userinfo信息是在用户授权登录时保存的 var n wx.getStorageSync(userinfo); //当本地缓存的用户名称不为或者null时设置userinfo信息 if(n.nickName ! n.nickName ! null){ this.setData({ userinfo: n, hasUserInfo:true, canIUseGetUserProfile:true }) // 通过wx.login获取登录凭证code然后通过code去获取我们用户的openid wx.login({ success:(res){ console.log(res); }, }) } //清空缓存信息测试使用 // wx.removeStorage({ // key: userinfo, // }); },在这里有必要讲解几处代码1、当页面加载完毕时onLoad函数我们将canIUseGetUserProfile数据设置ture代表可以使用使用getUserProfile了避免页面没有加载完毕就去获取用户信息2、当页面即将展示时onShow函数)调用wx.getStorageSync获取本地缓存数据来控制按钮的显示与否wxss.banner { border-radius: 10rpx; border: none; box-sizing: content-box; padding: 20rpx 0; width: 90%; height: 370rpx; margin: 20rpx auto; background:linear-gradient(109.6deg, rgb(204, 228, 247) 11.2%, rgb(237, 246, 250) 100.2%); /* background-image:image(../../images/cloudbg.jpg); */ text-align: center; } .topContainer { width: 100%; height: 260rpx; background-size: 100%; border-radius: 9px; } .userinfo-nickname { color:black; } .userLogin{ width: 50%; box-sizing: none; font-size: medium; } .userinfo-avatar { width: 150rpx; height: 150rpx; margin-bottom: 10rpx; border-radius: 50%; }当缓存里没有记录用户信息时显示的页面会出现登录按钮点击按钮后弹出授权信息点击允许后会出现微信头像和微信名称创作不易希望可以给个赞或收藏⭐鼓励一下谢谢也欢迎大家关注公众号名片获取更多优质文章