uniapp h5实现微信公众号登录

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


 

<!-- #ifdef H5 -->
						<tn-button @click="goToLoginH5" shape="round" backgroundColor="#FFFFFF10" fontColor="#ffffff"
							padding="40rpx 0" width="50%">
							<text class="tn-icon-wechat tn-padding-right-xs tn-text-xl"></text>
							<text class="">授权登录</text>
						</tn-button>
						<!-- #endif -->
        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)
	    }
    })
},

文章来源地址https://uudwc.com/A/Mx3jJ

原文地址:https://blog.csdn.net/m0_58135258/article/details/133072028

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请联系站长进行投诉反馈,一经查实,立即删除!

h
上一篇 2023年09月24日 05:00
Linux之Web服务器配置(Apache)
下一篇 2023年09月24日 05:04