1. 程式人生 > 其它 >入坑微信小程式必經之路(七)獲取當前使用者登入Openid

入坑微信小程式必經之路(七)獲取當前使用者登入Openid

不廢話,看程式碼

 onLaunch: function() {
    var _this = this;
    var url=this.globalData.url+"WeiXinConfig";
    wx.request({
      method: 'POST',
      url:url,
      header:{
        'content-type':'application/json'
      },success(res) {
        var Resdata=JSON.parse(res.data.d);
        if(Resdata[0]!=undefined){
          wx.login({
            //獲取code
            success: function (res) {
              var code = res.code; //返回code
              var appId = Resdata[0].appid;
              var secret = Resdata[0].appsecret;
              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
                  console.log('openid為' + openid);
                  console.log('appid為' + Resdata[0].appid);
                  console.log('appsecret為' + Resdata[0].appsecret);
                  if(openid!=undefined){
                    wx.setStorageSync("openid",openid);
                    // wx.setStorageSync("appid",Resdata[0].appid);
                    // wx.setStorageSync("appsecret",Resdata[0].appsecret);
                  }
                }
              })
            }
          })
        }
      }
    });