1.個人開發者是獲取不到OpenId:之前測試一直拿不到,讀者可以試一下。

2.獲取的程式碼和輸出:

//app.js

App({

globalData: {

appid: 'wx62a1hh8cfc28fdb',//appid需自己提供,此處的appid我隨機編寫

secret: '8990bf089dbsese3c951a1',//secret需自己提供,此處的secret我隨機編寫

},

onLaunch: function () {

var that = this

var user = wx.getStorageSync('user') || {};

var userInfo = wx.getStorageSync('userInfo') || {};

if ((!user.openid || (user.expires_in || Date.now()) < (Date.now() + 600)) && (!userInfo.nickName)) {

wx.login({

success: function (res) {

if (res.code) {

wx.getUserInfo({

success: function (res) {

var objz = {};

objz.avatarUrl = res.userInfo.avatarUrl;

objz.nickName = res.userInfo.nickName;

console.log(objz);

wx.setStorageSync('userInfo', objz);//儲存userInfo

}});

var d = that.globalData;//這裡儲存了appid、secret、token串

var l = 'https://api.weixin.qq.com/sns/jscode2session?appid=' + d.appid + '&secret=' + d.secret + '&js_code=' + res.code + '&grant_type=authorization_code';

wx.request({

url: l,

data: {},

method: 'GET', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT

// header: {}, // 設定請求的 header

success: function (res) {

var obj = {};

obj.openid = res.data.openid;

obj.expires_in = Date.now() + res.data.expires_in;

console.log(obj);

wx.setStorageSync('user', obj);//儲存openid

}

});

} else {

console.log('獲取使用者登入態失敗!' + res.errMsg)

}

}

});

}

},

})

結果輸出(設定不校驗域名):

VM682:1 工具未校驗合法域名、web-view(業務域名)、TLS 版本以及 HTTPS 證書。

app.js? [sm]:36

  1. {openid: "oBU4-5beiAsSLu40efAxL5d8iJe0", expires_in: NaN}
    1. expires_in:NaN
    2. openid:"o*********0efAxL5d8iJe0" 
    3. __proto__:Object

轉載:https://blog.csdn.net/qq_27626333/article/details/54614037