适用vue项目
说明
- 具体思路
- 方法
思路:
- 微信公众平台注册一个测试号
- 拿到测试号中appId
- 扫描测试号二维码并关注
- 网页服务-网页账号-网页授权获取用户基本信息-修改:将部署好的域名放入(注意:不需要http://前缀)
- 传出code拿到token
代码:
- 创建文件 src/assets/js/authorization/authorization.js
class Authorization {
// 获取code
getCode() {
var local = window.location.href; // 获取页面url
var appid = "wx80ec87a1c18e0afa";
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`;
}
// 截取url中的code方法
getUrlCode(variable) {
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i = 0; i < vars.length; i++) {
var pair = vars[i].split("=");
if (pair[0] == variable) {
return pair[1];
}
}
return "";
}
}
export {
Authorization
}
- 首页(需要授权页面)引入authorization.js以及api.js(axios二次封装有说明)
以下为js代码
import { Authorization } from "../assets/js/authorization/index";
import { ApiModel } from "../assets/js/request/api";
const authorization = new Authorization();
const apimodel = new ApiModel();
data() {
return {
code: "",
};
},
created() {
//思路:
//1.获取token,如果获取到token则授权成功
//2.若没有token,则获取通过微信公众号提供的方法获取code
//3.判断this.code是否为空,若为空则通过getUrlCode()截取code
//4.若code不为空,则执行getToken()方法拿到token,并将token缓存
const token = window.localStorage.getItem("token");
if (token) {
console.log("授权成功!");
} else {
this.code = authorization.getUrlCode("code");
if (this.code == "") {
this.code = authorization.getCode("code");
} else {
this.getToken();
console.log("授权成功!");
}
}
},
methods: {
// 获取token
getToken() {
let code = {
code: this.code,
};
apimodel
.getAuthorizations(code)
.then((res) => {
window.localStorage.setItem("token", res.data.access_token);
})
.catch((err) => {
if (err.response) {
console.log(err.response);
}
});
},
}