最近公司需要开发一个公众号社区项目,需要让当前微信用户和社区大区绑定一下。所以就有了这个试错的过程。
详解微信开放的测试号配置
这些域名都需要配置好,不然会报错。
上面就是微信提供给开发者测试使用的配置页面。
调用微信接口获取code
// utils.js
const getURLParam = function (name, targetUrl) {
var reg = new RegExp('[?&]' + name + '=([^&]+)')
targetUrl = targetUrl || window.location.search
var newurl = decodeURIComponent(targetUrl)
return newurl.match(reg) ? RegExp.$1 : null
}
// 获取微信用户code
async getCode() {
let appid = 'aaa'; // 这里就是微信提供的测试appid
let url = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${encodeURIComponent(location.href)}&response_type=code&scope=snsapi_userinfo&state=STATE&connect_redirect=1#wechat_redirect`;
const _code = utils.getURLParam("code", location.href);
//如果没有code 去获取code
if (_code == null) {
window.location.href = url;
}else{
//获取到code传递给后端获取token
await this.getToken(_code)
}
},
getToken(code) {
// 调用后端接口
}
调用微信api后就会自动跳转到指定的url,并且会携带code,所以我们就可以获取code。
下面是手机抓包看到的内容。
以上前端的任务就完成了。
但是需要注意一点。后端在调用微信api获取微信信息时,出现了48001错误。
user info{"errcode":48001,"errmsg":"api unauthorized, rid: 030ac-374d39bd"}
这里来看一下scope属性值
-
snsapi_base 不需要用户点同意,直接跳转到授权后的页面,只能用于获取openid,不能获取用户基本信息。
-
snsapi_userinfo 会征求用户同意,授权后,可以获取用户基本信息。
48001错误就是使用了snsapi_base,我们需要将其修改成snsapi_userinfo,让其可以获取微信用户信息。