admin管理员组文章数量:1567288
授权登录的官方文档:官方文档
前提:
在微信公众号请求用户网页授权之前,开发者需要先到公众平台官网中的“开发 - 接口权限 - 网页服务 - 网页帐号 - 网页授权获取用户基本信息”的配置选项中,修改授权回调域名。请注意,这里填写的是域名(是一个字符串),而不是URL,因此请勿加 http:// 等协议头
下面是详细步骤:
1、点击授权访问以下链接获取code
<view class="btn"><button type="primary" @tap="getUserInfo">一键授权</button></view>
redirect_uri是授权后需要重定向的地址,在后台配置即可
// 点击授权方法
getUserInfo() {
window.location.href = 'https://open.weixin.qq/connect/oauth2/authorize?appid=公众平台的appid&redirect_uri=http://xxxxx/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/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,这个看项目需要)
版权声明:本文标题:uni-app微信公众号授权登录 内容由热心网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:https://www.elefans.com/xitong/1726186310a1059558.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论