コメントで説明したように、JS SDK を使用した例を次に示します
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script> <!-- jQuery library, makes things easier. -->
<title>FB example</title>
</head>
<body>
<div id="fb-root"></div>
<script>
window.fbAsyncInit = function() {
// init the FB JS SDK
FB.init({
appId : YOUR_APP_ID, // App ID from the app dashboard
status : true, // Check Facebook Login status
xfbml : true // Look for social plugins on the page
});
// Additional initialization code such as adding Event Listeners goes here
};
// Load the SDK asynchronously
(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 = "//connect.facebook.net/en_US/all.js";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
/*
This function gets information about user and alrets user's name.
*/
function getUserInfo() {
FB.api('/me', function(response) {
$.ajax({
url: "ajax.php", //url to send ajax request to
data: {
json: response, // Key => value pairs of items to send
},
success: function(ajaxResponse) { // upon successful request
alert(ajaxResponse); //Alert whatever response we got.
}
})
})
}
/*
This function gets the login status of user
*/
function getLoginStatus() {
FB.getLoginStatus(function(response) {
if (response.status === 'connected') { //User is connected to Facebook and authorized your app
getUserInfo();
} else if (response.status === 'not_authorized') { //User is connected to Facebook, but hasn't authorized your app
login();
} else { //User is not connected to Facebook
login();
}
});
}
/*
Function promts user to log in and asks for permissions
*/
function login() {
FB.login(function(response) {
if (response.authResponse) {
getUserInfo();
} else {
alert('User cancelled login or did not fully authorize.');
}
}, {scope: 'email'}); // Comma separated permissions
}
</script>
<a href="javascript:getLoginStatus()"/>Login</a>
</body>
</html>
これは非常に単純な例です。ページに「ログイン」リンクが表示されます。それを押すと、ログインするように求められるか (Facebook にログインしていない場合、またはアプリをまだ承認していない場合)、またはあなたの名前がポップアップで表示されます。ほとんどのコードは、JavaScript SDK ドキュメントから引用されています。
編集:
ユーザーのデータをデータベースに追加するには、関数から AJAX 呼び出しを行うことをお勧めしますgetUserInfo()
。アラート部分を特定の php ファイルへの ajax 呼び出しに置き換えます。このファイルを作成して、response
変数 (response.name
や などのユーザーに関するデータを含むresponse.email
) からデータを渡します。php ファイル自体に、データベースに取得した情報を挿入します。
別の編集:
コードをもう一度更新しました。つまり、jQuery ライブラリを追加しました (単純な JS と大差ありませんが、ajax 呼び出しを簡単に行うことができます)。
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
getUserInfo()
また、 に ajax リクエストを行う機能を更新しましたajax.php
。
ajax.php
私は1行だけを作成しました:
print_r($_REQUEST['json']);
これにより、ajax 経由で送信されたデータがすべて出力され、ポップアップで表示されます。次のステップは、取得した情報を確認し、必要なもの ($_REQUEST['json']
単純な配列) を取得して、db に挿入することです。