uniapp h5实现微信公众号登录

 官方说明文档:https://developers.weixin.qq.com/doc/offiaccount/OA_Web_Apps/Wechat_webpage_authorization.html
下面就直接写登录过程了


 


						
							
							授权登录
						
						
        onLoad(options) {
			// #ifdef H5
			if (options.code == null) {
			} else {
				this.sendCode(options.code)
			}
			// #endif
				
		},
goToLoginH5() {
	let _this = this;
	uni.showModal({
		title: '提示',
		content: '需要小程序授权',
		success: (res) => {
			if (res.confirm) {
				_this.getWeChatCode();
			} else if (res.cancel) {
				uni.showToast({
					title: '未授权',
					icon: 'none'
				})
			}
	    }
	});
				
},
//请求微信接口,用来获取code
getWeChatCode() {
	let code = this.getUrlCode('code')
	if (code == null) {
		this.getpower()
	} else {
		this.sendCode(code)
	}
},
//方法:用来提取code
getUrlCode(name) {
	return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.href) || [, '' ])[1].replace(/\+/g, '%20')) || null
},
getpower() {
	let local = encodeURIComponent(window.location.href); //获取当前页面地址作为回调地址
	let appid = 'wx40ee16f1bc9eb844'
	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'
				
},
sendCode(code){
	let _this = this;
	loginWxOfficial({
		"form": {
			"code": code
		},
	}).then(res => {
	_this.uid = res.data.userId
	uni.setStorageSync('token', res.data.token)
	_this.getUserinfo()
	}).catch(err=>{
		alert(err+'err1')
	})
},
getUserinfo() {
	let _this = this;
	userInfo().then(res => {
	    if (res.status == 200) {
		    _this.userInfo = res.data.userInfo
		    uni.setStorageSync('userInfo', res.data.userInfo)
	    }
    })
},

你可能感兴趣的:(uni-app)