小程序新的授权登录

<template>
    <view class="page-login">
		<view v-if="canIUse||canIGetUserProfile">
			<view class='login-header'>
				<image style="width: 140rpx; height: 140rpx;" mode="aspectFit" src="../../static/image/login.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;
			if(uni.getStorageSync('userInfo')){
				this.userInfo = uni.getStorageSync('userInfo')
				this.login();
				// wx.switchTab({
				// 	url:'../index/index'
				// })
			}
			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;
								uni.setStorageSync('userInfo', res.userInfo);
								try {
								  _this.login();
								} catch (e) {}
							  },
							  fail(res) {}
							});
						} else {
							// 用户没有授权
							console.log('用户还没有授权');
						}
					}
				});
			}
		},
		onShow() {
			
		},
	    methods: {
			//登录授权
		    bindGetUserInfo(e) {
		    	var _this = this;
				uni.showLoading({
					title: '授权中...'
				});
				if(this.canIGetUserProfile){
                    //新版登录方式
					uni.getUserProfile({
						desc:'登录',
						success:(res)=>{
							//console.log(res);
							_this.userInfo = res.userInfo;
							uni.setStorageSync('userInfo', res.userInfo);
							try {
								_this.login();
							} catch (e) {}
						},
						fail:(res)=>{
							uni.hideLoading();
							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 {
						uni.hideLoading();
						console.log('用户拒绝了授权');
					    //用户按了拒绝按钮
					}
				}
		    },
			//登录
			login() {
				let _this = this;
				// 获取登录用户code
				uni.hideLoading();
				uni.showLoading({
					title: '登录中...'
				});
				uni.login({
					provider: 'weixin',
					success: function(res) {
						//console.log(res);
						if(res.code){
						   let code = res.code;
						   console.log(code)
						   uni.getUserInfo({
							  provider: 'weixin',
							  success: function(infoRes) {
                      //获取用户信息后向调用信息更新方法
								  _this.nickName = infoRes.userInfo.nickName; //昵称
								  _this.avatarUrl = infoRes.userInfo.avatarUrl; //头像
								uni.setStorageSync('nickName', _this.nickName);
								uni.setStorageSync('avatarUrl', _this.avatarUrl);
								  // _this.updateUserInfo();//调用更新信息方法
							  }
						  });
						 
						  //2.将用户登录code传递到后台置换用户SessionKey、OpenId等信息
						  //这个接口测试环境可以使用,正式环境不可使用,必须走后台了。
						  uni.request({
						      url: 'https://api.weixin.qq.com/sns/jscode2session?appid=' + appId + '&secret=' + secret + '&js_code=' + code + '&grant_type=authorization_code',
						      data: {},
						      method: 'GET',
						      header: {
						          'content-type': 'application/json'
						      },
						      success: (res) => {
								console.log(res)
						  		_this.openid = res.data.openid; //昵称
						  		_this.session_key = res.data.session_key; 
						  		uni.setStorageSync('openid', _this.openid);
						  		uni.setStorageSync('session_key', _this.session_key);
								_this.updateUserInfo();
						        uni.hideLoading();
						      }
						  });
						   //将用户登录code传递到后台置换用户SessionKey、OpenId等信息
						   //...写用code置换SessionKey、OpenId的接口
                            //置换成功调用登录方法_this.updateUserInfo();
						}else{
                            uni.showToast({title: '登录失败!',duration: 2000});
							console.log('登录失败!' + res.errMsg)
						}
				  },
				});
			},
			 //向后台更新信息
			updateUserInfo() {
				
				let _this = this;
				    // 这里添加您的逻辑
					if(uni.getStorageSync('token')){
						wx.switchTab({
							url:'../index/index'
						})
					} else {
						uni.reLaunch({//信息更新成功后手机号登录
							url: '/pages/index/checklogin'
						});
					}
				
				// 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>
<style>
	page{
		width: 100%;
		height: 100%;
	}
	
</style>
<style lang="scss" scoped>
	.login-header{
		margin: 90rpx 0 90rpx 50rpx;
		border-bottom: 1px solid #ccc;
		text-align: center;
		width: 650rpx;
		height: 300rpx;
		line-height: 450rpx;
		image{
			width: 200rpx;
			height: 200rpx;
		}
	}
	.content {
	    margin-left: 50rpx;
	    margin-bottom: 90rpx;
	}
	
	.content text {
	    display: block;
	    color: #9d9d9d;
	    margin-top: 40rpx;
	}
	.login-btn {
	    border-radius: 80rpx;
	    margin: 70rpx 50rpx;
	    font-size: 35rpx;
	}
</style>
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值