uni-app-微信公众号静默授权


前言

提示::公司的公众号用户,与后台系统的账号系统做绑定,用以推送消息

公众号自定义菜单直接链接到以下页面,进行静默授权,然后用户输入系统的分配的账号进行与微信的绑定和解绑。

页面如下:
请添加图片描述


  • onLoad:页面加载,在onLoad中发送请求比较合适的,即页面一加载就发送请求获取数据。
  • onShow:页面显示,会触发多次,只要页面隐藏,然后再显示出来都会触发。这里会重复触发,如果你重复发送请求不合适。
  • onReady:页面初次渲染完成了,但是渲染完成了,请求获取数据,就太慢了。

一、onLoad钩子中调用

最大的好处就是授权时,不会出现的页面空白的情况

onLoad() {
    
    }

二、使用步骤

代码有注释,如果不太明白多看几遍,if判断执行的时机,根据数据的缓存而执行。如果有openId,onload内的代码块不会执行,否则以下必然会执行以下一种情况。

// wechatAppId公众号的标识,改成自己的
	import {
    
    
		wechatAppId,
	} from '@/common/settings'
		onLoad() {
    
    
			//看看本地是否有openId
			const openId = uni.getStorageSync("openId")
			//看看本地是否有code,这个是公众号code
			const code = uni.getStorageSync("code")
			// 截取链接的code,具体方法在下面有
			const urlCode = this.getUrlCode().code
			if (!code && !urlCode && !openId) {
    
    
				//不存在存储的code 不存在地址参数code 不存在openid
				//存储当前初始页面历史列表数量
				uni.setStorageSync("historyLength", history.length);
				//local 回调地址,换成自己的
				const local =
'https://127.0.0.1:8080/pages/account/BindAndUnbind/BindAndUnbind'
				//encodeURIComponent对链接转码,这一步必须
				const uri = encodeURIComponent(local)
				//调转页面
				document.location.replace(
					`https://open.weixin.qq.com/connect/oauth2/authorize?appid=${
      
      wechatAppId}&redirect_uri=${
      
      uri}&response_type=code&scope=snsapi_base&state=123#wechat_redirect`
				)
			} else if (urlCode && !openId) {
    
    
				//存在地址参数code 不存在openid
				uni.setStorageSync('code', urlCode);
				const historyLength = uni.getStorageSync("historyLength");
				//跳转回初始页面
				history.go(-(history.length - historyLength));
			} else if (code && !openId) {
    
    
				//存在存储的code 不存在openid
		
				//请求后端接口获取用户的信息
				uni.$u.post('/api/login/volkswagen-login', {
    
    
					'webChatCode': code
				}).then(res => {
    
    
					if (res.code === 0) {
    
    
						uni.removeStorageSync('code');
						this.$u.toast("授权成功")
						uni.setStorageSync("openId", res.data.openId)
						uni.setStorageSync("openIdData", res.data)
						this.$u.vuex('openId', res.data.openId)
					} else {
    
    
						uni.removeStorageSync('code');
						this.$u.toast("code授权失败")
						uni.setStorageSync("openId", res.data.openId)
						uni.setStorageSync("openIdData", res.data)
						this.$u.vuex('openId', res.data.openId)
					}
				}).catch(err => {
    
    
					uni.removeStorageSync('code');
					this.$u.toast("catch授权失败")
				})
			}
		},

截取url中的code

			// 截取url中的code
			getUrlCode() {
    
    
				// 截取url中的code方法
				const url = location.search
				const theRequest = new Object()
				if (url.indexOf('?') != -1) {
    
    
					let str = url.substr(1)
					let strs = str.split('&')
					for (let i = 0; i < strs.length; i++) {
    
    
						theRequest[strs[i].split('=')[0]] = strs[i].split('=')[1]
					}
				}
				return theRequest
			},

猜你喜欢

转载自blog.csdn.net/qq_34082921/article/details/132499228