将fb登录与我的网络应用程序集成

时间:2014-07-27 17:21:13

标签: jquery html5 facebook web-applications login

我已将fb与我的应用集成,如下所示,

我正在使用fb示例代码,当我获得连接状态时,我正在尝试使用OpenMainPage打开我的应用页面。虽然我已成功登录并进入我的应用程序,OpenMainPage()在无限循环中被调用...我在fb回调上下文中打开页面时做错了什么?

  // 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.
       OpenMainPage();
      //window.open("http://Apples-iMac.local/~padmashreebhat/MyProject/MyNest/client/mainpage.html","_self");

    } 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      : '1511255225772471',
    cookie     : true,  // enable cookies to allow the server to access 
                        // the session
    xfbml      : true,  // parse social plugins on this page
    version    : 'v2.0' // use version 2.0
  });

  // 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 OpenMainPage() {
    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.email + '!';
            window.open("http://Apples-iMac.local/~padmashreebhat/MyProject/MyNest/client/mainpage.html","_self");

    });
   }

1 个答案:

答案 0 :(得分:0)

我的这个Javascript代码也存在无限循环问题。我见过打破循环的解决方案。但是我不喜欢插入一个循环中断,因为它仍在执行错误的代码(但是以受控的方式)。 最好重写Javascript代码以避免从一开始就进入无限循环。

我使用此代码段通过Facebook帐户客户端登录用户,然后将帐户信息发回服务器,以根据提供的Facebook凭据自动生成会员用户。

我DID将自己的代码保留在任何Facebook JS函数和事件之外,并通过按钮单击事件处理程序调用它。

更新:当用户使用Facebook登录按钮登录时,我重写了整个登录流程以允许自动服务器端登录/注册。我必须覆盖javascript登录流程,因为它在与主页/内容页面结合使用时会生成循环;即使这样它也无法正常工作,所以我创建了自己的附加服务器逻辑。 这是客户端代码:

 /*
    * /////////////////////////////////          FACEBOOK LOGIN JAVASCRIPT EVENTS        //////////////////////////////
    */

    // 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 = 'You haven\'t authorized 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 = 'You are not signed in to 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);
        });
    }

    function login() {
        FB.Event.subscribe('login', FaceBookRegister());
    }
    //, { scope: 'user_location,user_likes' }
    var loggedIn = false;
    var uid;
    var accessToken;
    var form;

    window.fbAsyncInit = function () {
        FB.init({
            appId: '700271373360155',
            status: true,
            cookie: true,  // enable cookies to allow the server to access 
            // the session
            xfbml: true,  // parse social plugins on this page
            version: 'v2.0' // use version 2.0
        });



        FB.Event.subscribe('auth.authResponseChange', function (response) {
            if (response.status === 'connected') {
                // the user is logged in and has authenticated your
                // app, and response.authResponse supplies
                // the user's ID, a valid access token, a signed
                // request, and the time the access token 
                // and signed request each expire
                uid = response.authResponse.userID;
                accessToken = response.authResponse.accessToken;
                sessionStorage.setItem("authorized", true);
                loggedIn = true;
                statusChangeCallback(response);
                // This is a form post since we don't want to use AJAX
            }
            else if (response.status === 'not_authorized') {
                // the user is logged in to Facebook, 
                // but has not authenticated your app
                loggedIn = false;
                initLogin = false;
            } else {
                sessionStorage.removeItem("UserName");
                loggedIn = false;
                FacebookLogoutLocal();
            }
        });

        // 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) {
        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/en_US/all.js";
        ref.parentNode.insertBefore(js, ref);
    }(document));

    // 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 =
              'You are now loggeed in, ' + response.name + '!';
            var userAuthenticated = sessionStorage.getItem("UserName");
            if (userAuthenticated != response.name) {
                FaceBookRegister();
            }
            sessionStorage.setItem("UserName", response.name);

        });
    };

    ////////////////////////////////        AUTHENTICATE THE FACEBOOK USER ON THE SERVER    ///////////////////////////////

    function FaceBookRegister() {

        if (loggedIn == true) {
            form = document.createElement("form");
            form.setAttribute("method", 'post');
            form.setAttribute("action", '/FacebookLoginMobileEng.ashx');

            var field = document.createElement("input");
            field.setAttribute("type", "hidden");
            field.setAttribute("name", 'accessToken');
            field.setAttribute("value", accessToken);
            form.appendChild(field);
            document.body.appendChild(form);
            form.submit();
        }
        else {
            //alert('U dient zich eerst aan te melden met uw Facebook account!');
            FacebookLogoutLocal();
        }

    }

    ////////////////////////////////           LOGS THE USER OUT FROM THE SERVER              ////////////////////////////

    function FacebookLogoutLocal() {
        if (loggedIn == false) {
            form = document.createElement("form");
            form.setAttribute("method", 'post');
            form.setAttribute("action", '/FacebookLogout.ashx');
            document.body.appendChild(form);
            form.submit();
        }
    }

从FB Javascrip SDK站点,您应该使用authResponseChange事件中的表单提交数据;但这会产生无限循环。 所以我将该代码放在我自己的函数中。 注册功能在我的会员数据库中创建一个Facebook用户,其中包含Facebook名称和电子邮件以及自动生成的密码以确保安全。它最初将facebook数据发回服务器并将其传递给HTTP处理程序,该处理程序重定向到专用于处理facebook凭据和其他凭据的页面,以编程方式创建新的Membership用户。

要与Javascript SDK一起正常工作,我必须添加其他服务器逻辑: 您必须重定向到没有相同主服务器的页面。您需要先存储请求网址:

FaceBookSession.UrlFbLoginSolver = context.Request.UrlReferrer.AbsolutePath;

我在我的主文件代码中使用它来检查:

if (FaceBookSession.UrlFbLoginSolver.Contains("Dutch"))
        {
            string url = FaceBookSession.UrlFbLoginSolver;
            FaceBookSession.UrlFbLoginSolver = String.Empty;
            Response.Redirect(url);//redirects back to the original requester
        }
        else
        {
          ....//normal page load
        }