Login via facebook SDK

Asked

Viewed 634 times

1

Well recently I made a login page where you have the normal login and the by facebook, only when login by facebook when you click redirects to the application to allow access, ok so far so good, only when you click and allows it returns to the page with a code in the browser only it displays the error message Error connection with Facebook ID and Secret are right!

    <?php
session_start();
if($_SERVER['REQUEST_METHOD'] == 'GET' && isset($_GET['code'])){

  // Informe o seu App ID abaixo
  $appId = '680167435480727';

  // Digite o App Secret do seu aplicativo abaixo:
  $appSecret = 'xxxxxxx';

  // Url informada no campo "Site URL"
  $redirectUri = urlencode('$path');

  // Obtém o código da query string
  $code = $_GET['code'];

  // Monta a url para obter o token de acesso e assim obter os dados do usuário
  $token_url = "https://graph.facebook.com/oauth/access_token?"
  . "client_id=" . $appId . "&redirect_uri=" . $redirectUri
  . "&client_secret=" . $appSecret . "&code=" . $code;

  //pega os dados
  $response = @file_get_contents($token_url);
  if($response){
    $params = null;
    parse_str($response, $params);
    if(isset($params['access_token']) && $params['access_token']){
      $graph_url = "https://graph.facebook.com/me?access_token="
      . $params['access_token'];
      $user = json_decode(file_get_contents($graph_url));

    // nesse IF verificamos se veio os dados corretamente
       if(isset($user->email) && $user->email){

    /*
    *Apartir daqui, você já tem acesso aos dados usuario, podendo armazená-los
    *em sessão, cookie ou já pode inserir em seu banco de dados para efetuar
    *autenticação.
    *No meu caso, solicitei todos os dados abaixo e guardei em sessões.
    */

        $_SESSION['email'] = $user->email;
        $_SESSION['nome'] = $user->name;
        $_SESSION['uid_facebook'] = $user->id;

        $mail =  $_SESSION['email'];
        $name = $_SESSION['nome'];
        $name = $_SESSION['uid_facebook'];

        $check = mysql_num_rows(mysql_query("SELECT * FROM users WHERE mail = '$mail' LIMIT 1"));
        if($check==0){  

    // REGISTRO

    function GenerateName($mail){
    $name = current(explode('@', $mail));
    return $name;
}

        $username = GenerateName($mail); // Nombre generado
        $password = substr(md5(rand(0, 999). strtolower($mail). rand(0,100000)), 0, 12);    

        mysql_query("INSERT INTO `users` (username,real_name,password,auth_ticket,motto,mail,rank,look,gender,account_created,last_online,online,ip_last,ip_reg,working,secretcode,mymusik,home_room,vip) VALUES ('".mysql_real_escape_string($username)."','Habbo','".mysql_real_escape_string($password)."','-/-','".$sitename." <3','".mysql_real_escape_string($mail)."','1','".$look."','".$gender."','".time()."','".time()."','1','".$remote_ip."','".$remote_ip."','','','','0','1')") or die(mysql_error());

        $_SESSION['username'] = $username;
        $_SESSION['password'] = $password;

        header('location: '.$path.'/welcome');
        exit();

        }else{

        // LOGIN
        $userq1 = mysql_query("SELECT * FROM users WHERE mail = '$mail' LIMIT 1");
        while($row = mysql_fetch_assoc($userq1)){

        $credUser = $row['username'];
        $credPass = $row['password'];

        $_SESSION['username'] = $credUser;
        $_SESSION['password'] = $credPass;

        header('location: '.$path.'/me');

        }
        }
      }
    }else{
$login_fehler = "Ocorreu um erro de código. Contate-nos através de nosso facebook fb.com/HebbiBrasil";
      exit(0);
    }

  }else{
$login_fehler = "Ocorreu um erro de código. Contate-nos através de nosso facebook fb.com/HebbiBrasil";
    exit(0);
  }
}else if($_SERVER['REQUEST_METHOD'] == 'GET' && isset($_GET['error'])){
$login_fehler = "Ocorreu um erro de código. Contate-nos através de nosso facebook fb.com/HebbiBrasil";
}
?>
  • I recommend that you remove App Secret from your question, since it is something secret (as the name says) and specific to your application. I suggest you re-define it as well since it was put here.

  • Have you downloaded the Facebook library? Is it related to the current file? Take a look here. It is the most updated code currently on the Internet for login with the Face SDK. http://www.krizna.com/general/login-with-facebook-using-php/ Besides of course, be totally commented! Look there and tell me.

  • Remove "@" to not omit errors, you want to know what is wrong, do not use "@" to omit it. If you are using file_get_contents you need to allow it to connect to external website in case allow_url_fopen in the php.ini

  • You don’t need the SDK, everything can be done using the Curl or the file_get_contents/fopen, PHP natives, including is also documented in https://developers.facebook.com/docs/graph-api/reference all documents endpoints to be used.

  • Oh yes. It’s also used. But I figured that even though it used file_get_contents($token_url);, there was some related directory that had not been done the link (require)

1 answer

1


The service of API Login Dialog of Facebook is used to request a user’s data with the user’s consent.

To use the service you need create an APP to receive credentials.

Modelled FB.login v2.12 of the Javascript documentation we will create a functional example of login via facebook

A button with ID fb-login :

 <button class="btn btn-facebook" id="fb-login" type="button">Logar Usando o Facebook</button>

In Jquery

         var appId = '680167435480727';
          //Load the Facebook JS SDK
        (function (d) {
            var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0];
            if (d.getElementById(id)) {
                return;
            }
            js = d.createElement('script');
            js.id = id;
            js.async = true;
            js.src = "//connect.facebook.net/pt_BR/all.js";
            ref.parentNode.insertBefore(js, ref);
        }(document));
        window.fbAsyncInit = function () {
            FB.init({
                appId: appId,
                xfbml: true,
                version: 'v2.3',
                status: true,
                cookie: true
            });
        };
        function showDetails() {
            FB.api('/me', {fields: fields}, function (details) {
                // Imprime no HTML os dados do usuário
                //$('body').append(JSON.stringify(details, null, '\t'));
                try {
                    $.post('facebook.php', {"dados": details}, function (json) {
                        if (!json.error) { // ocorreu tudo certo
                            window.location.href = json.url;
                        } else {
                            console.log("Não foi possível logar");
                        }
                    }, "JSON");
                } catch (e) {
                    console.log("Erro ao logar via facebook");
                }
            });
        }
        // Tipos de permissão que irá ser pedida ao usuário.
        var permissions = [
            'email',
            'user_birthday'
        ].join(',');
        // Campos que vão ser retornados após o login ser confirmado
        var fields = [
            'id',
            'name',
            'first_name',
            'middle_name',
            'last_name',
            'birthday',
            'email'
        ].join(',');
        $('#fb-login').click(function () {
            fbAsyncInit();
            // Tenta fazer o login
            FB.login(function (response) {
                // Se usuário está logado ....
                if (response.authResponse) {
                    showDetails();
                }
            }, {scope: permissions});
        });

If everything goes right, the function will make a POST of dice received in facebook php. :

   $graphObject = $_POST['dados'];
   if (empty($graphObject['first_name'])) 
       return print json_encode("error"=>1,"msg"=>'Não conseguimos extrair o seu nome');

   if (empty($graphObject['id'])) 
       return print json_encode("error"=>1,"msg"=>'Não conseguimos extrair o ID do seu perfil');

   if (empty($graphObject["email"])) 
      return print json_encode("error"=>1,"msg"=>'Não conseguimos extrair o email do seu perfil');

// a partir daqui continua sua função de login, já que todos os dados necessários foram enviados.

Browser other questions tagged

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