Facebook PHP API code not working with "Pages" to get Wall posts
<?php
require '../src/facebook.php';
try
{
// Create our Application instance (replace this with your appId and secret).
$facebook = new Facebook(array(
'appId' => '120875194666085',
'secret' => '0272027b5c5c1dabde81096497970c56',
'scope' => 'read_stream',
));
$user = $facebook->getUser();
if ($user) {
try {
// Proceed knowing you have a logged in user who's authenticated.
$user_profile = $facebook->api('/me/feed');
} catch (FacebookApiException $e) {
error_log($e);
$user = null;
}
}
// Login or logout url will be needed depending on current user state.
if ($user) {
$logoutUrl = $facebook->getLogoutUrl();
} else {
$loginUrl = $facebook->getLoginUrl(array('scope' => 'read_stream'));
}
}
catch(FacebookApiException $e){}
?>
<?php
if ($user): ?>
<?php else: ?>
<div>
Login using OAuth 2.0 handled by the PHP SDK:
<a href="<?php echo $loginUrl; ?>">Login with Facebook</a>
</div>
<?php endif ?>
<?php if ($user): ?>
<?php
for($i = 0; $i < 25; $i++)
{
echo "<br />";
echo $user_profile['data'][$i]['from']['name'];
echo " : ";
echo $user_profile开发者_如何学编程['data'][$i]['message'];
}
?>
<?php endif ?>
This worked just fine for normal accounts, but when I tried to log in with a Facebook "Pages" account, it didn't work at all. Any help on this matter? Also, when I got to the Facebook Graphs API documentation, even those links don't give me a proper feed of the Pages wall. From what I had gathered, I had to https://graph.facebook.com/[company page id]/feed??access_token=[access_token] to get it to work (which I am not sure how to translate into the Facebook API.
You should be able to access Fan Page Feeds as long as you have any access_token.
If you have a valid authorised user that is logged in
$fan_page_feed = $facebook->api('/COMPANY_PAGE_ID/feed');
will return a JSON object containing feed data.
Alternatively you could use the applications access_token to get the information. This example gets the feed from the Facebook Platfrom page (For the sake of conciseness, the script also assumes everything will work perfectly - you should implement your own error handling as you see fit):
<html><head></head>
<body>
<pre>
<?php
require ('facebook.php');
$facebook = new Facebook(array(
'appId' => 'YOUR_APP_ID',
'secret' => 'YOUR_APP_SECRET',
'cookie' => true
));
$result = $facebook->api('oauth/access_token', array('client_id'=>'YOUR_APP_ID', 'client_secret'=>'YOUR_APP_SECRET', 'grant_type'=>'client_credentials'));
// $result should contain 'access_token=VALID_ACCESS_TOKEN'
$access_token = explode('=',$result);
$fan_page_feed = $facebook->api('/19292868552/feed', array('access_token'=>$access_token[1]));
print_r($fan_page_feed);
?>
</pre>
</body>
</html>
精彩评论