從微信小程序官方發佈的公告中咱們可獲知:小程序體驗版、開發版調用 wx.getUserInfo 接口,將沒法彈出受權詢問框,默認調用失敗,需使用 <button open-type="getUserInfo"></button> 引導用戶主動進行受權操做:json
1.當用戶未受權過,調用該接口將直接報錯 小程序
2.當用戶受權過,能夠使用該接口獲取用戶信息微信小程序
但在實際開發中咱們可能須要彈出受權詢問框,所以須要咱們本身來寫模擬受權彈框(主要是對 <button open-type="getUserInfo"></button>的包裹+用戶是不是第一次受權判斷來顯示該頁面),代碼以下:服務器
1.頁面結構微信
<template> <view> <!-- #ifdef MP-WEIXIN --> <view v-if="isCanUse"> <view> <view class='header'> <image src='../../static/img/wx_login.png'></image> </view> <view class='content'> <view>申請獲取如下權限</view> <text>得到你的公開信息(暱稱,頭像、地區等)</text> </view> <button class='bottom' type='primary' open-type="getUserInfo" withCredentials="true" lang="zh_CN" @getuserinfo="wxGetUserInfo"> 受權登陸 </button> </view> </view> <!-- #endif --> </view> </template>
這裏的isCanUse是用來記錄當前用戶是不是第一次受權使用的,wx_login.png圖在底部下載獲取便可。app
2.樣式ide
<style> .header { margin: 90rpx 0 90rpx 50rpx; border-bottom: 1px solid #ccc; text-align: center; width: 650rpx; height: 300rpx; line-height: 450rpx; } .header image { width: 200rpx; height: 200rpx; } .content { margin-left: 50rpx; margin-bottom: 90rpx; } .content text { display: block; color: #9d9d9d; margin-top: 40rpx; } .bottom { border-radius: 80rpx; margin: 70rpx 50rpx; font-size: 35rpx; } </style>
3.腳本部分this
<script> export default { data() { return { SessionKey: '', OpenId: '', nickName: null, avatarUrl: null, isCanUse: uni.getStorageSync('isCanUse')||true//默認爲true }; }, methods: { //第一受權獲取用戶信息===》按鈕觸發 wxGetUserInfo() { let _this = this; uni.getUserInfo({ provider: 'weixin', success: function(infoRes) { let nickName = infoRes.userInfo.nickName; //暱稱 let avatarUrl = infoRes.userInfo.avatarUrl; //頭像 try { uni.setStorageSync('isCanUse', false);//記錄是否第一次受權 false:表示不是第一次受權 _this.updateUserInfo(); } catch (e) {} }, fail(res) {} }); },
//登陸 login() { let _this = this; uni.showLoading({ title: '登陸中...' }); // 1.wx獲取登陸用戶code uni.login({ provider: 'weixin', success: function(loginRes) { let code = loginRes.code; if (!_this.isCanUse) { //非第一次受權獲取用戶信息 uni.getUserInfo({ provider: 'weixin', success: function(infoRes) {
//獲取用戶信息後向調用信息更新方法 let nickName = infoRes.userInfo.nickName; //暱稱 let avatarUrl = infoRes.userInfo.avatarUrl; //頭像 _this.updateUserInfo();//調用更新信息方法 } }); } //2.將用戶登陸code傳遞到後臺置換用戶SessionKey、OpenId等信息 uni.request({ url: '服務器地址', data: { code: code, }, method: 'GET', header: { 'content-type': 'application/json' }, success: (res) => { //openId、或SessionKdy存儲//隱藏loading uni.hideLoading(); } }); }, }); }, //向後臺更新信息 updateUserInfo() { let _this = this; uni.request({ url:'url' ,//服務器端地址 data: { appKey: this.$store.state.appKey, customerId: _this.customerId, nickName: _this.nickName, headUrl: _this.avatarUrl }, method: 'POST', header: { 'content-type': 'application/json' }, success: (res) => { if (res.data.state == "success") { uni.reLaunch({//信息更新成功後跳轉到小程序首頁 url: '/pages/index/index' }); } } }); } }, onLoad() {//默認加載 this.login(); } } </script>
4.最終效果以下:url
wx_login.png圖:spa