uniapp小程序新版授权登录
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>
路是自己走出来的,而不是选出来的。