How to save data coming from the facebook SDK login in the database?

2

I'm using facebook api for login , and following the tutorial I have already been able to implement it, but I still do not understand how the system that picks up user information works.

What I need to do is store this information in the database (MySQL), so I can identify and associate the user with the forms they fill out (it's not a registration form, it's a search, which can be answered several times by same user).

Then, in my form database, I wanted to create some columns to include this information, and thus be able to identify which (and how many) forms were answered by each user.

When I log in, it tells me that I'm granting permissions to get the email and the public profile, but I do not know where this information is stored, and how do I play them in a PHP variable to send to BD.

The code I'm using is the basics:

<!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>

So the question is : How do I save information coming from facebook login to the MySQL database through PHP?

    
asked by anonymous 03.08.2015 / 21:45

1 answer

4

Since you're using PHP, why not also use Facebook SDK of PHP ? It will be much easier to get and save user data, since you just want it.

When the person clicks the button that you put to login with Facebook, call a URL of yours that runs the flow of the Facebook SDK.

To install the SDK more easily, add it to composer.json:

{
  "require" : {
    "facebook/graph-sdk" : "~5.0"
  }
}

Basic example of login flow

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

Saving User Information

So the user's name, email, and Facebook ID are in the $user_profile array. And that covers your need to get and save user data.

Additional information

With Facebook ID you can perform additional actions later, and this depends on a change of access tokens, but is beyond the scope of your question. Anyway, when you need it, the reference is: link

    
04.08.2015 / 01:43