2013-09-23 2 views
0

Что я хочу сделать, это в соответствии с пользователем приходят на моей странице,выполнять различные действия в соответствии с facebook статус входа

  1. проверки состояния facebook. если вы вошли в систему и уже авторизованы моим приложением, переадресовываете на новую страницу, то есть url.php.
  2. Если не вошли в систему и уже утвержденную затем показать страницу index.php с connect facebook кнопку
  3. Если не разрешено с моим приложением, то попросите его сделать. Также просят вспомнить пароль, так что в следующий раз он войти в систему, должны быть перенаправлены на страницу url.php

Я попытался с FB.getLoginStatus. Когда я выполняю простой код, как показано ниже, он отлично работает:

FB.getLoginStatus(function(response) { 
    if (response.status === 'connected') { 
    var uid = response.authResponse.userID; 
    var accessToken = response.authResponse.accessToken; 
    } else if (response.status === 'not_authorized') { 
    // but has not authenticated your app 
    } else { 
    // the user isn't logged in to Facebook. 
    } 
}); 

Когда я попытался сделать то же самое со следующими фактический код никогда не добиться успеха, после того, как гроздь попытки. На самом деле то, что происходит, the content on the page like кнопка and rest it always get loaded even user is logged in or not. Пожалуйста, дайте мне подсказку для этого кода, чтобы поместить условие соответствующим образом:

Mycode:

<?php 
session_start(); 
$appId = '178862'; 
$appSecret = 'xxxxxxxxxxxxxxxxxxxxxxxx'; // Facebook App Secret 
$return_url = 'dev01.dev/FB/facebook-php-sdk/examples/'; //path to script folder 
?> 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml" > 
<head> 
<script type="text/javascript" src="https://www.google.com/jsapi"></script> 
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"> 
</script> 
    <title>ThenWat</title> 
    <script> 
function AjaxResponse() 
{ 
    //alert("2"); 
    var mydata;   
    CallAfterLogin(mydata, function(send) { 
       }); 
    } 
function LodingAnimate() //Show loading Image 
{ 
    //alert("animate4");  
    // $("#LoginButton").hide(); //hide login button once user authorize the application 
} 

    </script> 
</head> 
<body style="height: 560px"> 
<?php 
if(!isset($_SESSION['logged_in'])) 
{ 
?> 
    <div style="z-index: 1; left: 538px; top: 290px; position: absolute;"> 
    <input class="uibutton confirm large" type="submit" value="Connect with facebook" onclick="AjaxResponse()" > 
    </div> 
<?php 
} 
?> 


<div id="fb-root"></div> 
<script type="text/javascript"> 
window.fbAsyncInit = function() { 
FB.init({ 
    appId: '<?php echo $appId; ?>', 
    cookie: true, 
    xfbml: true, 
// channelUrl: '<?php echo $return_url; ?>channel.php', 
    oauth: true});}; 
(function() { 
     //alert("1"); 
    var e = document.createElement('script'); 
    e.async = true; 
    e.src = document.location.protocol +'//connect.facebook.net/en_US/all.js'; 
    document.getElementById('fb-root').appendChild(e);}()); 
function CallAfterLogin(data,callback){ 
     //alert("CallafterLogin3"); 
     FB.login(function(response) { //--- 
    x: FB.getLoginStatus(function(response) { 
     { 
      LodingAnimate(); 
      FB.api('/me?fields=movies,email', function(mydata) { 
      console.log(mydata); 
       if(mydata.email == null) 
       { 
       alert("You must allow us to access your email id!"); 
       ResetAnimate(); 
       }   
       else 
     { 
      //alert("json-5"); 
      var json = JSON.stringify(mydata.movies.data); 
     // alert(mydata.movies); 
      var a = JSON.parse(json);  
      $.post('movies_db.php',{'myd':a}, function(data) 
      { 
       $.ajax({ 
      url:'url.php' 
      ,async:  true 
      ,cache:  false 
      ,dataType: 'html' 
      ,success: function(data){ 
       $('body').html(data); 
        } 
     });   
      }); 
     } 

       }); //-- 
     } //if 
      }); //--- 
      } //main function 
</script> 
</body> 
</html> 

Когда я положил AjaxResponse() в OnLoad то это не входит в линию x

до того FB.getLoginStatus(function(response) { если я кладу document.getElementById("b1").style.display="none"; скрывает кнопку

ответ

0
1. Perform user App authentication. 
2. Store user facebook profile details in database 
3. If user has already authenticated your app, and logged into his facebook a/c the redirect to next page 
4. If user is not logged in, SDK will ask to perform facebook login 

исходный код

фб Войти http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js ">
.middle { background-color: Yellow; }

 .left{ 
      background-color:Green; 
     } 
     .url{ 
      box-sizing: border-box; 
      display: block; 
     } 
     .url:hover { 
      box-shadow: 2px 2px 5px rgba(0,0,0,.2); 
     } 
     .header{ 
      background-color: #61B329; 
      color: #FFF; 
      margin-top: 0px !important; 
      margin-bottom: 20px; 
      padding-bottom: 9px; 
     } 
     .page-header-text { 
      padding-left: 15px; 
      padding-top: 20px; 
      padding-bottom: 10px; 
      margin: 0px; 
     } 


     html, body { margin: 0; padding: 0; border: 0 } 
    </style> 
    <script> 
     $(document).ready(function() 
     { 
      console.log("ready!"); 
      //alert("Welcome"); 
     }); 
    </script> 
</head> 

<body> 
    <div class="page-header header"> 
     <h1 class="page-header-text">login</h1> 
    </div>  
     <table border = "0" width = "100%"> 
      <tr> 
       <div class = "middle"> 
        <td style = "width:40%"> 
        <input type = "button" id = "loginButton" class = "btn btn-primary" onclick = "authUser();" value = "Login | Facebok" style = "display:none; left:500px; margin-top:200px; position:relative"/> 
        </td>    
       </div> 
      </tr>    
     </table> 
    <div id = "fb-root"></div> 
    <script type = "text/javascript"> 
     var userid; 
     FB.init({ 
     //appId: '', 
     appId: 'app id', 
     xfbml: true, 
     status: true, 
     cookie: true, 
     }); 
     FB.getLoginStatus(checkLoginStatus); 
     function authUser() 
     { 
      FB.login(checkLoginStatus, {scope:'email'}); 
     } 
     function checkLoginStatus(response) 
     {    
      if(response && response.status == 'connected') 
      { 
      FB.api('/me?fields = movies,email,name,gender,locale,location,link', function(mydata) 
      { 
       console.log(mydata.email); 
       console.log(mydata.id); 
       userid = mydata.id; 
       var name = mydata.name; 
       gender = mydata.gender; 
       locale = mydata.locale; 
       city = mydata.location; 
       link = mydata.link; 
       //alert(name); 
       var email = mydata.email; 
       //var json = JSON.stringify(mydata.movies.data); 
       //var a = JSON.parse(json); 
       var picture = "https://graph.facebook.com/"+userid+"/picture?type = small"; 
       // alert(picture); 
       $.post('user_record.php',{ name: name, email: email, userid:userid, picture:picture, gender: gender, locale: locale, city: city, link: link}, function(data) 
       { 
        var $form = $("<form id = 'form1' method = 'post' action = 'start.php'></form>"); 
        $form.append('<input type = "hidden" name = "userid" value = "'+userid+'" />'); 
        $('body').append($form); 
        window.form1.submit(); 
       }); 
      }); 

      console.log('Access Token: ' + response.authResponse.accessToken); 
      } 
      else 
      { 
       document.getElementById('loginButton').style.display = 'block'; 
      } 
     } 
    </script> 
</body> 

Исходный код на GitHub: https://github.com/karimkhanp/facebookLoginSDK

Смежные вопросы