我正在尝试创建一个Facebook应用程序,并在用户打开应用程序时需要来自Facebook的用户ID。我在Facebook画布上设置了我的应用程序及其show mock模板,我需要帮助将Facebook API连接到我的页面,我是否需要为此下载API?如何从Facebook说它发送给应用程序的JSON对象中获取用户ID?
我的测试应用是:
<?php
echo "this is working";
?>
这适用于Facebook。
答案 0 :(得分:9)
下载PHP SDK
获取用户ID的一个非常简单的代码示例 - 如果用户已登录并已授权应用程序,那么$facebook->getUser()
将为您提供用户ID:
require 'facebook.php';
$facebook = new Facebook(array(
'appId' => 'YOUR_APP_ID',
'secret' => 'YOUR_APP_SECRET',
));
// Get User ID
$user = $facebook->getUser();
if ($user) {
try {
// Get the user profile data you have permission to view
$user_profile = $facebook->api('/me');
echo "<pre>";
print_r($user_profile);
echo "</pre>";
} catch (FacebookApiException $e) {
$user = null;
}
} else {
die('<script>top.location.href="'.$facebook->getLoginUrl().'";</script>');
}
查看SDK中的示例以及Facebook Developers Site。
答案 1 :(得分:0)
这是我编写的一种黑客代码,它允许获取任何Facebook用户ID,即使他未登录或未经app授权 https://github.com/invisiblevision/get-facebook-id/
<?php
$profile_url = 'https://facebook.com/profileUrl';
function get_web_page( $url )
{
$user_agent='Mozilla/5.0 (Windows NT 6.1; rv:8.0) Gecko/20100101 Firefox/8.0';
$options = array(
CURLOPT_CUSTOMREQUEST =>"GET", //set request type post or get
CURLOPT_POST =>false, //set to GET
CURLOPT_USERAGENT => $user_agent, //set user agent
CURLOPT_COOKIEFILE =>"cookie.txt", //set cookie file
CURLOPT_COOKIEJAR =>"cookie.txt", //set cookie jar
CURLOPT_RETURNTRANSFER => true, // return web page
CURLOPT_HEADER => false, // don't return headers
CURLOPT_FOLLOWLOCATION => true, // follow redirects
CURLOPT_ENCODING => "", // handle all encodings
CURLOPT_AUTOREFERER => true, // set referer on redirect
CURLOPT_CONNECTTIMEOUT => 120, // timeout on connect
CURLOPT_TIMEOUT => 120, // timeout on response
CURLOPT_MAXREDIRS => 10, // stop after 10 redirects
);
$ch = curl_init( $url );
curl_setopt_array( $ch, $options );
$content = curl_exec( $ch );
$err = curl_errno( $ch );
$errmsg = curl_error( $ch );
$header = curl_getinfo( $ch );
curl_close( $ch );
$header['errno'] = $err;
$header['errmsg'] = $errmsg;
$header['content'] = $content;
return $header;
}
/*Getting user id */
$url = 'http://findmyfbid.com';
$data = array('url' => $profile_url );
// use key 'http' even if you send the request to https://...
$options = array(
'http' => array(
'header' => "Content-type: application/x-www-form-urlencoded\r\n",
'method' => 'POST',
'content' => http_build_query($data),
),
);
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);
function getData($data)
{
$dom = new DOMDocument;
$dom -> loadHTML( $data );
$divs = $dom -> getElementsByTagName('code');
foreach ( $divs as $div )
{
return $div -> nodeValue;
}
}
$uid = getData($result); // User ID