小程序用户信息获取

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

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

微信接口登录文档

获取用户信息方法文档

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

小程序登录流程

image

为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 返回参数相同的数据。

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

image

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'
          })
        })
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容