微信小程序获取用户头像和昵称

由于微信回收了open-data,头像返回了默认头像,昵称返回了微信用户,大家都骂骂咧咧的把getUserInfo改成了getUserProfile,getUserProfile这个api需要tap才能触发,不能再直接在onload和onshow直接调用函数了。
所以我们选择onload的时候打开一个showModal,让用户点击允许获取信息才调用该接口。而我们为了避免每次获取头像和昵称而把它存起来,但是又担心用户修改昵称和头像,所以搞了一个定时器,因为setStorageSync官方说不清理就不会丢失(其实常常被吐槽自动丢失)。(样式自己写吧,别这么懒)

回收的代码:

<open-data type='userAvatarUrl' ></open-data>
<open-data type='userNickName' ></open-data>

调整后的代码:

a.wxml代码:

<view>
	<image src="{{userInfo.avatarUrl}}"></image>
	<text>{{userInfo.nickName}}</text>
</view>

a.js代码:

Page({
  data:{
    userInfo: {}
  },
  onLoad:function(e){
    this.setUserInfoStorageTime();
  },
  getUserProfile() {
    var that = this;
    wx.showModal({
      title: "提示",
      content: "是否允许获取微信昵称和头像?",
      success(res) {
        if (res.confirm) {
          wx.getUserProfile({
            desc: "用于完善用户资料", // 声明获取用户个人信息后的用途,后续会展示在弹窗中,请谨慎填写
            success: (res) => {
              app.globalData.userInfo = res.userInfo; //这个我有时候获取不到,所以没管它,但先写着
              that.setData({
                userInfo: res.userInfo
              });
              wx.setStorageSync("userInfo", res.userInfo);
              
              let setNowTime = Date.now() + 3600 * 1000 * 24 * 30;  // 我设置了30天有效期,你们可以自己改
              wx.setStorageSync("userInfoStorageTime", setNowTime);
            },
            fail: function (err) {
              console.log(err);
            },
          });
        }
      },
    });
  },
  setUserInfoStorageTime() {
    var that = this;
    let nowTime = Date.now();
    let oldTime = wx.getStorageSync("userInfoStorageTime");
    let userInfo = wx.getStorageSync("userInfo");
    if ( userInfo.nickName != undefined && userInfo.nickName != null && userInfo.nickName != "" ) {
      if (oldTime && nowTime < oldTime) {
        that.setData({
          userInfo:userInfo
        })
        return;
      } else {
        that.getUserProfile();
      }
    } else {
      that.getUserProfile();
    }
  },
})
  • 5
    点赞
  • 44
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值