uni-app微信公众号授权登录

授权登录的官方文档:官方文档

前提:
在微信公众号请求用户网页授权之前,开发者需要先到公众平台官网中的“开发 - 接口权限 - 网页服务 - 网页帐号 - 网页授权获取用户基本信息”的配置选项中,修改授权回调域名。请注意,这里填写的是域名(是一个字符串),而不是URL,因此请勿加 http:// 等协议头

下面是详细步骤:
1、点击授权访问以下链接获取code

<view class="btn"><button type="primary" @tap="getUserInfo">一键授权</button></view>

redirect_uri是授权后需要重定向的地址,在后台配置即可

			// 点击授权方法
			getUserInfo() {
				window.location.href = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=公众平台的appid&redirect_uri=http://xxxxx.com/xxx.html&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect'
				console.log(this.code);
				if(this.code){
					//将onLoad中的获取token方法放进来即可
				} else {
					//没有code就去获取code
				}
				
			},

这边在地址栏中就能看见了
在这里插入图片描述
由于它是跳转到了另一个页面,获取不到我想要的code,所以我让后台那边处理了一下,再跳回到我这边指定的页面,并把code一起返回给我

2、根据code获取token

从后台跳回来的时候传了一个code,在onLoad中接收code

		onLoad(option) {
			this.user_id = uni.getStorageSync("user_id");
			this.code = option.code
			console.log(option);
		}

在这里插入图片描述
有了code之后就能获取token了,可以自己去获取,也可以请求后台的接口
自己请求的话只要请求下面你的链接就行

https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=APPID&grant_type=refresh_token&refresh_token=REFRESH_TOKEN

我这边是请求后台的接口获取token

		onLoad(option) {
			this.user_id = uni.getStorageSync("user_id");
			this.code = option.code
			console.log(option);
			if(this.code){
				//这里是封装的请求方式,用普通uni.request也可以
				this.http.httpRequest('/api/login/getToken','post',{
					code:this.code
				}).then((res) => {
					if(res.code == 200){
						console.log(res);
						this.http.httpRequest('/api/login/login','post',{
							user_nickname:res.data.nickname,
							user_openid:res.data.openid,
							user_avatar:res.data.headimgurl
						}).then((res) => {
							if(res.code == 200){
								console.log(res);
								//成功后缓存到本地,其他地方要用到
								uni.setStorageSync('user_id',res.user_id)
								uni.setStorageSync('token',res.token)
								uni.switchTab({
									url:'mine'
								})
							} else {
								uni.showToast({
									icon:'none',
									title:res.msg
								})
							}
							
						})
					} else {
						uni.showToast({
							icon:'none',
							title:res.msg
						})
					}
					
				}).catch((err) => {
					console.log(err);
				})
			} else {
				uni.showToast({
					icon:'none',
					title:'请先登录'
				})
				//没有code在走一次流程去获取code
				.........
			}
		},

这样就能拿到个人信息数据了:
在这里插入图片描述

(文档中还有一个第三部刷新token,这个看项目需要)

  • 1
    点赞
  • 29
    收藏
    觉得还不错? 一键收藏
  • 8
    评论
评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值