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 https://developers.facebook.com/docs/facebook-log... 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>

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.