微信公众号跳转h5授权登录

目录

授权登录

静默登录:静默授权用户是没有感知的,只能获取用户的user_id(PID),

主动授权:需要用户去进行点击授权确定按钮的,拿到用户的user_id(PID)、头像、昵称等信息。

确认公众号类型

首先先确认自己的公众号是订阅号还是服务号,订阅号是没办法进行网络授权的,必须是服务号才能够网络授权。

网络授权

在公众号的微信认证进行网络授权

将文件下载后给后端,放入到根目录,域名是和你线上的域名一样。

接下来就是在代码编写

methods: {
			/*微信登录相关  start*/
			//方法:用来判断是否是微信内置的浏览器
			isWechat() {
			        return String(navigator.userAgent.toLowerCase().match(/MicroMessenger/i)) === "micromessenger";
			},
			//方法:用来提取code
			getUrlCode(name) {
				return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.href) || [, ''])[1]
					.replace(/\+/g, '%20')) || null
			},
			//检查浏览器地址栏中微信接口返回的code
			checkWeChatCode() {
				let code = this.getUrlCode('code')
				uni.showToast({
					title:`微信code=${code}`
				})
				if (code) {
					
					this.getOpenidAndUserinfo(code)
				}
			},
			//请求微信接口,用来获取code
			getWeChatCode() {
				let local = encodeURIComponent(window.location.href); //获取当前页面地址作为回调地址
				let appid = '自己的appid'
				
				//通过微信官方接口获取code之后,会重新刷新设置的回调地址【redirect_uri】
				window.location.href =
					"https://open.weixin.qq.com/connect/oauth2/authorize?appid=" +
					appid + 
					"&redirect_uri=" +
					local +
					"&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect";
			},
			//把code传递给后台接口,静默登录
			getOpenidAndUserinfo(code) {
				this.$http({
					url:'api/login',
					data:{
						code:code
					}
				}).then((res) => {
					console.log(res)
					if (res.code != 0) {
						uni.showToast({
							title: res.msg,
							duration: 3000,
							icon: 'none'
						});
						return
					}else{
						this.afterLogin(res)
					}
				})
			},
			/*微信登录相关  end*/
			afterLogin(res){
				let user = res.data.user
				uni.setStorageSync('token', res.data.token);
				let u = {
					avatar: user.avatar ? user.avatar : this.avatar,
					mobile: user.mobile,
					nickname: user.nickname ? user.nickname : '土肥圆'
				}
				uni.setStorage({
					key: 'u',
					data: u,
					success: () => {
						
						let url = uni.getStorageSync('redirect')
						uni.reLaunch({
							url: url ? url : '/pages/index'
						})
					}
				});
			},
		},

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值