网页版 Facebook 第三方登录示例
先跳转 授权
https://www.facebook.com/v7.0/dialog/oauth?client_id=“+client_id+”&redirect_uri=“+redirect_uri+”&state="
授权后会自动重定向到 回调地址 redirect_uri
<!DOCTYPE html>
<html lang="en">
<head>
<title>Facebook Login</title>
<meta charset="UTF-8">
<style type="text/css" media="screen">
hr {
border: none;
}
</style>
<script src="./jquery-2.1.4.min.js"></script>
</head>
<body>
<script>
var client_id="3110596669584569";//示例参数
var client_secret="fa7f7e41afb23923ac69fbd488872cef";//示例参数
var redirect_uri="https://www.baidu.com/login/login.html";//获取Facebook用户信息后回调地址,客户服务器的链接(此处为示例)
// This is called with the results from from FB.getLoginStatus().
function statusChangeCallback(response) {
var code = getUrlParam("code");
console.log("response1="+JSON.stringify(response));
if(code!=''&&code!=null&&code!=undefined){
if (response.status === 'connected') {
testAPI(response.authResponse.accessToken);
} else {
$.get("https://graph.facebook.com/v7.0/oauth/access_token?client_id="+client_id+"&client_secret="+client_secret+"&redirect_uri="+redirect_uri+"&code="+code,function(e){
var token = e.access_token;
testAPI(token);
console.log("token="+token);
//FB.logout(statusChangeCallback);
});
}
}else{
window.location.href="https://www.facebook.com/v7.0/dialog/oauth?client_id="+client_id+"&redirect_uri="+redirect_uri+"&state=";
}
}
// 初始化FB
window.fbAsyncInit = function () {
FB.init({
appId: client_id,
cookie: false, // enable cookies to allow the server to access
xfbml: true, // parse social plugins on this page
version: 'v7.0' // use graph api version 2.8
});
//查询登录状态
FB.getLoginStatus(statusChangeCallback);
};
// 加载facebook SDK
(function (d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) return;
js = d.createElement(s); js.id = id;
js.src = 'https://connect.facebook.net/ko_KR/sdk.js#xfbml=1&version=v7.0&appId=2429587588227274&autoLogAppEvents=1';
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
// 注销
function logout(token) {
FB.logout(function (response) {
console.log("logout1="+JSON.stringify(response));
//FB.Auth.setAuthResponse(null, 'unknown');
});
}
// 获取用户信息
function testAPI(token) {
FB.api('/me', 'GET', { access_token:token,fields: 'first_name,last_name,name,id,email'}, function (response) {
// document.getElementById('status').innerHTML = JSON.stringify(response);
console.log(JSON.stringify(response));
var s=response;
//FB.logout();
logout(token);
});
}
/*获取地址栏参数*/
function getUrlParam(name) {
var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象
var r = window.location.search.substr(1).match(reg); //匹配目标参数
if (r != null) return unescape(r[2]);
return null; //返回参数值
}
</script>
</body>
</html>