微信小程序 官方API:https://mp.weixin.qq.com/debug/wxadoc/dev/api/
首先 以下代碼是 頁面加載請求用戶 是否同意授權 同意之后 用code 訪問 微信接口 拿到OpenId
//頁面加載 微信授權 var getInfo = function (thisObj){ var that = thisObj; wx.login({ success: function (res) { if (res.code) { //獲取openId wx.request({ url: 'https://api.weixin.qq.com/sns/jscode2session', data: { //小程序唯一標識 appid: '', //小程序的 app secret secret: '', grant_type: 'authorization_code', js_code: res.code }, method: 'GET', header: { 'content-type': 'application/json'}, success: function(openIdRes){ console.info("登錄成功返回的openId:" + openIdRes.data.openid); weChatUserInfo.openId = openIdRes.data.openid; // 判斷openId是否獲取成功 if (openIdRes.data.openid != null & openIdRes.data.openid != undefined) {
// 有一點需要注意 詢問用戶 是否授權 那提示 是這API發出的 wx.getUserInfo({ success: function (data) { // 自定義操作 // 綁定數據,渲染頁面 that.setData({ }); }, fail: function (failData) { console.info("用戶拒絕授權"); } }); }else { console.info("獲取用戶openId失敗"); } }, fail: function(error) { console.info("獲取用戶openId失敗"); console.info(error); } }) } } }); }
以下是 手動配置 打開 微信授權
//手動打開微信授權 var getInfoAgain = function (thisObj){ var that = thisObj; wx.openSetting({ success: function (data) { //判斷 用戶是否同意授權 if (data.authSetting["scope.userInfo"] == true) { // 同意授權 wx.login({ success: function (res) { if (res.code) { console.info("登錄成功返回的CODE:" + res.code); //獲取openId wx.request({ url: 'https://api.weixin.qq.com/sns/jscode2session', data: { // 小程序唯一標示 appid: '', // 小程序的 app secret secret: '', grant_type: 'authorization_code', js_code: res.code }, method: 'GET', header: { 'content-type': 'application/json' }, success: function (openIdRes) { // 獲取到 openId console.log(openIdRes.data.openid); // 判斷openId是否為空 if (openIdRes.data.openid != null & openIdRes.data.openid != undefined) { wx.getUserInfo({ success: function (data) { // 自定義操作 // 綁定數據,渲染頁面 that.setData({ }); } }) }else { // openId為空 } } }) } } }); }else { // 手動 開啟 是否授權提示框后 拒絕 } } }); }
//TODO 有個地方需要注意一下 小程序開發者工具 有一個配置
這個配置 如果打開 不驗證域名 都可以訪問
但是 這只是開發者工具 可以訪問 以及手機預覽 可以訪問
如果放到正式版的環境 或者說 測試版的環境 那么 是不可以訪問除了 設置好的域名以外 所有的域名 需要將 微信接口 (https://api.weixin.qq.com) 設置到 小程序白名單中 否則 獲取不到OpenId 返回undefined