微信网页授权,我们都知道有两种,一种是静默授权,一种是需要用户同意的授权。两种授权方式的区别就在于 ,静默授权自动跳转到回调页面,拿取到的信息只要用户的openid,而另外一种弹窗授权,则可以拿到用户的基本信息,而且用户无需关注公众号。

好了,说到这里,我们就来说一说用uniapp H5来做公众号的授权,在这里我就只写一种静默授权的模式吧。

1.首先我们需要在公众号中配置授权回调域名。(开发 - 接口权限 - 网页服务 - 网页帐号 - 网页授权获取用户基本信息”的配置选项中,修改授权回调域名
2.在uniapp 项目中新建一个登录授权页面,开始写我们的代码部分。

//一进入这个页面,我们就要先去查找链接里面是否带有code,如果有,那么,我们就拿取到这个code,直接去调取授权登录(自己后台给的接口)。如果没有,我们就需要跳转链接去拿取code
data(){
 	return {
	code:''
}
}
onLoad(){
	this.pageLoad();
},
methods:{
	pageLoad(){
		this.code=this.GetQueryString('code');
		if(this.code){
		//直接去登录发起请求
	} else {
		//获取code
		//静默授权
		this.getwx_authorize();
	}

},
//拉取授权
getwx_authorize(){
//授权的回调地址
	let redirect_uri=encodeURIComponent('http://xxx.com/h/pages/user/wxlogin');
	//这是我们公众号的appid
	let appid='wx2d87077a8abxxxx';
	//静默授权	
	window.location.href="https://open.weixin.qq.com/connect/oauth2/authorize?appid="+appid+'&redirect_uri='+redirect_uri+'&response_type=code&scope=snsapi_base&state=123#wechat_redirect'+'&t='+new Date().getTime();
	//非静默授权调取下面的这个地址,弹出授权接口,获取到用户信息
	window.location.href="https://open.weixin.qq.com/connect/oauth2/authorize?appid="+appid+'&redirect_uri='+redirect_uri+'&response_type=code&scope=snsapi_userinfo&state=123#wechat_redirect'+'&t='+new Date().getTime();
},
//获取url中参数的方法
	GetQueryString(name) {
				var url = window.location.href;
				try {
					var cs = url.split('?')[1]; //获取?之后的参数字符串
					var cs_arr = cs.split('&'); //参数字符串分割为数组
					for (var i = 0; i < cs_arr.length; i++) { //遍历数组,拿到json对象
						if (cs_arr[i].split('=')[0] == name) {
							return cs_arr[i].split('=')[1];
						}
					}
					return null;
				} catch {
					return null;
				}
			},
	//登录 这里就是自己的接口函数了。
				async getLogin(){
				const res =await this.$api.post('自己的接口地址',{
						'code': this.code,
						data:{}
				})
				console.log(res)
				if(res.status==1){
					uni.setStorageSync('token',res.result.token)
					uni.switchTab({
						url:'/pages/index/index'
					})
				} else {
					uni.showToast({
						title: res.message,
						icon: 'none',
						duration: 2000
					})
				}
			},
}




Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐