最新版微信小程序授权登录(自定义头像昵称)

        根据官方微信小程序开发关于登录授权API的调整,自 2022年10月25日起有关API接口获取用户头像将统一返回默认灰色头像,昵称将统一返回 “微信用户”。(如下图所示)

 那我们如何解决?

效果图:

登录授权页面

wxml代码如下:

<button>标签中将open-type="chooseAvatar"是用来设置用户头像,并且获得一个临时路径。

<button class="avatar" open-type="chooseAvatar" bind:chooseavatar="onChooseAvatar" style="width: 250rpx;height: 200rpx;"><image class="avatar" src="{
    
    {avatarUrl}}" ></image></button>

<input bindinput="inputValue" placeholder="请输入昵称" style="width: 200rpx;height: 100rpx; margin:20rpx auto;"/>

<button bindtap="submit" style="background-color: aquamarine;">授权登录</button>

js代码如下:

js代码主要包括三个事件(头像临时路径)、昵称、获取授权并变灰色头像和“微信用户”。

// pages/show/show.js
const defaultAvatarUrl = 'https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0'
const app=getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    avatarUrl: defaultAvatarUrl,//头像临时路径,默认是defaultAvatarUrl的灰色头像
  },
  
  /**
   * 获取头像的临时路径   */
  onChooseAvatar(e) {
    const { avatarUrl } = e.detail //e.detail是从前端传过来的所选头像的临时路径
    this.setData({         
      avatarUrl,        //将所选头像临时路径赋值给avatarUrl
    })
  },

   /**
    *获取文本框所输入的昵称信息*/
  inputValue(e){
    console.log(e)
    this.setData({
      inputNickname:e.detail.value
    })
  },
   /**
    *授权登录,将API调整后返回的nickName和avatarUrl改成我们自定义选择的头像和昵称*/
  submit(e){
    var that=this
    wx.getUserProfile({ //获取登录授权的API
      desc: '获取用户必要信息',
      success(res){
        app.globalData.userInfo=res.userInfo //将API返回的信息赋值给全局变量userInfo
        app.globalData.userInfo.nickName=that.data.inputNickname //更改全局变量中的userinfo中的昵称
        app.globalData.userInfo.avatarUrl=that.data.avatarUrl //更改头像临时路径
        console.log(app.globalData.userInfo)
        wx.setStorageSync('userInfo', res.userInfo) //将信息本地储存,方便下次不用再次授权登录
        wx.showToast({
          title: '授权成功!',
          success(){
            wx.navigateTo({
              url: '/pages/info/info',//登录成功返回到主页
            })
          }
        })
      }
    })
  }
})

主页展示页面

wxml代码:

<view style="width: 100%;height: 400rpx;background-color: aquamarine;display: flex;flex-direction: column;justify-content: center;">
  <image src="{
   
   {userInfo.avatarUrl}}" style="width: 250rpx;height: 250rpx;border-radius: 50% 50%;overflow: hidden;margin: auto;"></image>
  <view style="margin: auto;">{
   
   {userInfo.nickName}}</view>
</view>

js代码:

此处引用全局变量中的userInfo中的信息,此变量是我们在授权时所赋值的。

const app=getApp()
Page({
  data: {
    userInfo:app.globalData.userInfo,
  },
)}

猜你喜欢

转载自blog.csdn.net/weixin_52312427/article/details/128439249