good afternoon,
I have been trying to use "login with facebook" on my website for 15 days. I have been using the code published by Facebook, at the link ... web / v2.2.

My problem with this code is that I want the customer after login with his facebook (through the window that pop out) to be redirected to a specific page on my website, but what happens is that after the customer does login with your facebook, the client is redirected to the same page that asks him to login.

I have already followed the steps that are explained in the link that I mentioned earlier. Could someone help me?

the code i am using is this:

</script> <html> <head> <title>Facebook Login JavaScript Example</title> <meta charset="UTF-8"> </head> <body> <script>

  function statusChangeCallback(response) {  // Called with the results from FB.getLoginStatus().
    console.log('statusChangeCallback');
    console.log(response);                   // The current login status of the person.
    if (response.status === 'connected') {   // Logged into your webpage and Facebook.
      testAPI();  
    } else {                                 // Not logged into your webpage or we are unable to tell.
      document.getElementById('status').innerHTML = 'Please log ' +
        'into this webpage.';
    }
  }

  function checkLoginState() {               // Called when a person is finished with the Login Button.
    FB.getLoginStatus(function(response) {   // See the onlogin handler
      statusChangeCallback(response);
    });
  }

  window.fbAsyncInit = function() {
    FB.init({
      appId      : '{}',
      cookie     : true,                     // Enable cookies to allow the server to access the session.
      xfbml      : true,                     // Parse social plugins on this webpage.
      version    : '{api-version}'           // Use this Graph API version for this call.
    });

    FB.getLoginStatus(function(response) {   // Called after the JS SDK has been initialized.
      statusChangeCallback(response);        // Returns the login status.
    });
  };

  (function(d, s, id) {                      // Load the SDK asynchronously
    var js, fjs = d.getElementsByTagName(s)[0];
    if (d.getElementById(id)) return;
    js = d.createElement(s); js.id = id;
    js.src = "https://connect.facebook.net/en_US/sdk.js";
    fjs.parentNode.insertBefore(js, fjs);
  }(document, 'script', 'facebook-jssdk'));

  function testAPI() {                      // Testing Graph API after login.  See statusChangeCallback() for when this call is made.
    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> <fb:login-button scope="public_profile,email" onlogin="checkLoginState();"> </fb:login-button> <div id="status"> </div> </body> </html> <div id="fb-root"></div> <script async defer crossorigin="anonymous" src="https://connect.facebook.net/en_GB/sdk.js#xfbml=1&version=v6.0&appId=505608310005112&autoLogAppEvents=1"></script> <div class="fb-login-button" data-width="" data-size="" data-button-type="continue_with" data-layout="rounded" data-auto-logout-link="true" data-use-continue-as="true"></div> <script>

Dani AI

Generated

Short answer: nothing in the Facebook JS SDK will automatically send the user to another page for you — the app must perform the redirect after a successful login. In your existing flow the right place to redirect is inside the callback that confirms a successful login (the code path where response.status === 'connected' or after you successfully fetch FB.api('/me')). Use location.replace('/your-target.html') if the login page should not remain in history, or location.href = '/your-target.html' if it should.

Practical checklist based on the thread:

  • Make sure the same app ID is present in your FB.init call and you only load the SDK once (remove duplicate sdk.js includes). ’s snippet appears to include multiple SDK script tags which can conflict.
  • Place <div id="fb-root"></div> and the SDK include in the recommended order and keep your HTML structure valid.
  • If relying on an OAuth redirect (server-side code), follow the explicit OAuth flow and whitelist the redirect_uri in the Facebook app settings, as suggested — that flow performs the redirect server-side and is more robust for exchanging codes/tokens.
  • Use HTTPS in production and test in a private window to avoid cached login state. Watch the browser console and the network tab for SDK or permission errors.

Example (do the redirect only after login is confirmed):

if (response.status === 'connected') {
  // optional: wait for FB.api('/me') if you need user info first
  window.location.replace('/after-login.html');
}

Extra notes: prefer redirecting from inside the success callback so the redirect only occurs when an authResponse exists. If the app stays in development mode only listed users will be allowed to log in. Finally, check for deprecated Graph API/SDK versions and update to the current SDK before deploying.

Recommended Answers

All 4 Replies

I’ve had much success with the server side implementation of OAuth and I always find the JS version a but tricky.

Is the code above modified properly with your app ID and API version?

Ping :)

Were you ever able to get this working? Per my previous post, is your app ID properly specified in your actual code?

commented: Hi Dani, my app on facebook is setup and live. If you have a code more simple and working with login of FB and you can share i'll be thankful +0

So I actually wrote two tutorials for using OAuth 2 with the DaniWeb API.

Here is the one for being PHP-based: https://www.daniweb.com/programming/web-development/tutorials/469804/getting-started-with-oauth-2-0-explicit-flow

And here is the one for being Javascript-based: https://www.daniweb.com/programming/web-development/tutorials/469810/oauth-2-0-implicit-flow-with-the-daniweb-api

Connecting to Facebook via OAuth is quite similar. Here's my code (I use PHP Codeigniter framework) to connect via Facebook.

public function auth($service = 'facebook')
{
    // Attempt to retrieve the referer
    if (($referer = $this->input->get('uri')) === null)
    {
        $referer = $this->input->get('state');
    }

    if (empty($referer))
    {
        $referer = 'profile';
    }

    $redirect_uri = urlencode(base_url(uri_string()));

    $oauth = array(
        'linkedin' => array(
            'YOUR_APP_ID' => '',
            'YOUR_APP_SECRET' => '',
            'COMMA_SEPARATED_LIST_OF_PERMISSION_NAMES' => 'r_basicprofile,r_emailaddress'
        ),
        'facebook' => array(
            'YOUR_APP_ID' => '',
            'YOUR_APP_SECRET' => '',
            'COMMA_SEPARATED_LIST_OF_PERMISSION_NAMES' => 'email,public_profile'
        ),
        'google' => array(
            'YOUR_APP_ID' => '',
            'YOUR_APP_SECRET' => '',
            'COMMA_SEPARATED_LIST_OF_PERMISSION_NAMES' => 'profile email'
        )
    );

    if ($service == 'facebook')
    {
        // Retrieve everything passed in as a query string
        $parameters = $this->input->get();

        // If ?code= is passed in and not empty ...
        if (isset($parameters['code']))
        {
            $code_generated_by_facebook = $parameters['code'];

            // If ?state= is passed in and a valid match ...
            // Hash is changing on every page refresh?
            if (isset($parameters['state']))
            {
                // Make an API call to fetch an access token
                $ch = curl_init();
                curl_setopt($ch, CURLOPT_URL, 'https://graph.facebook.com/v3.2/oauth/access_token');
                curl_setopt($ch, CURLOPT_POST, true);
                curl_setopt($ch, CURLOPT_POSTFIELDS, "client_id={$oauth['facebook']['YOUR_APP_ID']}&redirect_uri=$redirect_uri&client_secret={$oauth['facebook']['YOUR_APP_SECRET']}&code=$code_generated_by_facebook");
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

                // Retrieve the result of the API call
                $result = json_decode(curl_exec($ch));
                curl_close($ch);

                // Use the access token retrieved to make the desired API request to retrieve a member's profile
                if (isset($result->access_token))
                {
                    $access_token = $result->access_token;

                    $app_secret_proof = hash_hmac('sha256', $access_token, $oauth['facebook']['YOUR_APP_SECRET']);

                    $file = file_get_contents("https://graph.facebook.com/v3.2/me?fields=id,picture,about,birthday,education,email,first_name,last_name,relationship_status,website,work&appsecret_proof=$app_secret_proof&access_token=$access_token");
                    $user = json_decode($file);                     

                    // We have access to the User now!!

                }
            }
        }
        else
        {
            // Initiate redirect to Facebook OAuth API
            redirect("https://www.facebook.com/v2.0/dialog/oauth/?display=page&client_id={$oauth['facebook']['YOUR_APP_ID']}&redirect_uri=$redirect_uri&state=" . urlencode($referer) . "&scope={$oauth['facebook']['COMMA_SEPARATED_LIST_OF_PERMISSION_NAMES']}");
        }
    }

    // We have retrieved a valid user from the API

}
commented: I am sorry for my lack of knowledge, but you're too good for me! I give you the details you need to fill the code, and just copy it. Is it possible? +0

So the code that I have provided here is server-side, while the code you were working with is client-side. Do you have any experience working with server-side OAuth? Also keep in mind the code I've provided only works with my Codeigniter framework, so you can't copy/paste it.

However, it's heavily commented. If you read it and understand how it works, you should be able to create what you need based off of it in your own project.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.