小程序用户信息获取

460 阅读1分钟

如果只是展示用户头像昵称,可以使用open-data组件

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

微信接口登录文档

获取用户信息方法文档

当需要使用 button 来授权登录时,

小程序登录流程

为button组件绑定login事件

流程: 点击按钮>调用wx.login>服务器返回参数>发送参数>返回user>保存user>回首页

login.wxml

<button class="loginButton" 
  open-type="getUserInfo" 
  withCredentials="true" 
  bind:getuserinfo="login">
    登录
</button>

login.js

  login(event) {
   wx.login({
     success: function(res) {
       console.log(res);
     },
     fail: function(res) {}
   });
 }

登录按钮如上所示配置后,button组件上的bindgetuserinfo事件,当open-type为 getUserInfo 时,用户点击会触发。可以从事件返回参数的detail字段中获取到和wx.getUserInfo 返回参数相同的数据。

我们把按钮返回的参数打出来

detail内的encryptedData和iv是我们待会需要的,把他存下来 在login事件内使用wx.login方法,获取code并保存

wx.login({
    success: function(res) {
        console.log(res)
    },
    fail: function(error) {}
})

紧接着就是把code,iv,encrypted_data,app_id,app_secret发送给后端,后端解密后将用户信息返回给前端,拿到用户数据,存到storage里,同时清除所有页面,进入首页

解密具体实现需要和后端协商,我的http.post方法返回了promise,所以能直接使用.then()

http.post('/sign_in/mini_program_user',{
          code,
          iv,
          encrypted_data,
          app_id,
          app_secret
        })
        .then(response=>{
          wx.setStorageSync('me', response.data.resource)
          wx.setStorageSync('X-token', response.header["X-token"])
          wx.reLaunch({
            url: '/pages/index/index'
          })
        })