利用 Javascript 與 Facebook 串接
單純了解是否登入及授權的狀態
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:fb="http://www.facebook.com/2008/fbml" xmlns:og="http://opengraph.org/schema/">
<head runat="server">
<title></title>
<script type="text/javascript" src="https://connect.facebook.net/zh_TW/all.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"></script>
<script>
$(function () {
var _app_id = '{app_id}';
//放至『應用程式ID/ API鑰匙 』
var _api_key = '{api_key}';
//放至『應用程式密鑰』
//驗證
FB.init({
appId: _app_id,
status: true,
// check login status
cookie: true,
// enable cookies to allow the server to access the session
xfbml: true,
// parse XFBML
oauth: true
// enable OAuth 2.0
});
FB.Canvas.setAutoGrow();
//autoResize → no scrollbar
$('#btn').click(function () {
getLoaginState();
});
//檢查登入狀態
function getLoaginState() {
FB.getLoginStatus(function (response) {
if (response.status === 'connected') {
//登入且授權
var uid = response.authResponse.userID;
var accessToken = response.authResponse.accessToken;
$("#uid").html("UID:" + uid);
$("#accessToken").html("accessToken:" + accessToken);
} else if (response.status === 'not_authorized') {
// 登入了尚未授權
alert("請允許授權!");
} else {
// 帳號沒有登入
login();
}
});
}
//跳出登入視窗
function login() {
FB.login(function (response) {
if (response.authResponse) {
var uid = response.authResponse.userID;
console.log(uid);
} else {
alert('須同意應用程式');
}
}, { scope: "email" });
//scope,此設定是可以取得 EMail 的權限。
}
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div id="fb-root"></div>
<input type="button" id="btn" value="點我授權" /><br />
<span id="uid"></span>
<br>
<span id="accessToken"></span>
</form>
</body>
</html>
畫面如下