当前位置:网站首页>微信小程序获取登录用户信息、openid和access_token

微信小程序获取登录用户信息、openid和access_token

2022-04-23 14:02:00 1029179954

1:获取登录用户信息
由于微信小程序提升用户体验,所以获取用户信息就有所提升,使用button按钮,添加open-type="getUserInfo"即可
wxml

<view class='loginHeader'>
     <image src='{
   {userHead}}' class='userHead' mode='aspectFill' bindtap='previewHead' />
     <button class='userTitle'  open-type="getUserInfo"  bindtap='loginTap'>{
   {userTitle}} </button>
     <!-- <text class='userTitle' bindtap='loginTap'>{
   {userTitle}}</text> -->
</view>

js

  loginTap: function () {
                    wx.getUserProfile({
                         desc: '展示用户信息', // 声明获取用户个人信息后的用途,后续会展示在弹窗中,请谨慎填写
                         success: (res) => {
                           console.log(res.userInfo)
                           app.userTitle=res.userInfo.nickName
                           app.userHead=res.userInfo.avatarUrl
                           this.setData({
                              userHead: app.userHead,
                              userTitle: app.userTitle
                           })
                         }
                       })
     },

2:获取openid和access_token
openid:
每个微信唯一的id
access_token:
access_token是公众号的全局唯一接口调用凭据,公众号调用各接口时都需要使用access_token。
appid、secret:在微信公众平台里边,具体在下图
在这里插入图片描述

js(放在微信小程序onload函数即可)

 //获取openid
    wx.login({
      success: function (res) {
        var code1 = res.code
        var appid1 = "自己的appid"
        var secret1 = "自己的秘钥"
        var ul = 'https://api.weixin.qq.com/sns/jscode2session?appid=' + appid1 + '&secret=' + secret1 + '&js_code=' + code1 + '&grant_type=authorization_code'
        //获取openid
        wx.request({
          url: ul,
          method: 'GET',
          success: function (e) {
            var openid = e.data.openid
            console.log('获取登录身份的唯一openid', openid)
            that.openid=e.data.openid
            wx.setStorageSync('openid', openid)
          }
        })

      }
    })
  },
    //获取access_token
    const appid = "自己的appid" // 这里填写你的appid
    const secret = "自己的秘钥" // 这里填写你的secret
    wx.request({
      url: `https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${appid}&secret=${secret}`, 
      header: {
        'content-type': 'application/json' 
      },
      success(res) {
        console.log("at微信小程序"+res.data.access_token)
        that.access_token=res.data.access_token
        console.log("onload:"+that.access_token)
        wx.setStorageSync('at',res.data.access_token)
      },
      fail(error){
        console.log(error)
      }
    })

版权声明
本文为[1029179954]所创,转载请带上原文链接,感谢
https://blog.csdn.net/baidu_38978508/article/details/121592280