微信/QQ/微博/百度等第三方使用二维码扫码登录原理

1.登录页loginwx.html,包含一个微信登录按钮
代码如下:

// loginwx.html
<span id="loginWx">微信登录</span>
<script>
$('#loginWx').on('click', function(){
	var authSite = '/callback?qd=wechat'
	window.open(authSite, "popup_1522755126508", "toolbar=no, titlebar=no, top=100px, left=100px, location=no, directories=no, status=no, menubar=no, copyhistory=yes, width=650, height=450");
});
</script>

2.callback页面,代码如下:

// callback.html
function parseParams(str) {
    var obj = {};
    if(!str) { return obj; }
    str.replace(/([^&=?#]*)=([^&=?#]*)/g, function (src, $1, $2) {
        obj[$1] = $2;
    });
    return obj;
}
var obj = parseParams(window.location.href);
var code = obj['code'];

if (code) {
    if (window.opener && window.opener.location) {
        window.opener.location.reload();
    }
    window.close();
}
else {
	var authSite = '/authsite';
    window.location.href = authSite;
}

3.authsite页面(二维码扫描),代码如下:

//authsite.html
function hasLogin() {
	$.ajax({
	    type: "GET",
	    url: "https://long.open.weixin.qq.com/connect/l/qrconnect?uuid=xxx",
	    dataType: "script",
	    cache: !1,
	    timeout: 6e4,
	    success: function(ret) {
	    	switch(ret.errno){
	    		case 0:
	    			window.top.location = '/callback?code=uidpassport';
	    			break;
	    		default:
	    			setTimeout(hasLogin, 2e3);
	    			break;
	    	}
	    },
	    error: function(e) {
	        setTimeout(hasLogin, 2e3);
	    }
	});
}
setTimeout(hasLogin, 100);

主要依赖于window.opener.location

此条目发表在JavaScript分类目录。将固定链接加入收藏夹。

发表评论

电子邮件地址不会被公开。 必填项已用*标注