How to save data coming from Facebook SDK login to database?
I'm using the Facebook api for login , and following the tutorial I have already managed to implement, but I still do not understand how the system that takes the user information works.
What I need is to save this information in the database (MySQL), in order to identify and associate the user with the forms that he fills out (it is not a registration form, it is like a search, which can be answered several times by the same user).
So, in my form database, I wanted to create some columns to include this information, so I could identify which (and how many) forms were answered by each user.
When I log in, it informs me that I am granting permissions to take the email and the public profile, but I do not know where this information is recorded, and how do I throw them in a PHP variable to send pro BD.
The code I'm using is the basic:
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>Facebook Login JavaScript Example</title>
</head>
<body>
<script>
// This is called with the results from from FB.getLoginStatus().
function statusChangeCallback(response) {
console.log('statusChangeCallback');
console.log(response);
// The response object is returned with a status field that lets the
// app know the current login status of the person.
// Full docs on the response object can be found in the documentation
// for FB.getLoginStatus().
if (response.status === 'connected') {
// Logged into your app and Facebook.
testAPI();
} else if (response.status === 'not_authorized') {
// The person is logged into Facebook, but not your app.
document.getElementById('status').innerHTML = 'Please log ' +
'into this app.';
} else {
// The person is not logged into Facebook, so we're not sure if
// they are logged into this app or not.
document.getElementById('status').innerHTML = 'Please log ' +
'into Facebook.';
}
}
// This function is called when someone finishes with the Login
// Button. See the onlogin handler attached to it in the sample
// code below.
function checkLoginState() {
FB.getLoginStatus(function(response) {
statusChangeCallback(response);
});
}
window.fbAsyncInit = function() {
FB.init({
appId : 'XXXXXXXXXXXXXX',
cookie : true, // enable cookies to allow the server to access
// the session
xfbml : true, // parse social plugins on this page
version : 'v2.2' // use version 2.2
});
// Now that we've initialized the JavaScript SDK, we call
// FB.getLoginStatus(). This function gets the state of the
// person visiting this page and can return one of three states to
// the callback you provide. They can be:
//
// 1. Logged into your app ('connected')
// 2. Logged into Facebook, but not your app ('not_authorized')
// 3. Not logged into Facebook and can't tell if they are logged into
// your app or not.
//
// These three cases are handled in the callback function.
FB.getLoginStatus(function(response) {
statusChangeCallback(response);
});
};
// 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/sdk.js";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
// Here we run a very simple test of the Graph API after login is
// successful. See statusChangeCallback() for when this call is made.
function testAPI() {
console.log('Welcome! Fetching your information.... ');
FB.api('/me', function(response) {
console.log('Successful login for: ' + response.name);
document.getElementById('status').innerHTML =
'Thanks for logging in, ' + response.name + '!';
});
}
</script>
<!--
Below we include the Login Button social plugin. This button uses
the JavaScript SDK to present a graphical Login button that triggers
the FB.login() function when clicked.
-->
<fb:login-button scope="public_profile,email" onlogin="checkLoginState();">
</fb:login-button>
<div id="status">
</div>
</body>
</html>
Then the question is : How do I record the information coming from the login with facebook in the MySQL database, through PHP?
1 answers
Since you are using PHP, why not also use the Facebook SDK of PHP ? It will get much easier to get and save user data since you just want it.
Facebook facebookWhen the person clicks the button you put to login with Facebook, call a URL of yours that runs the Facebook SDK flow.
To install the SDK more easily, add to composer.json:
{
"require" : {
"facebook/graph-sdk" : "~5.0"
}
}
Basic fundamental example of flow of login
Facebook.php :
class Facebook
{
private $helper;
public function __construct()
{
FacebookSession::setDefaultApplication('SuaAppId', 'SuaAppSecret');
$this->helper = new FacebookRedirectLoginHelper('http://seudominio.com/facebook-confirmado.php');
}
public function Login()
{
$loginUrl = $this->helper->getLoginUrl(array('scope' => 'email'));
header("Location: {$loginUrl}");
exit;
}
public function GetSession()
{
try {
$session = $this->helper->getSessionFromRedirect();
}
catch(FacebookRequestException $ex) {
// Trate erros do FB aqui
}
catch(\Exception $ex) {
// Trate outros erros aqui
}
if($session)
{
// Logado, obtém informações do usuário
$user_profile = (new FacebookRequest(
$session, 'GET', '/me'
))->execute()->getGraphObject(GraphUser::className());
return $user_profile;
}
}
}
Facebook-login.php :
$facebook = new Facebook();
$facebook->Login();
Facebook-confirmed.php :
$facebook = new Facebook();
$userProfile = $facebook->GetSession();
// User profile vai conter os dados do usuário:
// [id] => 4903490234934
// [email] => [email protected]
// [first_name] => Nome
// [gender] => male
// [last_name] => Sobrenome
// [link] => https://...
// [locale] => en_US
// [middle_name] => Nome do Meio
// [name] => Nome Sobrenome
// [timezone] => -3
// [updated_time] => 2015-06-06T03:29:08+0000
// [verified] => 1
How to save user information
Thus, the user's name, email and Facebook ID are in the array $user_profile
. And this covers your need to get and save user data.
Additional information
With the Facebook ID you can perform additional actions later, and this depends on a exchange access tokens, but it is outside the scope of your question. Anyway, when you need it, the reference is: https://developers.facebook.com/docs/facebook-login/access-tokens