思路:當你點進來的時候先判斷地址欄上有沒有code痛黎,如果有code那么直接截取發(fā)給后端围来,如果沒有的話就跳轉到這個地址(這里需要填寫自己的appId)痛垛,需要傳入一個回調地址,這樣微信就知道怎么再跳轉回來粹淋,這里的回調地址就是你當前剛點進來的這個地址,你這里只要寫window.location.href即可瑟慈,這樣跳轉回來的時候你會發(fā)現(xiàn)url上多出了一個code桃移,前端只需要拿到當前的code,然后傳給后臺葛碧,后臺獲取到openid借杰,返回給我們即可,然后我們存起來就可以啦
"https://open.weixin.qq.com/connect/oauth2/authorize?appid=appid" +
"&redirect_uri=" +
encodeURIComponent(window.location.href) +
"&response_type=code" +
"&scope=snsapi_base" +
"&state=1#wechat_redirect";
<template>
<div id="app">
<keep-alive>
<router-view class="router"></router-view>
</keep-alive>
</div>
</template>
<script>
import wxConfig from "./wx/wxConfig";
import axios from "axios";
import { get_openid, getOpenId } from "./api/app";
import { mapMutations } from "vuex";
export default {
data() {
return { transitionName: "slide-right" };
},
name: "App",
async mounted() {
// http://192.168.2.51/?code=071bJnFa1ymwUz0IhgJa1xsx1B4bJnFz&state=1#/
await wxConfig(); // 初始化jssdk
await this.getOpenId();
},
methods: {
...mapMutations(["setopenId"]),
GetRequest() {
var url = location.search;
var theRequest = new Object();
if (url.indexOf("?") != -1) {
var str = url.substr(1);
strs = str.split("&");
for (var i = 0; i < strs.length; i++) {
theRequest[strs[i].split("=")[0]] = unescape(strs[i].split("=")[1]);
}
}
return theRequest;
},
async getCode() {
let search = window.location.search;
let code = search
.split("&")[0]
.split("?")[1]
.split("=")[1];
const res = await getOpenId({ code });
if (res.status == 200) {
let openid = res.result;
this.setopenId(openid);
localStorage.setItem("openid", openid);
} else {
}
},
async getOpenId() {
let code = this.GetRequest()["code"];
if (code == "" || code == null) {
window.location.href =
"https://open.weixin.qq.com/connect/oauth2/authorize?appid=*******************" +
"&redirect_uri=" +
encodeURIComponent(window.location.href) +
"&response_type=code" +
"&scope=snsapi_base" +
"&state=1#wechat_redirect";
} else {
this.getCode();
}
},
},
};
</script>