uniapp:微信H5授权
uniapp微信H5授权代码
<template>
<view />
</template>
<script>
import {
ApiModel
} from "../../static/request/api";
const apimodel = new ApiModel();
export default {
data() {
return {
code: "",
};
},
mounted() {
this.getAuth();
},
methods: {
/*
------------------------授权-------------------------------------
*/
getAuth() {
this.code = this.getUrlCode("code");
if (!this.code) {
this.getCode();
} else {
this.getToken();
}
},
/*
-------------------------3、获取token-----------------------------------
*/
getToken() {
let code = {
code: this.code,
};
apimodel.getAuthorizations(code).then(
(res) => {
uni.setStorage({
key: "token",
data: res.data.access_token
})
this.code = "";
uni.redirectTo({
url: "/pages/index/userInfo"
})
},
(err) => {
err;
this.code = "";
}
);
},
/*
----------------------------------1、获取code---snsapi_userinfo---------------------------------------
*/
getCode() {
const local = window.location.href;
const appid = "wx5f0b9b679cf33479";
window.location.href = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${encodeURIComponent(
local
)}&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect`;
},
/*
----------------------------2、截取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;
}
},
};
</script>

浙公网安备 33010602011771号