uniapp 开发 h5 授权微信登录(静默和非静默)

具体流程:

进入 h5 ➡️ 静默登录 ➡️ 请求登录接口 ➡️ 必要时候调起登录组件 ➡️ 点击按钮进行非静默登录 ➡️ 再次请求登录接口 ➡️ 获取到所有用户数据

一、封装登录 function

authLogin: (callback) => {
	const that = this;
	// 判断是否是在微信环境下运行
	if (utils.isWechat()) {
		const token = window.localStorage.getItem('__token');
		const unionid = window.localStorage.getItem('__unionid');
		const loginType = window.localStorage.getItem('__loginType');
		// 有token证明登录过,可直接进行回调
		if (token) {
			callback();
			return;
		}
		if (!unionid) {
		    // 判断登录方式为静默或非静默, snsapi_base 静默,snsapi_userinfo 非静默
			const snsapi = loginType == "snsapi_userinfo" ? "snsapi_userinfo" : "snsapi_base";
			// 获取 code 方法,附文章最下边
			let _code = utils.getUrlParam("code");
			if (_code == null || _code === "") {
				// 进行微信授权,附文章最下边
				// 传当前页面的URL(微信授权完之后返回到的页面)和 登录方式
				utils.getWXCode(window.location.href, snsapi);
			} else {
				uni.request({
					url: '登录请求接口',
					method: "GET",
					data: {
						code: _code,
						snsapi: snsapi
					},
					success: (res) => {
						// 静默登录获取到的 unionid 为假数据,我这里后端接口设置静默登录时候返回为 "" ,方便后面判断是否需要非静默登录
						window.localStorage.setItem('__unionid', res.data.data.unionid);
						window.localStorage.setItem('__token', res.data.data.token);
						window.localStorage.setItem('__openid', res.data.data.openid);
						window.localStorage.removeItem('__loginType');
						// 登录成功后的回调,我这里的每个接口请求都需要在有token的前提下进行
						callback();
					},
					fail: (err) => {
						// alert("err");
						uni.hideLoading();
						uni.showToast({
							title: '登录失败'
						})
					},
				})
			}
		}
	} else {
		uni.showModal({
			title: '错误提示',
			content: '请在微信客户端打开链接',
			showCancel: false,
			success(res) {
				if (res.confirm) {}
			}
		})
	}
},

二、封装非静默登录组件

<template>
	<view class="login-container">
		<view class="login-close" @click="closeLogin"></view>
		<view class="login-main">
			<view class="close-btn">
				<image class="" src="../../static/icon/close3.png" mode="widthFix" @click="closeLogin"></image>
			</view>
			<view class="logo">
				<image src="../../static/img/logo.png" mode="widthFix"></image>
			</view>
			<view class="txt">登陆后体验完整功能哦!</view>
			<button class="login-btn" @click="login">微信登录</button>
		</view>
	</view>
</template>

<script>
	import utils from '../../utils/utils.js';
	export default {
		data() {
			return {}
		},
		props: ['page'],
		onLoad() {},
		methods: {
			login() {
			    // 非静默登录前先把token缓存清除,否则授权完之后跳转过去不会请求登录接口
				window.localStorage.removeItem('__token');
				// 设为非静默
				window.localStorage.setItem('__loginType', 'snsapi_userinfo');
				utils.getWXCode(this.page, 'snsapi_userinfo');
			},
			closeLogin() {
				this.$emit('closeLogin', false);
			}
		}
	}
</script>

<style lang="less" scoped>
	.login-container {
		position: fixed;
		top: 0;
		left: 0;
		width: 100vw;
		height: 100vh;
		background-color: rgba(0, 0, 0, 0.6);
		z-index: 99;

		.login-close {
			position: fixed;
			top: 0;
			left: 0;
			width: 100%;
			height: calc(100% - 630rpx);
		}

		.login-main {
			position: fixed;
			bottom: 0;
			left: 0;
			width: 100%;
			height: 630rpx;
			background-color: #fff;
			border-radius: 16rpx 16rpx 0 0;

			.close-btn {
				display: flex;
				align-items: center;
				justify-content: flex-end;
				padding: 30rpx 30rpx 0;
				// position: absolute;
				// top: 30rpx;
				// right: 30rpx;


				image {
					width: 40rpx;
					height: 40rpx;
				}
			}

			.logo {
				display: flex;
				align-items: center;
				justify-content: center;

				image {
					width: 170rpx;
					height: 170rpx;
				}
			}

			.txt {
				margin-top: 40rpx;
				font-weight: 500;
				font-size: 36rpx;
				color: #333333;
				text-align: center;
			}

			.login-btn {
				margin: 96rpx 30rpx 0;
				color: #fff;
				background-color: #49C265;
			}
		}
	}
</style>

三、使用组件

<template>
	<view class="content">
		<!-- 登录组件 -->
		<loginMask v-if="showLogin" :page="myPage" @closeLogin="closeLogin"></loginMask>
	</view>
</template>

<script>
	import utils from '../../utils/utils.js';
	import loginMask from '../../components/login/login.vue';

	export default {
		data() {
			return {
				showLogin: false,
				myPage: '当前页面的链接,不能使用 window.location.href,防止携带code',
			}
		},
		components: {
			loginMask
		},
		onLoad() {
			const that = this;
			// 调用封装好的登录function
			// 登录function封装好后可以放在 Vue.prototype 上,直接this.authLogin调用
			// 也可以放在utils.js中,用utils.authLogin调用
			that.authLogin(() => {
				that.goodsList();
			})
		},
		methods: {
			goodsList() {
				const that = this;
				uni.request({
					url:"请求接口"
				})
			},
			closeLogin(e) {
				this.showLogin = e;
			},
			// 在需要展示登录组件的时候让 this.showLogin = true
		}
	}
</script>

<style lang="less" scoped></style>

四、utils/utils.js

export default {
	// 判断是否为微信环境
	isWechat: () => {
		var ua = navigator.userAgent.toLowerCase();
		var isWXWork = ua.match(/wxwork/i) == 'wxwork';
		var isWeixin = !isWXWork && ua.match(/MicroMessenger/i) == 'micromessenger';
		return isWeixin;
	},

	// 获取code并登录   
	getWXCode: async (url, snsapi) => {
		let appid = '' //公众号的唯一标识
		let local = encodeURIComponent(url); //授权后重定向的回调链接地址
		let time = +new Date(); //时间戳
		window.location.href =
			`https://open.weixin.qq.com/connect/oauth2/authorize?
				appid=${appid}&
				redirect_uri=${local}&
				response_type=code&
				scope=${snsapi}&
				state=1&
				time=${time}#wechat_redirect`;
	},

	// 截取code
	getUrlParam: (name) => {
		let reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
		let r = window.location.search.substr(1).match(reg);
		if (r != null) {
			return unescape(r[2]);
		}
		return null;
	},
}
  • 4
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
要在uniapp开发H5登录微信公众号并进行联调,有以下几个步骤: 1. 获取微信开发者账号和相关配置信息:首先需要在微信开放平台注册并创建一个开发者账号,然后创建一个微信公众号,并获取相应的AppID和AppSecret等配置信息。 2. 在uniapp项目中配置相关插件:在uniapp项目的manifest.json文件中,添加对应的插件配置,如"@dcloudio/uni-mp-weixin"插件。然后在项目的App.vue中通过uni.login方法获取登录凭证code,并调用uni.request方法发送请求到服务器获取用户的openid和session_key。 3. 前端与后端的联调:根据服务器返回的用户openid和session_key,在前端进行相关的业务逻辑处理,如展示用户信息、跳转到其他页面等。其中,服务器端需要处理用户的登录请求,并返回openid和session_key等信息给前端。 4. 微信公众号授权设置:在微信公众号后台设置中,配置网页授权域名和回调地址,并将uniapp项目的H5链接添加到公众号菜单中。 5. 测试和调试:完成以上步骤后,进行测试和调试,确保登录功能在H5中正常使用。可以通过调试工具、日志打印等方式进行定位和解决问题。 总结:在uniapp开发H5登录微信公众号的联调过程中,需要进行微信开发者账号和相关配置的准备,配置相关插件和设置,前端与后端的联调,以及进行测试和调试。通过这些步骤,可以实现在uniapp项目中登录微信公众号并进行H5联调。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

陈龙龙的陈龙龙

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值