1.授權按鈕:
<view> <button class='login-btn' type='primary' @click="bindGetUserInfo"> 授權登錄 </button> </view>
2.事件方法:
<script> export default { data() { return { nickName: null, //昵稱 avatarUrl: null, //頭像 isCanUse: uni.getStorageSync('isCanUse') || true, //默認為true userInfo: {}, canIUse: uni.canIUse('button.open-type.getUserInfo'), canIGetUserProfile: false, detail: {}, openid: null, gender: null, city: null, province: null, country: null, session_key: null, unionid: null, } }, onLoad() { //默認加載 var _this = this; //console.log(uni.getUserProfile); if (uni.getUserProfile) { this.canIGetUserProfile = true; } // console.log(this.canIGetUserProfile) //判斷若是版本不支持新版則采用舊版登錄方式 //查看是否授權 if (!this.canIGetUserProfile) { uni.getSetting({ success: function(res) { if (res.authSetting['scope.userInfo']) { uni.getUserInfo({ provider: 'weixin', success: function(res) { // console.log(res); _this.userInfo = res.userInfo; try { uni.setStorageSync('isCanUse', false); _this.login(); } catch (e) {} }, fail(res) {} }); } else { // 用戶沒有授權 console.log('用戶還沒有授權'); } } }); } }, methods: { //第一次授權 bindGetUserInfo(e) { var _this = this; if (this.canIGetUserProfile) { //新版登錄方式 uni.getUserProfile({ desc: '登錄', success: (res) => { _this.userInfo = res.userInfo; try { _this.login(); } catch (e) {} }, fail: (res) => { console.log('用戶還沒有授權'); } }); } else { if (e.detail.userInfo) { _this.userInfo = e.detail.userInfo; try { _this.login(); } catch (e) {} } else { console.log('用戶拒絕了授權'); //用戶按了拒絕按鈕 } } }, //登錄 login() { let _this = this; // 獲取登錄用戶code uni.getProvider({ service: 'oauth', success: function(res) { if (~res.provider.indexOf('weixin')) { uni.login({ provider: 'weixin', success: function(res) { // console.log(res); if (res.code) { let code = res.code; uni.request({ url: 'https://api.wyzdjg.top/userinfo', data: { code: code, }, method: 'GET', header: { 'content-type': 'application/json' }, success: (res2) => { console.log(res2); console.log(123) _this.detail = res2.data.data; _this.updateUserInfo(); uni.hideLoading(); } }); //將用戶登錄code傳遞到后台置換用戶SessionKey、OpenId等信息 //...寫用code置換SessionKey、OpenId的接口 //置換成功調用登錄方法_this.updateUserInfo(); } else { uni.showToast({ title: '登錄失敗!', duration: 2000 }); } }, }); } else { uni.showToast({ title: '請先安裝微信或升級版本', icon: "none" }); } } // }); }, //向后台更新信息 updateUserInfo() { let _this = this; // console.log(_this); uni.request({ url: 'https://api.wyzdjg.top/updateinfo', //服務器端地址 data: { openid: _this.detail.openid, nickname: _this.userInfo.nickName, avatarUrl: _this.userInfo.avatarUrl, gender: _this.userInfo.gender, city: _this.userInfo.city, province: _this.userInfo.province, country: _this.userInfo.country, session_key: _this.detail.session_key, unionid: _this.detail.unionid, }, method: 'POST', header: { 'content-type': 'application/json' }, success: (res) => { console.log(res) if (res.data.code == 200) { uni.reLaunch({ //信息更新成功后跳轉到小程序首頁 // url: '/pages/index/index' }); } } }); } }, } </script>