微信小程序获取用户信息和openid

1.获取用户信息
微信改变了获取用户信息的方法

wxml:
 <button class="cu-btn bg-Olive shadow" open-type="getUserInfo" bindgetuserinfo="getUserInfo">   登 录</button>
js:
// 获取用户昵称
  getUserInfo: function (e) {
    console.log(e)
    app.globalData.userInfo = e.detail.userInfo
    this.setData({
      nickname: e.detail.userInfo.nickName
    })
  }
  1. 获取openid
app.js
// 登录
    wx.login({
      success: res => {
        // 发送 res.code 到后台换取 openId, sessionKey, unionId
        if (res.code) {
          //发起网络请求
          wx.request({
            url: 'http://localhost/tp/public/wx',
            data: {
              code: res.code
            }
          })
        } else {
          console.log('获取用户登录态失败!' + res.errMsg)
        }
      }
    })
index.js:
 wx.login({
      //获取code
      success: function (res) {
        var code = res.code; //返回code
        console.log(code);
        var appId = 'appid';
        var secret = 'appsecret';
        wx.request({
          // url: 'https://api.weixin.qq.com/sns/jscode2session?appid=this.appid&secret=this.secret&js_code=this.code&grant_type=authorization_code',
          url: 'https://api.weixin.qq.com/sns/jscode2session?appid=&secret=&js_code=app.js中获得的code&grant_type=authorization_code',
          data: {},
          header: {
            'content-type': 'json'
          },
          success: function (res) {
            var openid = res.data.openid //返回openid
            console.log('openid为' + openid);
          }
        })
      }
    })

 posted on 2020-09-20 11:28  My_serendipity  阅读(406)  评论(0编辑  收藏  举报