1. 程式人生 > 其它 >微信小程式獲取頭像和openID

微信小程式獲取頭像和openID

技術標籤:微信小程式小程式

1、繫結按鈕

 <button class="weiBtn" open-type="getUserInfo" bindgetuserinfo="getlogin" bindtap="tozhangLogin">微信登入</button>

2、獲取使用者資訊

 getlogin: function(e) {
    if (e.detail.userInfo) {
        this.setData({
          usertx: e.detail.userInfo.avatarUrl
        })
    }
},

3、wx.login 獲取code、根據code獲取openID

 wx.login({
      //獲取code
      success: function (res) {
        var code = res.code; //返回code
        console.log(code);
        var appId = '。。。';//微信小程式AppID
        var secret = '。。。';//可在微信開發設定根據二維碼獲取
        wx.request({
          url: 'https://api.weixin.qq.com/sns/jscode2session?appid='+appId+'&secret='+secret+'&js_code='+code+'&grant_type=authorization_code',
          data: {},
          header: { 
            'content-type': 'json'
          },   
          success: function (res) {
            var openid = res.data.openid //返回openid
          }
        })
      }
    })

注:程式碼僅供參考,如有不對,請留言。