1. 程式人生 > >Egret微信小遊戲登入授權

Egret微信小遊戲登入授權

  getUserInfo(left, bottom) {
return new Promise((resolve, reject) => {
  let sysInfo = wx.getSystemInfoSync();
  let sdkVersion = sysInfo.SDKVersion;
  sdkVersion = sdkVersion.replace(/\./g, "");
  sdkVersion = sdkVersion.substr(0, 3);
  let sdkVersionNum = parseInt(sdkVersion);
  console.log("platform獲取使用者授權:", sdkVersionNum);
  //判斷使用者是否授權過
  wx.getSetting({
    success(res){
      if (sdkVersionNum >= 201 && !res.authSetting['scope.userInfo']) {
        var button = wx.createUserInfoButton({
          type: 'text',
          // text: '老鐵授權',
          style: {
            left: 118,
            top: 263,
            width: 140,
            height: 140,
            lineHeight: 0,
            // backgroundColor: '#228B22',
            // color: '#ffffff',
            textAlign: 'center',
            fontSize: 0,
            borderRadius: 10
          }
        });
        button.onTap((res) => {
          console.log("使用者授權:", res);
          var userInfo = res.userInfo;
          var nickName = userInfo.nickName;
          var avatarUrl = userInfo.avatarUrl;
          var gender = userInfo.gender; //性別 0:未知、1:男、2:女
          var province = userInfo.province;
          var city = userInfo.city;
          var country = userInfo.country;
          button.destroy();
          resolve(userInfo);
        });
      } else {
        wx.getUserInfo({
          withCredentials: true,
          success: res => {
            var userInfo = res.userInfo;
            var nickName = userInfo.nickName;
            var avatarUrl = userInfo.avatarUrl;
            var gender = userInfo.gender; //性別 0:未知、1:男、2:女
            var province = userInfo.province;
            var city = userInfo.city;
            var country = userInfo.country;
            resolve(userInfo);
          },
          fail: res => {
            wx.showModal({
              title: '友情提醒',
              content: '請允許微信獲得授權!',
              confirmText: "授權",
              showCancel: false,
              success: res => {
                resolve(null);
              }
            });
          }
        });
      }
    }
  })
});

}