uniapp 微信授权登录功能实现

uniapp 微信授权登录功能实现

微信授权登录

很多app都有第三方账号登录,常见的就是 微信/QQ/支付宝/淘宝等第三方账号登录。

下面说明一下微信授权的登录的全过程。

uni.login({})

...mapActions([
   'loginAction',
 	"userInfoAction",
 	"codeAction"
  ]),
_this = this;
uni.login({
  provider: 'weixin',
  success: function (loginRes) {
  //通过微信授权可以拿到一些数据,如:openId,此处的contype:form代表数据请求是通过form-data的形式传递的,这个前面的博文中有提到。
	_this.$store.commit("wxLoginInfoFn", loginRes.authResult);
	_this.$request.urlRequest(
		'/user/checkOpenId',//此处的接口是后台提供的。如果微信已经注册过,则返回为true
		{
			"openId": loginRes.authResult.openid,
			"contype": "form"
		},
		'POST',
		function (res) {
			if(res.result){ //注册过
				_this.loginAction({//此处的方法是写入到store中的action中的登录方法
					"appId": "wx9b0c3683xxxxxxxx",
					"openId": loginRes.authResult.openid,
					"type": "1"
				}).then((res) => {
					if(res.code === 200){
						_this.getUserInfo();
						// 以下的代码可以注释掉,通过后台返回的数据来获取。因为后台没有返回已经注册过的微信信息,所以此处代码是为了再次获取微信的信息。
						uni.getUserInfo({
						  provider: 'weixin',
						  success: function (infoRes) {
							  console.log("微信",infoRes.userInfo);
							  _this.$store.commit("wxUserInfoFn", infoRes.userInfo);
							  console.log("getUserInfo",infoRes.userInfo)
						  },
						  fail: () => {
						  }
						});
					}else{
						console.log(res)
						uni.showToast({
							title: res.msg,
							icon: 'none',
							duration: 4000
						});
					}
				});
			}else{ //未注册
				// 获取用户信息  获取微信授权
				uni.getUserInfo({
				  provider: 'weixin',//供应商为微信
				  success: function (infoRes) {
					  console.log("微信",infoRes.userInfo);//此处可以获取到微信的信息
					  _this.$store.commit("wxUserInfoFn", infoRes.userInfo);//此处代码是将微信的信息存储到store中的state中。
					  _this.$store.commit("wxLoginFn", true);
					  console.log("getUserInfo",infoRes.userInfo)
					  uni.showToast({title:"授权成功!"});
				  },
				  fail: () => {
					  uni.showToast({title:"授权失败"});
				  }
				});
			}
		}
	)
  },
  fail: () => {
	  uni.showToast({title:"微信登录授权失败"});
  }
});

在这里插入图片描述

评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

叶浩成520

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

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

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

打赏作者

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

抵扣说明:

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

余额充值