mpvue小程序授权获取用户信息

常规判断用户登录状态,自动弹出授权

 mountd(){
//      this.getSetting();
//      this.getUserInfo();
    }, 
getSetting(){
        wx.getSetting({
          success(res) {
            console.log(res);
            if (!res.authSetting['scope.getUserInfo ']) {//未授权getUserInfo
              wx.authorize({
                scope: 'scope.getUserInfo ',
                success(res) {
                  // 用户已经同意小程序使用用户信息,后续调用 wx.userInfo 接口不会弹窗询问
                  console.log(res);
                },
                fail(err){
                  console.log(err);
                }
              })
            }else{//已授权
              wx.getUserInfo({
                success(res) {
                  console.log(res)
                },
                fail(err) {
                  console.log(err);
                }
              })
            }
          }
        })
      },
getUserInfo () {
        // 调用登录接口
        var _this=this;
            wx.getUserInfo({
              success(res) {
                console.log(res);
                _this.userInfo=res.userInfo
              },
              fail(err) {
                console.log(err);
              }
            })
      },

上面getUserInfo是会一直fail,返回未授权信息。

原因是因为微信现在不允许开发环境下,直接弹出授权窗口,然后通过wx.getUserInfo获取用户信息,但是正是环境不受影响;

解决方法(小程序与小游戏获取用户信息接口调整):

1 通过open-data可用于展示用户信息

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

2 通过button 

<template>
  <div class="container">
    <div class="userinfo" v-if="userInfo.nickName">
      <p>基本信息</p>
      <img class="userinfo-avatar" :src="userInfo.avatarUrl" background-size="cover" />
      <p>{{userInfo.nickName}}</p>
      <p>{{userInfo.province+'-'+userInfo.city}}</p>
    </div>
    <button v-if="!userInfo.nickName" open-type="getUserInfo" @getuserinfo="authSetUser">
        授权登录
    </button>
  </div>
</template>

...
 data () {
      return {
        userInfo: {},
      }
    },
...
created () {
      this.getUserInfo();
    },
methods: {
      authSetUser (e) {
        this.userInfo=e.mp.detail.userInfo;
      },
      getUserInfo () {
        // 调用登录接口
        var _this=this;
            wx.getUserInfo({//当已授权getUserInfo时
              success(res) {
                console.log(res);
                _this.userInfo=res.userInfo
              },
              fail(err) {
                console.log(err);
              }
            })
      },

猜你喜欢

转载自blog.csdn.net/github_38928905/article/details/85628623