介绍
功能: 支持微信/支付宝网页静默授权
为什么需要线上html
因为在开发环境的时候,是本地服务http://localhost:8080
,但是微信需要JS接口安全域名.
配置信息
- 先登录微信公众平台进入“公众号设置”的“功能设置”里填写“网页授权域名”
- 然后把 html 文件放到服务器上, 安全域名指向这个html
- 在 vue 环境配置文件(.env.development、.env.production),中配置以下参数
- VUE_APP_WX_GET_CODE_DOMAIN = ‘第二步的html文件的线上地址’
- VUE_APP_APP_ID = ‘微信/支付宝的appid’
- 使用方法:
- 直接调取 util 文件中的 getAuthorCode 方法
- 调取完后,就可以在地址栏中,看到那个 code 了 (获取code的时候,可以使用这个方法 onGetRequest().code )
代码信息
授权文件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>授权code</title>
</head>
<body>
</body>
</html>
<script>
(function () {
var tools = {
getParamer: function (key) {
var map = this.getSearch();
return map[key];
},
getSearch: function () {
var search = window.location.search;
return this.getSearchByStr(search);
},
getSearchByStr: function (search) {
if (search) {
search = search.substring(1);
} else {
return {};
}
var strsz = search.split("&");
var map = {};
for (var i = 0; i < strsz.length; i++) {
var strs = strsz[i];
if (strs.indexOf("=") != -1) {
var tempsz = strs.split("=");
var tempkey = tempsz[0];
var tempvalue = tempsz[1];
map[tempkey] = decodeURIComponent(tempvalue);
}
}
return map;
},
setLocalStorage: function (key, val) {
var map = {};
map[key] = val;
localStorage.setItem(key, JSON.stringify(map));
},
getLocalStorage: function (key) {
var mapStr = localStorage.getItem(key);
if (!mapStr) {
mapStr = "{}";
}
var map = JSON.parse(mapStr);
return map[key];
},
urlAddProp: function (url, key, val) {
var jing = url.indexOf("#");
var left = "";
var right = "";
if (jing == -1) {
//无#号情况
left = url;
} else {
//有#号情况
left = url.substring(0, jing);
right = url.substring(jing);
}
if (left.indexOf("?" + key + "=") != -1 || left.indexOf("&" + key + "=") != -1) {
var start = left.indexOf("?" + key + "=");
if (start == -1) {
start = left.indexOf("&" + key + "=");
}
var end = left.indexOf("&", start + 1);
if (end == -1) {
end = left.length;
}
right = left.substring(end) + right;
left = left.substring(0, start + 1);
} else {
var type = left.indexOf("?") != -1 ? "&" : "?";
left += type;
}
var data = key + "=" + val;
return left + data + right;
},
/**
* 设置环境
*/
getCodeName() {
if (/MicroMessenger/.test(window.navigator.userAgent)) { // 微信
return 'code'
} else if (/AlipayClient/.test(window.navigator.userAgent)) { // 支付宝
return 'auth_code'
} else {
return ''
}
}
}
function wxLogin(callback) {
const codeName = tools.getCodeName()
if (tools.getParamer(codeName)) {
callback(tools.getParamer(codeName));
} else {
//去取code
let url = ''
var appid = tools.getParamer('appid');
if(codeName === 'code'){
url = "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";
}else if(codeName === 'auth_code'){
url = "https://openauth.alipay.com/oauth2/publicAppAuthorize.htm?app_id=" + appid + "&redirect_uri=" + encodeURIComponent(window.location.href) + "&response_type=code&scope=auth_base";
}
window.location.href = url;
}
}
var url = tools.getParamer("url");
tools.setLocalStorage("url", url);
wxLogin(function (code) {
const codeName = tools.getCodeName()
var toUrl = tools.getLocalStorage("url");
toUrl = tools.urlAddProp(toUrl, codeName, code);
window.location.href = toUrl;
});
})()
</script>
util 文件
// 在util 文件中放入一下方法
/**
* 获取认证 code
* @param {String}} routerCallback 回调路由
*/
function getAuthorCode(routerCallback) {
const a = document.createElement('a');
const urlCallback = encodeURIComponent(
process.env.VUE_APP_BASE_DOMAIN + routerCallback
);
if (process.env.NODE_ENV === 'development') {
// 测试环境走线上
a.href = `${process.env.VUE_APP_WX_GET_CODE_DOMAIN}?url=${urlCallback}&appid=${process.env.VUE_APP_APP_ID}`;
} else {
// 正式环境 直接获取
switch (judgeEnvironment()) {
case 'WX':
a.href = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${process.env.VUE_APP_APP_ID}&redirect_uri=${urlCallback}&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect`;
break;
case 'ZFB':
a.href = `https://openauth.alipay.com/oauth2/publicAppAuthorize.htm?app_id=${process.env.VUE_APP_APP_ID}&redirect_uri=${urlCallback}&response_type=code&scope=auth_base`;
break;
case 'OTHER':
a.href = 'javascript:;'
console.error('当前环境不支持授权~')
break;
}
}
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
}
/**
* 获取 url
* @returns params的参数
*/
function getUrl() {
const url = window.location.href
var params = []
var h
var hash = url.slice(url.indexOf('?') + 1).split('&')
for (var i = 0; i < hash.length; i++) {
h = hash[i].split('=') //
params[h[0]] = h[1]
}
return params
}
/**
* 判断浏览器环境
*/
function judgeEnvironment() {
if (/MicroMessenger/.test(window.navigator.userAgent)) {
return 'WX'
} else if (/AlipayClient/.test(window.navigator.userAgent)) {
return 'ZFB'
} else {
return 'OTHER'
}
}
/**
*
* @returns {Object} url参数集
*/
function onGetRequest() {
const url = window.location.href
var params = []
var h
var hash = url.slice(url.indexOf('?') + 1).split('&')
for (var i = 0; i < hash.length; i++) {
h = hash[i].split('=')
params[h[0]] = h[1]
}
return params
}