1.新建 utils文件夹及wxauth.js
2.封装 wxauth.js(请求自己接口时要注意接口返回数据的结构)
import axios from 'axios';
import url from '../ui/URL.js';
//取Cookie的值
function GetCookie(name) {
var arg = name + "=";
var alen = arg.length;
var clen = document.cookie.length;
var i = 0;
while (i < clen) {
var j = i + alen;
if (document.cookie.substring(i, j) == arg) return getCookieVal(j);
i = document.cookie.indexOf(" ", i) + 1;
if (i == 0) break;
}
return null;
}
function getCookieVal(offset) {
var endstr = document.cookie.indexOf(";", offset);
if (endstr == -1) endstr = document.cookie.length;
return unescape(document.cookie.substring(offset, endstr));
}
//取Cookie的值end
var TOKEN = GetCookie('TokenKey');
if (TOKEN === 'null' || TOKEN === 'undefined') {
TOKEN = '';
}
//取Cookie的值 end
/**
* 微信公众号授权
* */
export function wxAuthorize() {
// 封装-静默授权
//if JNZgetOpenId 存储过 openid 这个为空 则重新存 openid
let isopenid=(localStorage.getItem("openid") == null || localStorage.getItem("openid") == "null")
let isgetopenid=(localStorage.getItem("JNZgetOpenId") == null || localStorage.getItem("JNZgetOpenId") == "null")
if(isopenid == true && isgetopenid == false){
var getYHxxData = localStorage.getItem('JNZgetOpenId'); // 读取字符串数据
var YHxxObj = JSON.parse(getYHxxData);
localStorage.setItem("openid", YHxxObj.openId);
}
let ISsq = (localStorage.getItem("openid") == 'null' || localStorage.getItem("openid") == null) && (localStorage.getItem("JNZgetOpenId") == null || localStorage.getItem("JNZgetOpenId") == "null")
let urlzt=window.location.href.indexOf('code='); //url中是否包含code
//没有openid并且没有JNZgetOpenId 并且 url中没有找到code(没有code就是没有打开过授权页)
// console.log('ISsq && urlzt----'+ISsq+'----'+urlzt+'----'+isopenid)
if(ISsq && urlzt==-1){
//获取微信网页授权的code 打开 `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${redirectUrl}&response_type=code&scope=snsapi_base&state=STATE&connect_redirect=1#wechat_redirect`授权
getAuthorize()
}else if(ISsq && urlzt!=-1){
//如果没有openid 但网页中已经有code 说明已经打开过授权页那么就获取url中的code【运行getAuthorize后第一次进来时没有存code】
getUrlcode()
}
}
//获取微信code和openid
function getAuthorize() {
// 获取微信网页授权的code 开始
const isWechat = () => {
let ua = window.navigator.userAgent.toLowerCase();
return ua.match(/MicroMessenger/i) == 'micromessenger';
};
//是微信中打开,则进行一下操作
if (isWechat) {
//获取微信网页授权的code
axios({
method: "get",
url: url.wx.getCodeSnsApiUserInfo,
headers:{
token:TOKEN
},
params: {
backUrl: window.location.href
},
}).then((response) => {
window.location.href = response.data.data
}).catch((error) =>
console.log(error)
)
}
}
//获取url中的code
function getUrlcode(){
var code = getUrlParam("code"); //此处使用的是history路由模式,hash这么拿不到。getUrlParam()方法在下面
console.log('获取到了 ', code);
axios({
method: 'get',
url: url.wx.getOpenId,
headers:{
token:TOKEN
},
params: {
code: code
},
}).then((response) => {
localStorage.setItem('JNZgetOpenId', JSON.stringify(response.data.data));
localStorage.setItem("openid", response.data.data.openId);// 此处我将openid 进行了存储
/*
* 存JNZgetOpenId 主要后期用来获取微信基本信息
* */
let urldelcode=window.location.href.indexOf('code=');
if(urldelcode!=-1){
let qxurl=window.location.href;
let pos = qxurl.indexOf("?code=");
let pos1 = qxurl.indexOf("#/");
let url1=qxurl.substring(0,pos);
let url2=qxurl.substring(pos1,qxurl.length);
let cdxurl=url1+url2
//如果已经制授权过去掉网址中的code
window.location.href =cdxurl
}
}).catch((error) =>
console.log(1 + error) //请求失败返回的数据
)
};
//获取url中的参数
function getUrlParam(name) {
var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象
var r = window.location.search.substr(1).match(reg); //匹配目标参数
if (r != null) {
return unescape(r[2]);
}
return null; //返回参数值
};
3.在main.js中全局引入
import { wxAuthorize } from 'utils/wxauth.js'
Vue.prototype.wxOauth = wxAuthorize
4.在首页onLoad生命周期中调用
onLoad() {
// 静默授权
this.wxlogin()
},
methods: {
// 静默授权(具体内容在utils-wxauth.js)
wxlogin(){
this.wxOauth()
}
}
网页授权 | 微信开放文档