uniapp在微信小程序获取用户信息和openId

uniapp在微信小程序获取用户信息和openId
获取用户信息
获取openId
获取用户信息
使用getUserProfile(),这个方法在每次出发的时候都会调起微信授权的那个弹出层,为什么不用getUserInfo(),微信给程序员们发公告了,不同于gerUserInfo,getUserProfile的使用方法被简化了许多,不需要在按钮属性中添加open-type,更不用规定按钮的方法,只需要:

<button @click="getUserProfile">获取用户信息</button>

这个API需要在微信开发者工具基础调试库版本2.10.4以上或微信版本7.0.9以上才可以使用。

所以使用之前在页面的onLoad()里面判断下:

onLoad() {
     if(uni.getUserProfile){
         this.canIUseGetUserProfile = true
     }
},

使用时的注意事项,这个方法必须由按钮直接调用,不可以在其他函数的回调中使用这个方法,否则就会报如下错误:

> errMsg: "getUserProfile:fail can only be invoked by user TAP gesture."

因此,直接调用就可以了,具体如下:

DOM:

<button v-if="canIUseGetUserProfile" class="sys_btn" @click="getUserProfile">授权</button>

JS:

getUserProfile() {
          //获取用户信息
            uni.getUserProfile({
                desc: '用户信息展示',
                success: (info) => { 
                    this.userInfo = info
                },
                fail: (err) => {
                    uni.showToast({
                        title: "微信登录授权失败",
                        icon: "none"
                    });
                }
            })
},

关于getUserProfile()的参数和出参照文档即可: wx.getUserProfile(Object object)

获取到用户信息之后,存到vuex中供后续使用。

获取openId

在获取openID之前需要先调用login()方法获取一个登陆凭证

uni.login({
     timeout: 10000,
      provider: 'weixin',  //如果是uniapp,在这里需要标明平台的类型,支持的参数请查阅uniapp官网的uni.login()文档
      success: (res) => {
            //登陆成功的回调
      },
      fail: (err) => {
             //登陆失败的回调
      }
})

在获取到登陆凭证之后,就可以调用接口获取openId和session_key等参数了。
可以在login()的success中直接使用如下代码:

uni.request({  
      url: 'https://api.weixin.qq.com/sns/jscode2session',  
      method:'GET',  
      data: {  
          appid: 'wx xxxxxxxxxxxx,       //你的小程序的APPID  
          secret: 'xxxxxxxxxxxxx',       //你的小程序的secret,  
          js_code: 'xxxxxxxxxxxxx        //wx.login 登录成功后的code  
      },  
      success: (cts) => {  
          console.log(cts);
      }  
});  

直接使用微信提供的https://api.weixin.qq.com/sns/jscode2session接口,传入的参数重appid和secret需要小程序管理员到微信公众平台获取,具体详细的获取方式不作赘述。

到这里微信授权获取登陆信息的过程就结束了,可以将获取到的信息都存储到uniapp的Storage中做一个数据持久化,这样可以避免页面刷新导致的数据丢失。
————————————————
版权声明:本文为CSDN博主「ʚ杨ɞ」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/weixin_43387188/article/details/118763643

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章