
正文
js 微信公众号网页用户授权,获取微信code,access_tocken,用户信息
提示:扫一扫查出行【扫一扫了解最新限行尾号】
复制提示
第一次做微信网页授权,过程有点艰难,主要是不知道redirect_uri的地址要怎么写,刚开始我以为就是授权结束后要跳转到的首页地址,于是写成了uri = 'http://18i194c049.iask.in/credit/ProfessionalCredit/html/homePage.html'这种形式的,结果到了授权页面一直就弹出授权界面,像个死循环,后来想想应该是重定向url没写对以至于code没法传给后台换取不到access_token,所以一直循环弹出授权界面,最后请教大佬终于明白了,这个地址很重要,写你当前访问的页面的 href,因为点击同意授权后他会拼接?code='123456789'&href='www.baidu.com'等一些参数回来页面将跳转至 redirect_uri/?code=CODE&state=STATE页面,才能传给后台code换取access_token,登录成功。
具体过程请阅读微信公众号开发者文档,就不详细说了https://developers.weixin.qq.com/doc/offiaccount/OA_Web_Apps/Wechat_webpage_authorization.html
直接上前端代码:
(function () {
var href = location.href;
if(href.indexOf("code=") === -1){ //如果没有code参数就直接调用授权函数
get_weixin_code_login();//调用授权函数
}else{ //如果有拿取code值
getUrlCode();
var local = window.location.href;
this.code = this.getUrlCode().code;
alert(this.code);
if (this.code == null || this.code == '' || this.code == 'undefined') {
window.location.href = url;
}
getWxUserInfo(this.code);
}
})(); function get_weixin_code_login() {
var uri = window.location.href;
var appid = '**************';//自己公众号的appid
var url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' + appid + '&redirect_uri=' +
encodeURIComponent(uri) + '&response_type=code&scope=snsapi_userinfo&state=54321#wechat_redirect';
window.location.href = url;
// 这里走完就是已经授权了。如果授权了就会url中带有code
} //获取url参数
function getUrlCode() {
var url = location.search;
this.winUrl = url;
var theRequest = new Object();
if (url.indexOf("?") != -1) {
var str = url.substr(1);
var strs = str.split("&");
for (var i = 0; i < strs.length; i++) {
theRequest[strs[i].split("=")[0]] = (strs[i].split("=")[1]);
}
}
return theRequest;
} /**
* 授权后获取用户的基本信息
*/
function getWxUserInfo(coDe) {
mui.ajax({
type: "post",
url: 'http://18i194c049.iask.in/credit/caf/Verification/rz.do',
async: false,
data: {
code: coDe,
},
headers: {'Content-Type': 'application/json'},
dataType: "json",
//jsonp: "jsoncallback",
success: function (data) {
console.log("success : " + data);
alert('授权成功');
},
error: function () {
alert('授权失败');
}
});
};






