FB.login with PHP API

后端 未结 3 2150
情书的邮戳
情书的邮戳 2021-01-13 09:10

I\'ve set up a Canvas Page which doe\'s a FB.login on click of a form submit button. During the following request it tries to access the users data via $facebook->api(\'/me\

3条回答
  •  余生分开走
    2021-01-13 09:37

    I had the same problem and I've included a solution below.

    I believe the reason this happens is because on a Javascript login attempt your server never receives any access tokens. The Javascript is only passing data between your browser and Facebook.com so your server has no idea what the authentication status is. Your server will only receive the new access tokens when the page is refreshed; this is where facebook hands over the access tokens.

    Heres my solution. Upon a successful login via FB.login you will receive the response object and inside it is an access_token. All you need to do is pass this access token to your script in some way. Here is an example:

    // Hold the access token
    var js_access_token = "";
    
    // Connect to facebook
    FB.login(function(response) {
      if (response.session) {
        if (response.perms) {
          // user is logged in and granted some permissions.
          // Save the access token
          js_access_token = response.session.access_token;
          // Do stuff on login
        }
      }
    });
    

    You then include the access token along with any requests. I've chosen an ajax example.

    // Communication back to server.
    $.ajax({
      url: 'myurl.php',
      data: {
        js_access_token: js_access_token // Including the js_access_token
      },
      success: function(data) {
        console.log(data);
     }
    });
    

    Within your PHP you then need to have something which looks like this:

    $facebook = new Facebook(array(
      'appId' => $appid,
      'secret' => $appsecret,
      'cookie' => TRUE,
    ));
    if ($facebook) {
    
      // If we get the access token from javascript use it instead
      if (isset($_REQUEST['js_access_token']) && $_REQUEST['js_access_token']) {
        $facebook->setAccessToken($_REQUEST['js_access_token']);
      }
    
      try {
        $me = $api->api('/me');
      }
      catch (Exception $exc) {
        // Failure in Safari and IE due to invalid auth token
      }
    }
    

    Hope this helps

提交回复
热议问题