开发者

Using Facebook API in PHP

I am currently learning PHP and I want to start incorporating Facebook basic elements such as friend lists etc just to do something more fun than building a web shop. However, I have followed the guides on Facebook and added an app and I got the canvas to display what I want, but how do I start getting data from Facebook? I have downloaded this https://github.com/facebook/php-sdk#readme and I added it to my project.

For example, how would I ask for permissions, pull data from my own profile? Do I need to parse JSON? Where is the API for the PHP SDK? This http://developers.facebook.com/docs/reference/api/ does not look like the get user id part here:

require 'php-sdk/src/facebook.php';

$facebook = new Facebook(array(
  'appId'  => 'YOUR_APP_ID',
  'secret' => 'Y开发者_StackOverflow中文版OUR_APP_SECRET',
));

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

Any points in the right direction would be highly appreciated.


There is no need to parse JSON, you would have to go about doing an API request:

try {
    $user_profile = $facebook->api('/me');
} catch (FacebookApiException $fbException) {
    die('Houston, we got problems.');
    return;
}

This would leave you with either a $user_profile containing every single element you've previously requested permission for (such as first_name, etc), put into an associative array ($user_profile in this case). Obviously, you would first have to check for getUser()'s success or failure (if it returns 0, it failed), as the API call would behave as if you were logged out otherwise.


Have you had a look at example.php included with the PHP SDK? It shows how to do a login and get some basic data using the graph API. To make the permissions dialog appear in your application and retrieve an access token for a given user you can do something like this:

$app_id = "...";
$app_secret = "...";
$my_url = "...";

//session_start();

@$code = $_REQUEST["code"];

if( empty( $code ) ){
    $dialog_url =
            "http://www.facebook.com/dialog/oauth?client_id=" 
           . $app_id . "&redirect_uri=" . urlencode($my_url) . "&state="
           . $_SESSION['state']
           . "&scope=email,user_birthday,user_hometown,user_interests,user_location,user_online_presence,user_photos,user_status,publish_stream"; // Scope defines permissions

    echo("<script> top.location.href='" . $dialog_url . "'</script>"); // Redirect
}

$token_url = "https://graph.facebook.com/oauth/access_token?"
       . "client_id=" . $app_id . "&redirect_uri=" . urlencode($my_url)
       . "&client_secret=" . $app_secret . "&code=" . $code;

$response = file_get_contents($token_url);
$params = null;
parse_str($response, $params);

$graph_url = "https://graph.facebook.com/me?access_token=" . $params['access_token'];

$testuser = json_decode(file_get_contents($graph_url));

if( $testuser != null ){
    // Do stuff
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜