当前位置:网站首页>【微信公众号h5】授权
【微信公众号h5】授权
2022-07-21 13:37:00 【嘿,小苹果】
微信公众号,无法获取到用户的手机号
URL与Token都是要后台配置好的,直接叫后台给过来就好啦,域名一定要和URL的域名保持一致。
然后,在体验接口权限表里面找到网页帐号–网页授权获取用户基本信息,点击修改:
二、获取code
配置好以上回调域名等后,就可以写代码了。首先是获取code,需要打开如下页面:
https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=SCOPE&state=STATE#wechat_redirect
若提示“该链接无法访问”,请检查参数是否填写错误,是否拥有scope参数对应的授权作用域权限。
其中,这些参数说明在微信JSSDK说明文档里面都有说明,如下图:
配置好参数后,进入这个页面微信会返回code在回调的url里给我们:
然后,我们只需去url里截取这个code即可,但是我们发现这个code并不是跟在url的最后面,所以一开始我用vue的this.$route.query.code方法行不通,得用js进行截取,以下是我的代码
methods: {
getCode () {
// 非静默授权,第一次有弹框
this.code = ''
var local = window.location.href // 获取页面url
var appid = 'wx65adcf075369****'
this.code = this.getUrlCode().code // 截取code
if (this.code == null || this.code === '') {
// 如果没有code,则去请求
window.location.href = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${
appid}&redirect_uri=${
encodeURIComponent(local)}&response_type=code&scope=snsapi_userinfo&state=123#wechat_redirect`
} else {
// 你自己的业务逻辑
}
},
getUrlCode() {
// 截取url中的code方法
var url = location.search
this.winUrl = url
var theRequest = new Object()
if (url.indexOf("?") != -1) {
var str = url.substr(1)
var strs = str.split("&")
for(var i = 0; i < strs.length; i ++) {
theRequest[strs[i].split("=")[0]]=(strs[i].split("=")[1])
}
}
return theRequest
}
}
我的代码逻辑是先判断有没有code,没有才去获取,encodeURIComponent(),是对回调url进行编码,这个微信JSSDK说明文档里面都有说明。拿到code以后,传给后台,让后台去获取用户信息再传给前端。我们拿到用户信息后,比如openId,头像等,可以用localStorage缓存起来,这样就不用每次都去请求code,每次都去后台拿信息了。所以,我们可以在mounted钩子函数里面这样处理:
mounted() {
if(!window.localStorage.getItem('openId')){
// 如果缓存localStorage中没有微信openId,则需用code去后台获取
this.getCode()
} else {
// 别的业务逻辑
}
}
边栏推荐
- Tensorflow入门教程(三十七)——DC-VNet
- 计算机考研数据库题库
- 性能领域:你知道的越多,不知道的也就越多
- ES6 from getting started to mastering 06: arrow function this direction and precautions
- Map collection traversal in multiple ways
- solo 博客 文章的链接编辑提示非法链接
- 蔚来「城市」探索之路
- Photovoltaic power generation system and its MPPT control
- solo 博客的 Bubble 皮肤 文章详情的顶部图片怎么去掉
- 虚拟机无法连接互联网
猜你喜欢
随机推荐
How to drive growth strategy with innovation
Pycocotools installation method - one step~
Tensorflow入门教程(三十八)——V2-Net
【综合笔试题】难度 3.5/5,多解法热门二叉树笔试题
Comment emqx 5.0 atteint 100 millions de connexions mqtt dans la nouvelle architecture mria + rlog
判断一个人靠不靠谱,就看这3点
Matlab FCM fuzzy clustering
C # use objects comparer to compare objects
容器学习中的简答题
814. Binary tree pruning: simple recursive problem
性能领域:你知道的越多,不知道的也就越多
matlab-FCM模糊聚类
The darling of "all-optical" era - 400g optical module
【LeetCode】30、 串联所有单词的子串
FTP service and configuration
Operation of Py file
Openlayers:点聚合效果
The United States is eager to develop 6G or revisit its old dream of collecting 3G patent fees, but China has taken the lead
服务器时间自动同步
Tensorflow入门教程(三十七)——DC-VNet