当前位置:网站首页>H5网页获取微信授权登录

H5网页获取微信授权登录

2022-11-24 21:35:58zrong180106

进入页面判断是否获取code,

有code 则直接拿code去调后端接口让后端返回token,进而再调用获取用户信息的接口

mounted() {
    
			this.code = this.getQueryVariable('code')
			console.log('打印检查回调后是否获取到了code', this.code)
			// 如果已经是回调过来的函数,那就直接调用validToken来获取token,获取用户信息
			if (this.code) {
    
				console.log('进入页面判断是否获取到code,获取到后直接调用validToken,否则用户点击登录按钮登录')
				this.validToken();
			} else {
    
				this.getCode()
			}
			
		},

获取code,

注意回调后页面会刷新,进入到设置的回调地址

methods: {
    
			// 获取code
			getCode() {
    
				let link = window.location.href; 
				let code = this.getQueryVariable('code')
				// 已经授权登录过的就不用再授权了
				// 如果拿到code,调用授权接口,没有拿到就跳转微信授权链接获取
				if (code) {
    
					// 调用后台接口,授权 
					this.validToken()
				} else {
    
					var wxUrl =
						'https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx8129a1d96769c88c&redirect_uri=http%3A%2F%2Fwww.draw-motion.com&response_type=code&scope=snsapi_userinfo&state=12234&#wechat_redirect' 
					console.log('window.location.href---', wxUrl)
					window.location.href = wxUrl; // 这个时候页面一定会刷新,进入到给的redirect_uri中
				}
			},
			// 截取code函数,history模式
  //跳转后的地址格式为: http://www.draw-motion.com/?code=041ib51w34ztIY2DRc1w3oMBqY3ib51f&state=12234
			getQueryVariable(variable) {
    
				console.log('调用getQueryVariable来截取code')
				// window.location.href = 'http://192.168.3.220:8080/?code=071vWoml2lkgm94G7xol2lzcK72vWome&state=#/pages/user/index'
				var query = window.location.search.substring(1);
				var vars = query.split("&")
				for (var i = 0; i < vars.length; i++) {
    
					var pair = vars[i].split("=");
					// commit('SET_CODE', pair[1])
					if (pair[0] == variable) {
    
						return pair[1];
					}
				}
				return (false);
			},
			// 通过后端请求token
			async validToken(){
    
			      const res = await tokenIsValid({
    
			        code:this.code,
			        token:this.token
			      });
				  console.log('请求token后返回值', res)
			      if(res.code === 200){
    
			        this.code = res.content.code;
			        this.token = res.content.token;
					console.log('打印请求token接口的返回值', res.code)
			        // document.cookie = `token=${this.token};max-age=`+8*24*60*60;
					// uni.setStorageSync('token', res.data.data.token);
			        console.log('code',this.code,'token',this.token);
			        this.getUserInfos();
			      }else{
    
			        // alert('出现错误!请返回首页!ss', this.code,this.token)
					alert(this.code)
			        console.log('code-token-500',this.code,this.token);
			    uni.redirectTo({
    
			    			url: 'http://192.168.3.220:80/', // 首页
			    		});
			      }
			    },
				// 获取后台返回用户信息
				async getUserInfos(){
    
				  const info = await getUserInfo({
    
				    code:this.code,
				    token:this.token
				  });
				  if(info.code === 200){
    
				    console.log('用户信息',info.content)
				  }
				},
		}
	}
原网站

版权声明
本文为[zrong180106]所创,转载请带上原文链接,感谢
https://blog.csdn.net/qq_44830060/article/details/127802917

随机推荐