2

I am trying to integrate our DB with the facebook API , really new on this so I would appreciate some help.

I am always getting 0

Using

$uid = $facebook->getUser()

I had a look to similar issues but didn't find a related solution.

PHP

if($_REQUEST['action']=="signup" && $_REQUEST['auth']=="facebook" && !empty ($_REQUEST['auth'])  && !empty ($_REQUEST['action']) )
{

require_once('libs/facebook/src/facebook.php');

$config = array();
$config['appId'] = 'xxxx';
$config['secret'] = 'xxxxxx';

$facebook = new Facebook($config);
$uid = $facebook->getUser();
echo $uid;
}

//else {} normal sign up here with all the error checking

HTML

<div class="fb-login-class">
      <div class="fb-login-button" autologoutlink="true" scope="publish_stream" perms="email,user_birthday" data-show-faces="false"
      data-width="200" data-max-rows="1"></div>
</div>

JAVASCRIPT / JQUERY

window.fbAsyncInit = function() {
    // init the FB JS SDK
    FB.init({
      appId      : 'XXXX,                        // App ID from the app dashboard
      channelUrl : '//WWW.XXXX.com', // Channel file for x-domain comms
      status     : true,                                 // Check Facebook Login status
      xfbml      : true                                  // Look for social plugins on the page
    });



    // Additional initialization code such as adding Event Listeners goes here
     // will be handled. 
  FB.Event.subscribe('auth.authResponseChange', function(response) {
    // Here we specify what we do with the response anytime this event occurs. 
    if (response.status === 'connected') {


      loginfunction();
    } else if (response.status === 'not_authorized') {

      FB.login(function(response) {},{scope: 'email'});
    } else {

      FB.login(function(response) {},{scope: 'email'});
    }
  });
  };

(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_GB/all.js#xfbml=1&appId=XXXXX";
  fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));


function loginfunction() {
    console.log('Welcome!  Fetching your information.... ');
    FB.api('/me', function (response) {
        console.log(response);
/*I can see all the data here and the button also changes so I know that I am logged in */
        var data = 'action=signup&username=' + response.username + '&firstname=' + response.first_name + '&gender=' + response.gender + '&lastname=' + response.last_name + '&email=' + response.email + '&dob=' + "xxxx" + '&auth=facebook';
/*What's the point in passing all these parameters through ? only need to pass &auth=facebook and action=signup I guess the rest can be manipulated anyway so what's the point 
need to get them from PHP SDK (server side ajax call) */

        $.ajax({
            type: "POST",
            url: "actions/do_signup.php",
            data: data,
            beforeSend: function (html) {},
            success: function (html) {
                if (html == "success") {
                    window.location.replace("index.php");
                } else {}
            }
        });
    }, {
        scope: 'email'
    });
}

thanks

EDIT tried that only with PHP still failed

require('facebook.php');
$facebook = new Facebook( array (
    'appId'  => 'xxx',
    'secret' => 'xxxx',
    'cookie' => true
  )
);


if ($_REQUEST['act']=="fb")
{
//$next_url = $facebook->getLoginStatusUrl($params);

if ($facebook->getUser()) {
       $userProfile = $facebook->api('/me');
       $uid = $facebook->getUser();
       // do logic
       echo  $uid ;
       echo "ok";
    } else {
    echo "problem";
      $loginUrl = $facebook->getLoginUrl($params = array('scope' => user_birthday,read_stream,'redirect_uri' => 'http://xxxx/index.php?act=success'));
      header('Location:' . $loginUrl);

    }
}
else if ($_REQUEST['act']=="success")
{
  try{
      $_SESSION['fbAT'] = $facebook->getAccessToken();
    }catch(Exception $e){
      trigger_error("FB AccessToken: " . $e->getMessage());
    }    
$facebook->setAccessToken($_SESSION['fbAT']);

if ($facebook->getUser()) {
        $uid = $facebook->getUser();
       $userProfile = $facebook->api('/me');

       // do logic
       echo  $uid ;
       echo $userProfile;
       echo "ok";
    } else {
    $uid = $facebook->getUser();
    echo  $uid ;
    echo "still problem";


    }

Some steps that I have tried:

  • Sandbox Mode is disabled and I have confirmed the app id and secret as well...
  • Tried adding header : header('P3P:CP="IDC DSP COR ADM DEVi TAIi PSA PSD IVAi IVDi CONi HIS OUR IND CNT"');
  • Added cookie' => true
  • Try calling it from a static page not through ajax still 0
  • Only website is used under facebook basic tab
  • Under advanced app type is set to web
  • Under permissions default activity is public
  • Made sure that fb_ca_chain_bundle.crt is in the same dir that facebook.php also tried to use a different dir (the same with my php file)
    • Trying only PHP and getLoginUrl with additional scope to get access.
    • Trying getting and setting an access token
Athanatos
  • 1,089
  • 6
  • 15
  • 32

2 Answers2

4

In window.fbAsyncInit I have set cookie and oauth to true and this worked!

cookie:true,    
oauth : true.

Make sure that In your php you also have

cookie' => true.

That will enable the php code to integrare with the JS.

Athanatos
  • 1,089
  • 6
  • 15
  • 32
0

And you need to make sure the user has logged in with:

$loginUrl = $facebook->getLoginUrl(array( 'scope' => 'read_stream,etc..'));

The scope is defined by the permissions stated here

After that you should be able to do:

$user = $facebook->api("/me");

Which will get an array associated with the user, $user['id'] is probably the one you'll want to store as well as any other information like email address - be sure to request for email in the scope

Hope that solves the problem!

GroovyCarrot
  • 514
  • 3
  • 6
  • Tried that still getting 0 back . I would't expect the need to login again using getloginurl (as I am already logged in via JS), however doing that I am still getting 0 back. – Athanatos Sep 29 '13 at 21:43
  • I have updated the question with the code – Athanatos Sep 29 '13 at 21:49
  • Logging into Facebook with JavaScript will give the users browser access to the Facebook api but not your server, which will be making PHP calls - I'll do some reading for you and try to explain how to combine the two methods of communicating with Facebook, but off the top of my head I'm thinking you need to log in with PHP and `getLoginUrl`, then pass your `$facebook->getAccessToken()` to your JavaScript. Will do some reading and give you a more concise answer, but for now you should make sure that after logging in you can `print_r($facebook->api('/me'));` and retrieve your information – GroovyCarrot Sep 30 '13 at 00:30
  • Also in your PHP code the line: `$loginUrl = $facebook->getLoginUrl($params = array('scope' => user_birthday,read_stream,'redirect_uri' => 'http://xxxx/index.php?act=success'));` is missing quotes around your params as you are just passing a string so try: `$loginUrl = $facebook->getLoginUrl($params = array('scope' => 'user_birthday,read_stream','redirect_uri' => 'http://xxxx/index.php?act=success'));` – GroovyCarrot Sep 30 '13 at 00:40
  • Oh and last thing, don't `echo` before `Header()` as it might prevent redirect – GroovyCarrot Sep 30 '13 at 00:48
  • thanks for all the help, I think I have found the answer I will add it just now. – Athanatos Sep 30 '13 at 11:20