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

Asked

Viewed 5,409 times

2

I’m using the facebook api for login, and following the tutorial I have been able to implement, but I still don’t understand how the system works that takes user information.

What I need is to save this information in the database (Mysql), so I can identify and associate the user with the forms he fills in (it’s not a registration form, it’s like a survey, 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, and so be able to identify which (and how many) forms were answered by each user.

When I log in, he informs me that I’m granting permissions to pick up the email and public profile, but I don’t know where this information is recorded, and how do I play it in a PHP variable to send to the 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>

So the question is: How do I record the information coming from login with facebook in the Mysql database, through PHP?

  • 1

    in the documentation, look at the chapter Make API calls, example shows how to get user ID and email

1 answer

4


Since you are using PHP, why not use PHP Facebook SDK? It will become much easier to get and save user data as you just want it.

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

To install the SDK more easily, add 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

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 Facebook ID you can perform additional actions later, and this depends on an exchange of access tokens, but is outside the scope of your question. Anyway, when you need it, the reference is: https://developers.facebook.com/docs/facebook-login/access-tokens

  • +1 And I call this file facebook.php in the same skd javascript button? Or do I not need to use sdk javascript if I am going to use sdk php? And I know you’re already running away from the scope of the question, but for me to save the Infos in the same line of the form data I’ll have to be using sessions right? Could give a hint of what I have to study to do this (integrate the login of facebook to php sessions...)... Thanks for the help.

  • 1

    You no longer need the SDK Javascript. You will put a normal button and a normal call to URL, example: http://dominio.com/facebook-login.php. To keep the user logged in you follow the same procedure as a "traditional" login, storing in the session/cookie/etc.

  • Okay, I’ll start trying. Thanks!

  • Good luck! As your question and main problem have been solved, it would be interesting to mark my answer as accepted.

  • So Alfred, it’s hard for me to implement the PHP SDK (I’m still a beginner). Your answer helped me better understand the problem (I already gave +1), but I will keep the question open for a while longer, to see if a solution appears that allows me to use the JS SDK and pass these variables like thus. If this is not possible, "It is not possible" would also be a valid answer... Thanks!

  • 1

    It is more than possible yes, I just passed to you direct with PHP, because there involves only one communication, being more simplified, due to its original difficulty. If I remember, with more time I post a hint of how you should do to make JS <-> PHP communication.

  • Fatal error: Class 'Facebooksession' not found in /home/ciclumcom/public_html/demo/fb/facebook.php on line 9

Show 2 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.