//获取code
getCode ()
function getCode() {
var code = GetRequest()['code'];
var local = window.location.href;
if (code == null || code === '') {
window.location.href = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' + window.APPID + '&redirect_uri=' + encodeURIComponent(local) + '&response_type=code&scope=snsapi_base&state=1#wechat_redirect'
} else {
getOpenId(code) //把code传给后台获取用户信息
}
}
//从url中获取code
function GetRequest() {
var url = location.search;
var theRequest = new Object();
if (url.indexOf("?") != -1) {
var str = url.substr(1);
strs = str.split("&");
for (var i = 0; i < strs.length; i++) {
theRequest[strs[i].split("=")[0]] = unescape(strs[i].split("=")[1]);
}
}
return theRequest;
}
//向后台请求获取openid的接口
function getOpenId(code) {
$.ajax({
url: "/getOpenid",
type: "POST",
data: {
code: code
},
success: function (res) {
console.log('获取成功')
},
error: function (err) {
console.log("失败")
}
})
}
// 后台根据code获取access_token和openId
// 调取接口:https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code
// ````
// | 参数 | 是否必须 | 说明 |
// | ---- | ---- | ----
// | appid | 是 | 公众号的唯一标识 |
// | secret | 是 | 公众号的appsecret |
// | code | 是 | 填写第一步获取的code参数 |
// | grant_type | 是 | 填写为authorization_code
//返回的参数
// {
// "access_token":"ACCESS_TOKEN",
// "expires_in":7200,
// "refresh_token":"REFRESH_TOKEN",
// "openid":"OPENID",
// "scope":"SCOPE"
// }
// |参数|描述|
// |----|----|
// |access_token |网页授权接口调用凭证,注意:此access_token与基础支持的access_token不同 |
// |expires_in |access_token接口调用凭证超时时间,单位(秒) |
// |refresh_token |用户刷新access_token |
// |openid |用户唯一标识,请注意,在未关注公众号时,用户访问公众号的网页,也会产生一个用户和公众号唯一的OpenID |
// |scope |用户授权的作用域,使用逗号(,)分隔 |