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
};