1、網頁授權條件
1.1 設置
登錄公眾號,開發-接口全縣-網頁服務-網頁賬號-網頁授權獲取用戶基本信息 設置- 授權回調域名(請勿加 http://等協議頭),假設為 www.test.com
注意:將提示中的txt文件上傳到域名對應的服務器上(微信的安全考慮),不上傳,設置回調域名會報錯
1.2 訂閱號沒有授權接口
2、網頁授權
官方API
https://developers.weixin.qq.com/doc/offiaccount/OA_Web_Apps/Wechat_webpage_authorization.html
微信訪問以下地址:(以下僅APPID需替換公眾號的APPID),目的是獲取code以換取token
https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redirect_uri=https://www.test.com&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect
第2步成功后,頁面會自動跳轉到以下地址,這就開始進入具體的業務頁面了。
https://www.test.com/?code=CODE&state=STATE
注意:如果用戶同意授權,頁面將跳轉至 redirect_uri/?code=CODE&state=STATE。若用戶禁止授權,則重定向后不會帶上code參數,僅會帶上state參數redirect_uri?state=STATE
3、oauth2 授權
3.1 scope 參數
3.1.1 靜默授權
snsapi_base (不彈出授權頁面,直接跳轉,只能獲取用戶openid)
3.1.2 主動授權
snsapi_userinfo (彈出授權頁面,可通過openid拿到昵稱、性別、所在地。
4、代碼 將code 傳給給發拿到openid以及對應數據
var code = getParam("code");
let redirect_uri = window.location.href;
if(code != null){
$.ajax({
type: "get",
url: 'https://******/userLoginForWebCallBack',
data: {code:code},
success: function(data) {
return false;
},
error: function(e) {}
});
return false;
}
var url ="https://open.weixin.qq.com/connect/oauth2/authorize?appid="+appid+"&redirect_uri="+redirect_uri+"&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect";
window.location.href = url;
function getParam(paramName) {
paramValue = "", isFound = !1;
if (location.search.indexOf("?") == 0 && location.search.indexOf("=") > 1) {
arrSource = decodeURI(location.search).substring(1, location.search.length).split("&"), i = 0;
while (i < arrSource.length && !isFound) arrSource[i].indexOf("=") > 0 && arrSource[i].split("=")[0].toLowerCase() == paramName.toLowerCase() && (paramValue = arrSource[i].split("=")[1], isFound = !0), i++
}
return paramValue == "" && (paramValue = null), paramValue
};