記錄時間:2021-07-09 uniapp微信小程序獲取用戶信息代碼
<template> <view class="page-login"> <view v-if="canIUse||canIGetUserProfile"> <view class='login-header'> <image style="width: 140rpx; height: 140rpx;" mode="aspectFit" src="../../static/logo.png"></image> <view class="name">登錄</view> </view> <view class='content'> <view>申請獲取以下權限</view> <text>獲得你的公開信息(昵稱、頭像、地區等)</text> </view> <view class="login-box"> <!--新版登錄方式--> <button v-if="canIGetUserProfile" class='login-btn' type='primary' @click="bindGetUserInfo"> 授權登錄 </button> <!--舊版登錄方式--> <button v-else class='login-btn' type='primary' open-type="getUserInfo" withCredentials="true" lang="zh_CN" @getuserinfo="bindGetUserInfo"> 授權登錄 </button> </view> </view> <view v-else class="text-center"> 請升級微信版本 </view> </view> </template> <script> export default { data() { return { sessionKey: '', openId: '', nickName: null, avatarUrl: null, userInfo:{}, canIUse: uni.canIUse('button.open-type.getUserInfo'), canIGetUserProfile:false, }; }, onLoad() { var _this = this; //console.log(uni.getUserProfile); if( uni.getUserProfile ){ this.canIGetUserProfile = true; } //判斷若是版本不支持新版則采用舊版登錄方式 //查看是否授權 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 { _this.login(); } catch (e) {} }, fail(res) {} }); } else { // 用戶沒有授權 console.log('用戶還沒有授權'); } } }); } }, onShow() { }, methods: { //登錄授權 bindGetUserInfo(e) { var _this = this; if(this.canIGetUserProfile){ //新版登錄方式 uni.getUserProfile({ desc:'登錄', success:(res)=>{ //console.log(res); _this.userInfo = res.userInfo; try { _this.login(); } catch (e) {} }, fail:(res)=>{ console.log(res) } }); }else{ //舊版登錄方式 if (e.detail.userInfo) { //用戶按了允許授權按鈕 //console.log('手動'); //console.log(e.detail.userInfo); _this.userInfo = e.detail.userInfo; try { _this.login(); } catch (e) {} } else { console.log('用戶拒絕了授權'); //用戶按了拒絕按鈕 } } }, //登錄 login() { let _this = this; // 獲取登錄用戶code uni.login({ provider: 'weixin', success: function(res) { //console.log(res); if(res.code){ let code = res.code; //將用戶登錄code傳遞到后台置換用戶SessionKey、OpenId等信息 //...寫用code置換SessionKey、OpenId的接口 //置換成功調用登錄方法_this.updateUserInfo(); }else{ uni.showToast({title: '登錄失敗!',duration: 2000}); console.log('登錄失敗!' + res.errMsg) } }, }); }, //向后台更新信息 updateUserInfo() { uni.showLoading({ title: '登錄中...' }); let _this = this; var params = { openId: _this.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, unionId: '', } //console.log('登錄'); //...后台登錄的接口 } } } </script>