項目進行微信開發, 認證了一個微信服務號專門用於內部測試,但是內部可能存在多套不同環境(開發dev、測試sit、預發佈uat)等,由於微信限制一個服務號只能配置一個網頁授權域名, 又不可能給每個環境單獨配一個服務號,這樣不僅需要成本而且很浪費資源, 所以重點需要解決下面這個問題:
1、可以自動區分環境。比方部署開發環境。url可能是http://dev.xxx.com/api/,而在測試環境的時候應該是http://sit.xxx.com/api/。而並且不能寫死,否則開發和測試就要換來換去。非常麻煩
本文總結分享一下思路:
主要是通過中間頁面代理獲取微信授權CODE,然後跳轉到對應需要使用的環境URL下;
比如原來開發環境, 微信中授權域名配置的是dev.xxx.com,那麼現在配置的是一個代理域名proxy.xxx.com,通過代理域名拿到code後在跳回dev.xxx.com,如下圖所示
代碼片段 getCode.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>微信授權登錄</title>
</head>
<body>
</body>
<script>
var code = getPara("code");
if(!code)
{
var redirect = getPara("url");
var appid = getPara("appid");
var _from = getPara("from");
var redirect_url = encodeURIComponent('https://proxy.xxx.com/getCode.html?url='+redirect);
var url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid="+appid+"&redirect_uri=" + redirect_url + "&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect";
location.href = url;
}else{
var redirect = getPara("url");
var code = getPara("code");
if(redirect.split('?').length > 1){
location.href = redirect + "&code=" + code;
}else{
location.href = redirect + "?code=" + code;
}
}
function getPara(name){
var url = location.href;
eval("var reg = /("+name+"=[A-Za-z0-9_,-@!#\.\:\/]*)/i")
var match = url.match(reg);
if(match && match.length > 1){
var arr = match[0].split("=");
arr.shift();
return arr.join('=');
}else{
return "";
}
}
</script>
</html>
使用方法https://proxy.xxx.com/getCode.html?url=http://dev.xxx.com/uinfo&appid=wx6d421c188956xx95
歷史文章:
JAVA微信企業付款到零錢(十分鐘搞定)
微信授權獲取用戶openId的方法和步驟
一個微信號同時支持多個環境網頁授權
微信兩種簽名算法MD5和HMAC-SHA256