1. 登录微信公众平台,网址:mp.weixin.qq.com/
2. 进入接口权限页面,找到“网页授权获取用户基本信息”接口
登录成功后跳转至公众号管理界面------->找到一级菜单“开发”下面的“接口权限”-------->点击“接口权限”后显示接口列表------->接口中找到“网页服务”类目的“网页授权”下的“网页授权获取用户基本信息”接口
3. 进入功能配置页面
点击接口最右边“修改”,进入功能配置页面
然后点击“网页授权域名右侧”的设置,弹出修改窗口
4. 设置网页授权域名
按要求下载图示中的.txt文件,放置至域名服务器的根目录下或项目的根目录下,按要求输入名域名然后保存,这样网页授权域名就设置好了
注意:要想获取openid,还需要将您的网页部署到设置的域名下,需要注意的是不能加端口,因为微信公众号默认只支持80或443端口,否则会报错“reditect_uri 参数错误”,如下图
5. 代码实现
按照开发文档教程调用接口,文档链接贴上developers.weixin.qq.com/doc/offiacc…
(1)获取code
let local = encodeURIComponent(window.location.href); // 对url进行编码
let appId = this.appId; // 公众号openid
let url = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appId}&redirect_uri=${local}&response_type=code&scope=snsapi_userinfo&state=123#wechat_redirect`;
window.location.href = url;
(2)使用code,调用接口获取用户openid
由于我们是通过后端调用微信接口获取微信用户信息,所以前端只需要调用后端提供的api接口通过axios方式便可获取到用户微信信息
export default{
methods: {
async getOpenId(code) {
let res = await getOpenId({ code: code }); // 此处为调用后端提供的api接口
if (res) {
// to do something......
}
},
// 截取url中的参数方法
getUrlParams() {
let url = location.search;
let paramsObj= new Object();
if (url.indexOf("?") != -1) {
let str = url.substr(1)
let strs = str.split("&")
for (let i = 0; i < strs.length; i++) {
paramsObj[strs[i].split("=")[0]] = (strs[i].split("=")[1])
}
}
return paramsObj
}
},
async mounted() {
// 如果链接中code值存在,则调用接口取微信access_token,openid等值
if (this.getUrlParams().code) {
await this.getOpenId(this.getUrlParams().code);
}
// 跳转链接获取code值
if (!this.openId && !this.getUrlParams().code) {
let local = encodeURIComponent(window.location.href);
let appId = this.appId;
let url = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appId}&redirect_uri=${local}&response_type=code&scope=snsapi_userinfo&state=123#wechat_redirect`;
window.location.href = url;
}
},
}
所有设置和开发OK了,就可以实现获取微信用户信息啦~~~~