获取Facebook用户ID

时间:2012-09-17 09:55:19

标签: facebook tabs

我已经在网上搜索了高低,无法弄清楚我面临的问题。我在Facebook上有一个页面选项卡应用程序,用户喜欢该页面开始,然后他可以回答一些问题,我可以将facebook连接到功能但我无法获取用户ID并将其保存到数据库。

我在索引页面中有这个

<? include('db.php'); 
include_once("config.php");

// Finnur út hvaða spurninga sett á að nota
$sp_set = 1;

require_once 'facebook-php-sdk/src/facebook.php';
// Create our Application instance.
$facebook = new Facebook( array('appId' => '289393321124676',
'secret' => 'd47b7871e0a7fb475db6e2a643f675ed', 'cookie' => true, ));
$signed_request = $facebook -> getSignedRequest();
$like_status = $signed_request["page"]["liked"];
$user = $facebook->getUser();

//If the page is liked then display full app.

?>

用户ID始终为null,当用户提交问题时,所有内容都保存到数据库但用户为0。

请帮忙

3 个答案:

答案 0 :(得分:0)

  

$ user = $ facebook-&gt; getUser();

这将为您提供任何用户ID,除非用户已首先连接到您的应用。

因此,您必须在应用中实现客户端或服务器端Auth流。 https://developers.facebook.com/docs/authentication/pagetab/

答案 1 :(得分:0)

试试这个例子:

<?php

    $secret   = '********************************'; // App Secret 
    $app_id   = '***************';                  // App ID
    $page_url = 'https://www.facebook.com/*******'; // FB fan page URL, where the application tab is installed

    require 'src/facebook.php';

    $facebook = new Facebook(array(
        'appId'  => $app_id,
        'secret' => $secret,
    ));

    // Get User ID
    $user = $facebook->getUser();

    if ($user) {
        try {
            // Proceed knowing you have a logged in user who's authenticated.
            $user_profile = $facebook->api('/me');
        } catch (FacebookApiException $e) {
            error_log($e);
            $user = null;
        }
    }

    // Login url will be needed depending on current user state.
    if (!$user) {
        $loginUrl = $facebook->getLoginUrl(array('redirect_uri' => $page_url.'?sk=app_'.$app_id));
    }

    $signed_request = $facebook->getSignedRequest();

?><!DOCTYPE html>
<html>
    <body><pre>

<?php 

    if (!$user): // isn't authorized
        echo '<a href="'.$loginUrl.'" target="_top">Authorize app</a>';
    else:
        if ($signed_request['page']['liked']): // likes
            echo 'The page is liked by user with id '.$signed_request['user_id'];
        else:
            echo 'The page is <strong>NOT</strong> liked by user with id '.$signed_request['user_id'];
        endif;
    endif;


?>
    </pre></body>
</html>

答案 2 :(得分:0)

我遇到了类似的问题。我最终使用FB JS-SDK来调用oAuth对话框,以允许用户连接到我的应用程序并授予我权限。此时,您可以访问他们的用户ID以及他们授予您许可的任何其他信息。

将以下代码添加到window.fbAsyncInit来电:

FB.login(function(response) {
 if (response.authResponse) {
  console.log('Welcome!  Fetching your information.... ');
  FB.api('/me', function(response) {
   console.log('Good to see you, ' + response.name + '.');
  });
 } else {
  console.log('User cancelled login or did not fully authorize.');
 }
});

来源:https://developers.facebook.com/docs/reference/javascript/FB.login/