Facebook PHP SDK Graph API post to page not functioning properly - php

I'm trying to add a feature to my app that will post a status to a admin user's page timeline with the same detail as if they posted on Facebook.com. The main feature I am focusing on is the link sharing and thumbnail images, like when you paste a link into your status and it auto-detects a thumbnail image, gives you a nice link, description, etc. I have tireless read through other forums and the Graph API documents, and I keep running into problems with the post showing as the admin user, rather than the page. Here is my code:
$facebook = new Facebook(array(
'appId' => $appID,
'secret' => $appSecret,
));
$loginUrl = $facebook->getLoginUrl(array(
"scope" => 'publish_stream, read_insights, manage_pages, photo_upload, video_upload, create_note, manage_notifications'
));
$access_token = $facebook->getAccessToken();
$fbpost = array();
$fbpost['access_token'] = $access_token;
$fbpost['message'] = $message;
$fbpost['link'] = $link;
$fbpost['description'] = $description;
$fbpost['caption'] = $caption;
$fbpost['picture'] = $fbimg;
$status = $facebook->api('/'.$pageID.'/feed', 'POST', $fbpost);
var_dump($status);
When I only post the $fbpost['message'] it correctly posts the status as the page, but when I add ANYTHING else it shows the post as the authenticated admin user instead of the page. Very frustrating. Any ideas?

I keep running into problems with the post showing as the admin user, rather than the page.
Then get a page access token, not a user access token for the admin user …

Thanks to CBroe for providing a link to the Facebook docs on the page/app access token. After checking that out, I came up with this PHP (since there is no good documentation in the PHP SDK for getting a page access token):
$user_token = $facebook->getAccessToken();
$accounts = $facebook->api('/me/accounts?access_token='.$user_token);
$account_token = 0;
foreach ($accounts['data'] as $account) {
if ($account['id'] == $_SESSION['facebook']) {
$account_token = $account['access_token'];
}
}
if ($account_token) {
/// your page token code
} else {
echo 'You must be an admin on this page!';
}

Related

How to ask user to like facebook fan page to make download button visible?

I want to create page in which there is a download link. which is only visible to users who have liked my fan page at facebook. Otherwise it show like button.
I am using the following code but it
<?php
include_once("php/src/facebook.php");
// Create our Application instance.
$facebook = new Facebook(array(
'appId' => '354967071210221',
'secret' => 'APP_Secret',
'cookie' => true,
));
$signed_request = $facebook->getSignedRequest();
// Return you the Page like status
$like_status = $signed_request["page"]["liked"];
if($like_status)
{
echo 'User Liked the page';
// Place some content you wanna show to user
}else{
echo 'User do not liked the page';
// Place some content that encourage user to like the page
}
?>
You can get this info using FQL queries
1) Find out your page_id
SELECT page_id, pic FROM page WHERE username="grasphub"
(It says that your page_id is 354967071210221)
2) Check if user has liked your page using this query
SELECT page_id FROM page_fan WHERE page_id=354967071210221 AND uid = me()
This query will return empty result if user did not like your page yet.
So, your code will be:
include_once("php/src/facebook.php");
// Create our Application instance.
$facebook = new Facebook(array(
'appId' => '354967071210221',
'secret' => 'APP_Secret',
'cookie' => true,
));
$user = $facebook->getUser();
if ($user) { // Checks if there is already a logged in user
try {
$result = $facebook->api( array(
'method' => 'fql.query',
'query' => 'SELECT page_id FROM page_fan WHERE page_id=354967071210221 AND uid = me()',
));
if (!empty($result[0]['page_id'])) {
echo 'User Liked the page';
} else {
echo 'User do not liked the page';
}
} catch (FacebookApiException $e) {
error_log($e);
$user = null;
}
} else { //Ask for bare minimum login
$login_url = $facebook->getLoginUrl();
header("Location: ".$login_url);
}
if this code works
you can set show your file inside this if
if($like_status)
{
echo 'User Liked the page';
// Place some content you wanna show to user
}
TEST it!!!
Like / Unlike your FB page and check what the page will return if it gives you different value then its working and inside this IF you know that user likes your page..
First of all try
$signed_request = $facebook->getSignedRequest();
print_r($signed_request);
If it's empty or doesn't contain correct data, you should check your application settings (canvas url, tab url etc.)
You have two options client side or server side:
Here is the a link to a great tutorial on client side scripts
http://www.saschakimmel.com/2010/05/how-to-capture-clicks-on-the-facebook-like-button/
For the server side - You need to get permission from user to access his/her likes - I do not use the FB SDK, I made my own code:
- First the user has to login using this URL:
$loginUrl = "https://www.facebook.com/dialog/oauth?client_id={$appId}&redirect_uri= {$redirectUri}&scope={$scopeEncoded}";
When the user login, FB will ask about giving permissions to this app to access Likes
After accepting & redirecting, get the code in the url using $code = $_GET['code']
The last step is to get the token, you need to make a request using curl to this URL
$url = "https://graph.facebook.com/oauth/access_token?client_id={$appId}&redirect_uri={$redirectUri}&client_secret={$secretKey}&code={$code}";
Now, you have the token you can make curl request to user likes using this URL: https://graph.facebook.com/me/likes?access_token=$accessToken
Loop through the likes and find out if the user likes your page or not or use this URL:
$url = "https://graph.facebook.com/me/likes/{$yourpageId}/?access_token={$accessToken}";
This could be done using graph API .edge.create listens to the click event of like button.
FB.Event.subscribe('edge.create',function(response)
{
download();
});
FB.api("me/likes/page_id", function(response)
{
if ( response.data.length == 1 )
{
//Has liked the page
} else
{
//Havent liked the page
}});
source and download script - http://www.webtuts.info/webdevelopment/facebook-download-script-2/225/

post to the fan page's wall as page from another PHP site

I know that there are lot's of questons on this, but all seem to be needing a user to be logged in... I have been using code snippets from all possible tutorials, but none seem to work.
Here is the scenario:
I have a photo community running on PHP and I have a fan page on Facebook. When an image on the main site collects a certain amount of votes a function is triggered to post the image link to the Facebook wall. The link (post) is posted as a page and not as admin. Admin of course will not be online... Is this even possible to do these days? I have the latest PHP SDK and this is the function that I need to get working in stand alone mode before pluggin' into the main site.
OK. This code works perfectly if I am logged into the Facebook, but if I am not - it will not post... The App has all necessary and unnecessary :) permissions to interact with my page on my (admin) behalf. Any ideas will be appreciated.
<?php
//facebook application
$fbconfig['appid' ] = "1848740815xxxxx";
$fbconfig['secret'] = "a5aa62bb3a8ddcb98d5d9dbe4a3xxxxx";
$fbconfig['pageid'] = "121409594622865";
$user = null; //facebook user uid
try{
include_once "facebook.php";
}
catch(Exception $o){
error_log($o);
}
// Create our Application instance.
$facebook = new Facebook(array(
'appId' => $fbconfig['appid'],
'secret' => $fbconfig['secret']
));
//Facebook Authentication part
$user = $facebook->getUser();
$loginUrl = $facebook->getLoginUrl(
array(
'scope' => 'offline_access,publish_stream'
)
);
$logoutUrl = $facebook->getLogoutUrl();
$pageid = $fbconfig['pageid'];
if ($user) {
try {
$page_info = $facebook->api("/$pageid?fields=access_token");
if( !empty($page_info['access_token']) ) {
$args = array(
'access_token' => $page_info['access_token'],
'message' => 'This is a test feed message',
'link' => 'http://www.fotodvor.com',
'picture' => 'http://www.fotodvor.com/data/media/15/1319971991.jpg',
'name' => 'Test Picture',
'description'=> 'Description of the test picture!'
);
$post_id = $facebook->api("/$page_id/feed","post",$args);
}
} catch (FacebookApiException $e) {
error_log($e);
$user = null;
}
}
?>
Thanks in advance
here is a modified script with explanations adjusted for the changes in the API
<?php
//facebook application
$fbconfig['userid'] = "5332534xx";
$fbconfig['appid' ] = "184874081548xxx";
$fbconfig['secret'] = "a5aa62bb3a8xxxb98d5d9dbe4a368xxx";
$fbconfig['pageid'] = "121409594622xxx";
$fbconfig['token1'] = "AAACoJFn1eLABAKpL9W0nZBrw0e3zzdSNVsTg6FWDMhSnOUeinjid6yAQ2z9JDxxxxxxc1hMHBC3GG18KZBwppGDehWMEwLe56wagZDZD"; // step 1 - returned by loggin in.
$fbconfig['token2'] = "AAACoJFn1eLABAC2Q8OLnqxjUSKzdn9CzaXhy8nsG61vzp2ufePr5iwHZA7TM7Ibxxxxxxyf868O04FeBxMrIo0RCumrNaB78hZAp2uRrbVlGVPXP"; // step 3 - this is a page access token as page
$fbconfig['my_ulr'] = 'http://'.$_SERVER['SERVER_NAME'];
include_once "facebook.php";
// Create our Application instance.
$facebook = new Facebook(array(
'appId' => $fbconfig['appid'],
'secret' => $fbconfig['secret'],
));
// 1. we need to get a user access_token first, (old approach with offline_access forces the tokens received not to expire (good examples here - http://developers.facebook.com/docs/authentication2/ and http://www.howtobe.pro/tag/graph-api)
// run the file and see step 1 instructions.
//offline_access has been deprecated in May 2012 and therefore excluded from the request below
$token_url1 = "https://www.facebook.com/dialog/oauth?"."client_id=".$fbconfig['appid']."&redirect_uri=".urlencode($fbconfig['my_ulr'])."&scope=manage_pages,publish_stream&response_type=token";
echo "<h2>This little working example should give you a working non expiring token to use in your PHP script to enable it to post to your Facebook page as a page and not as a user</h2><br>";
echo "1 - Click on the link below (this redirects to uri with token attached). Log in as admin of the page you are trying to post to. Then copy the token you will get in the address bar to be used in the script in step 2.<br>";
echo "<a href='".$token_url1."' target='_blank'>$token_url1</a>";
//2. then paste the token you received into "step 1" variable in the config section above. Run this script again when logged in to receive all info.
$token_url2 = "https://graph.facebook.com/me?access_token=".$fbconfig['token1'];
$me = json_decode(file_get_contents($token_url2), true);
//echo "<hr><br>this URL gives you all pages that you as admin have access to, but these are NOT what we need to post to the fan page as PAGE so this is just for the heck of it...<br>";
//echo "<a href='".$token_url2."' target='_blank'>$token_url2</a>";
//echo "<hr>this is a raw server reply<br>";
//echo d($me['id'])."<hr>";
//new changes to API - https://developers.facebook.com/roadmap/offline-access-removal/#extend_token
$new_token_url2 = "https://graph.facebook.com/oauth/access_token?client_id=".$fbconfig['appid']."&client_secret=".$fbconfig['secret']."&grant_type=fb_exchange_token&fb_exchange_token=".$fbconfig['token1'];
$new_token2 = file_get_contents($new_token_url2);
$vars = explode('&', $new_token2);
//d($vars);
echo "2. We now obtain a long lasting token (based on <a href='https://developers.facebook.com/roadmap/offline-access-removal/#extend_token' target='_blank'>this</a>)
<br><br>We send the request<br>'".$new_token_url2."'<br><br>and the reply is:<br>'".$new_token2."'<br><br>";
//http://developers.facebook.com/tools/explorer?method=GET&path=533253476&accounts&access_token=AAACoJFn1eLABAFZBftV0vtlBiHKA7ZAIrukrriyp2coWSavj3L4CbfJ9r3WY76IPi7pwUgt3wsubaI4iBbsr663PrbNyaLdZAhLxneOLAZDZD
echo"So now open this page <a href='http://developers.facebook.com/tools/explorer' target='_blank'>http://developers.facebook.com/tools/explorer</a>,
then put the token above to put into the 'Access Token: ' field and press enter... You will need to press 'accounts' link to the right from the response window.
<br>you will see another response and copy your page access token from there. Automating this task into one query did not work... I tried many times.. the token returned IS NOT THE SAME as you would get following the instructions step by step...
This approach does not work - <br>";
echo "http://developers.facebook.com/tools/explorer?method=GET&path=".$me['id']."%2Faccounts&".$vars[0]."<BR><BR><BR>";
echo "Please check it here <a href='http://developers.facebook.com/tools/debug' target='_blank'>https://developers.facebook.com/tools/debug</a> and make sure it never expires...";
$pageid = $fbconfig['pageid'];
try {
//Step 3. Run this script WHEN LOGGED IN to and paste the resulting token into step 3 variable above to check the functionality
/* $page_info = $facebook->api("/$pageid?fields=access_token&".$new_token2); //wrong approach to use this straight. THIS is the access token is that we need. BUT this will work only if user is logged in. so
echo "<hr>this is a page_info breakdown";
d($page_info);
echo "and the access token you needs to paste into fbconfig['token2'] variable is this:<br>";
echo $page_info['access_token']; */
$args = array(
'access_token' => $fbconfig['token2'], //do not attempt to plug the $page_info['access_token'] here... it will be empty once you log off Facebook
'message' => 'This is a test feed message',
'link' => 'http://www.test.com',
'picture' => 'https://www.google.com/intl/en_com/images/srpr/logo3w.png',
'name' => 'Test Picture',
'description'=> 'Description of the test picture!'
);
//uncomment this once you are ready to post and you can see all the access token in the last step. Then comment out all echo and d()'s to make the script silent...
//$post_id = $facebook->api("/$pageid/feed","post",$args);
echo "<hr>This will show once the message is posted - post_id is: <br>";
d($post_id);
} catch (FacebookApiException $e) {
error_log($e);
}
function d($d){
echo '<pre>';
print_r($d);
echo '</pre>';
}
?>
I think I have found the answer. After a long time of testing here is the solution:
Treat this as a little sample/guide for those who are new to this.
The code and output has all necessary info:
<?php
//facebook application
$fbconfig['appid' ] = "184874081XXXXXX";
$fbconfig['secret'] = "a5aa62bb3a8ddcb98d5d9dbe4aXXXXXX";
$fbconfig['pageid'] = "121409594XXXXXX";
$fbconfig['token1'] = "AAACoJFn1eLABAHn92JsWIHZCESQWXmkXZBCedXXXXXXcyUG5vrCYZBXcgsNHN0IUvBj0Sec9vOxVsUgtMHflXXF2cbOF1oZD"; // step 1 - returned by loggin in.
$fbconfig['token2'] = "AAACoJFn1eLABAAUAPthH5DaZCmasZCh5DGGSnZXXXXXXSDh8v1WYYUEWJYuFdua9E5EfJ63c03lfwXrVJbP4VQj35aVcztFgKRYZAheHPNfDeLfbkPys"; // step 3 - this is a page access token as page
$fbconfig['my_ulr'] = 'http://'.$_SERVER['SERVER_NAME'];
include_once "facebook.php";
// Create our Application instance.
$facebook = new Facebook(array(
'appId' => $fbconfig['appid'],
'secret' => $fbconfig['secret'],
));
// 1. we need to get a user access_token first, offline_access forces the tokens received not to expire (good examples here - http://developers.facebook.com/docs/authentication2/ and http://www.howtobe.pro/tag/graph-api)
//run the file and see step 1 instructions.
$token_url1 = "https://www.facebook.com/dialog/oauth?"."client_id=".$fbconfig['appid']."&redirect_uri=".urlencode($fbconfig['my_ulr'])."&scope=manage_pages,offline_access,publish_stream&response_type=token";
echo "1 - this redirects to uri with token attached. Copy and paste this line into your browser and log in as admin of the page you are trying to post to. Make sure you change redirect_uri to your own. Then copy the token you will get in the address bar to be used in the script in step 2.<br>";
echo $token_url1;
//2. then paste the token you received into "step 1" variable in the config section above. Run this script again when logged in to receive all info.
$token_url2 = "https://graph.facebook.com/me/accounts?access_token=".$fbconfig['token1'];
$app_token2 = file_get_contents($token_url2);
echo "<hr><br>2 - this URL gives you all pages that you as admin have access to, but these are NOT what we need to post to the fan page as PAGE<br>";
echo $token_url2;
echo "<hr>2 - this is a raw server reply<br>";
d($app_token2);
$pageid = $fbconfig['pageid'];
try {
//Step 3. Run this script WHEN LOGGED IN to and paste the resulting token into step 3 variable above
$page_info = $facebook->api("/$pageid?fields=access_token"); //wrong approach to use this straight. THIS is the access token is that we need. BUT this will work only if user is logged in. so
echo "this is a page_info breakdown";
d($page_info);
echo "and the access token you needs to paste into fbconfig['token2'] variable is this:<br>";
echo $page_info['access_token'];
$args = array(
'access_token' => $fbconfig['token2'], //do not attempt to plug the $page_info['access_token'] here... it will be empty once you log off Facebook
'message' => 'This is a test feed message',
'link' => 'http://www.test.com',
'picture' => 'https://www.google.com/intl/en_com/images/srpr/logo3w.png',
'name' => 'Test Picture',
'description'=> 'Description of the test picture!'
);
//uncomment this once you are ready to post and you can see all the access token in the last step. Then comment out all echo and d()'s to make the script silent...
//$post_id = $facebook->api("/$pageid/feed","post",$args);
echo "<hr>This will show once the message is posted - post_id is: <br>";
d($post_id);
} catch (FacebookApiException $e) {
error_log($e);
}
function d($d){
echo '<pre>';
print_r($d);
echo '</pre>';
}
?>
You should be using the page access token if i'm understanding what you're trying to do correctly - this is a token which allows your app to act as the page, not as one of the admins.
This is accessible at the /me/accounts endpoint when you have a user access token with manage_pages permission - if you use that access token to post to /{page id}/feed (or photos, etc) it'll appear as the page

Determine if a user has liked my page using Facebook PHP SDK?

My search has come up empty because when you search for "Facebook" and "like" I get all kinds of other results.
I have an app that is only on my company's Facebook page. In that app I need to find out if the user has liked the company's page. I'll show one thing if not and another thing if so. How can I do this using the Facebook PHP SDK v.3.1.1?
It can be done this way:
<?php
require('facebook.php');
$config = array(
'appId' => 'your facebook app id',
'secret' => 'your facebook app secret code',
'allowSignedRequest' => false
);
$facebook = new Facebook($config);
$user_id = $facebook->getUser();
if (isset($user_id)) {
try {
$likes = $facebook->api('/me/likes/your_facebook_page_id_here', 'GET');
if (!empty($likes['data'])) // if user has liked the page then $likes['data'] wont be empty otherwise it will be empty
{
echo 'Thank you for liking our fan page!';
}
else {
//show something else
}
} catch (FacebookApiException $e) {
$login_url = $facebook->getLoginUrl();
echo 'Please click here to login into your Facebook account.';
error_log($e->getType());
error_log($e->getMessage());
}
} else {
$login_url = $facebook->getLoginUrl();
echo 'Please lick here to login into your Facebook account';
}
?>
The user will click on the "Please click here to login into your Facebook account." text which will redirect it to Facebook app permissions page, once user allows the permission to your app the code will fetch user's data and will display what ever you want if user hasn't liked your fan page.
You can do this using FQL. You'll also need to make sure that you have the user_likes permission set.
I pulled this example from an older app that is now offline, it may need to be changed depending on what Facebook has changed in their last round of updates. Lately I've been using javascript and I subscribe to the edge.create event.... just replace the page_id with your page's id and give it a try
$checkIfUserLikePage = $facebook->api(array(
"method" => "fql.query",
"query" => "select uid from page_fan where uid=me() and page_id=1234567"
));
$checkIfUserLikePage = sizeof($checkIfUserLikePage) == 1 ? true : false;
This should work for you! I had to do a lot of these types of pages so I created a really simple way of creating like gated pages. https://github.com/DrewDahlman/FBVersion
Enjoy!
$signed_request = $_REQUEST['signed_request'];
function parsePageSignedRequest() {
if (isset($_REQUEST['signed_request'])) {
$encoded_sig = null;
$payload = null;
list($encoded_sig, $payload) = explode('.', $_REQUEST['signed_request'], 2);
$sig = base64_decode(strtr($encoded_sig, '-_', '+/'));
$data = json_decode(base64_decode(strtr($payload, '-_', '+/'), true));
return $data;
}
return false;
}
if($signed_request = parsePageSignedRequest()) {
if($signed_request->page->liked) {
$this->assign('verify', $signed_request->page->liked);
}
else {
echo "Please click on the Like button to view our Coupons!";
jexit();
}
}
I hope this will help you :)
Old topic, but wanted to weigh in as I have recently learned a lot about how to do this and have had to put it into practice.
Have a look at this link: http://nickring.com/blog/2012/11/facebook-fan-gate-using-php/. It uses the signed_request variable as some of the other responses show, but it shows how it does not require requesting the signed_request variable via $_REQUEST.
The one main thing to remember is that signed_request is only available when the PHP script accessing signed_request is run within Facebook. If you run this script outside of Facebook in a script attempting to use the Facebook API, it will return an empty array.
Here's an example - the following script will run when you go to this address: https://www.facebook.com/yourFacebookPage/app_xxxxxxxxxxxxxxx with 'xxxxxxxxxxxxxxx' being the app ID.
// Check if the user has liked us on Facebook, require the Facebook SDK
require_once('linked/facebook/facebook.php');
// Setup the Config
$config = array(
'appId' => 'xxxxxxxxxxxxxxxxx',
'secret' => 'yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy',
'cookie' => true
);
// Create a Facebook SDK instance
$facebook = new Facebook($config);
// Get the signed_request variable that we so desparately need
$signed_request = $facebook->getSignedRequest();
$like_status = $signed_request["page"]["liked"];
// Make sure that it worked
if (!empty($signed_request))
{
// Get the signed_request information
if ($like_status == 1)
{
// Wo0t! Show the FB fan only page stuff here
}
else
{
// Show the 'Please like us page'
$page = file_get_contents('pages/facebookLikeUs.html');
// Finish the page
echo $page;
exit();
} // End if ($like_status == 1) ELSE Clause and IF
} // End if (!empty($signed_request)) IF Clause
else
{
// Damn, it didn't work. Show an error
}
The above script is the script that is called from the URL set in the Canvas URL in the "App on Facebook" section of the App's settings. The facebookLikeUs.html page is simply a page asking them to click "Like" to continue. If I'm in a situation that I want them to be redirected back into a website that requires the Facebook like I simply replace the // Wo0t! section with something like this:
// Wo0t! They're all set, establish some cookies, get a cookie, and redirect back to the PHD program site
setcookie('fbls', $signed_request['page']['id'] . '-' . $signed_request['user_id'], time() + 300);
$redirectURL = "http://www.myurl.com/theScriptIWantToReceiveTheUserFromFB.php";
// Since Facebook really wants to keep us in the page, we need to create a page that will automatically break out of FB
$page = file_get_contents('pages/facebookRedirectBack.html');
// Replace some stuff
$page = str_replace('$redirectURL', $redirectURL, $page);
// Output the page
echo $page;
exit();
With the facebookRedirectBack.html page being this:
<!DOCTYPE html>
<html>
<body>
<script type="text/javascript">
window.top.location.href = '$redirectURL';
</script>
</body>
</html>
If you're looking to have a bit more security on this, you can have the redirecting PHP script write some cookies and attach them to the URL such that the receiving script must compare the cookies and the URL params then delete the cookies after they've been read.
Hope this helps as I personally haven't found any consistent information on this subject.

How to make a wall post on a community page (as owner of the page) in Facebook?

I have looked at the developers' page but there tons of tons stuff. Application authentication (will my PHP called app?), setting permissions, how to make post after authentication?, where to store authentication? etc etc and so on I wasn't able to get all what all they mean, and what is need in all that stuff.
I only want to make a wall post to the community/fan page's wall as community/fan page. What steps should my PHP application follow to make a wall post?
I've written an in-depth tutorial about this subject: How To: Post On Facebook Page As Page Not As Admin User Using PHP-SDK
In short:
You need at least the publish_stream and manage_pages permissions
Query your page object to get a page access token
And post!
A starting code from my tutorial:
<?php
// This code is just a snippet of the example.php script
// from the PHP-SDK <http://github.com/facebook/php-sdk/blob/master/examples/example.php>
require '../src/facebook.php';
// Create our Application instance (replace this with your appId and secret).
$facebook = new Facebook(array(
'appId' => 'app_id',
'secret' => 'app_secret',
));
// Get User ID
$user = $facebook->getUser();
if ($user) {
try {
$page_id = 'page_id';
$page_info = $facebook->api("/$page_id?fields=access_token");
if( !empty($page_info['access_token']) ) {
$args = array(
'access_token' => $page_info['access_token'],
'message' => "I'm a Page!"
);
$post_id = $facebook->api("/$page_id/feed","post",$args);
}
} 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'=>'manage_pages,publish_stream'));
}
?>
Note: you may need the offline_access if you want to post while you are not connected to Facebook (e.g.: from your CMS)

Issues getting the Facebook PHP SDK to work on my application

I was making a facebook application in which i have to show news feeds of the user who is using it. I am using graph API to do this. The problem is that its not getting me feeds.
I used it to show friends like this:
$friends = $facebook->api('/me/friends');
and it is working fine.
For news feeds i use this:
$feeds = $facebook->api('/me/home');
it shows me an error:
Fatal error: Uncaught IDInvalidException: Invalid id: 0 thrown in
/home/content/58/6774358/html/test/src/facebook.php on line 560
when i try to get Profile feed (Wall) by using this:
$feeds = $facebook->api('/me/feed');
it shows me an empty array.
These API calls are showing me results in the graph API page but don't know why not working in my application.Can any one help me please..
My full code is as follows
require_once 'src/facebook.php';
// Create our Application instance.
$facebook = new Facebook(array(
'appId' => 'xxxxx',
'secret' => 'xxxxx',
'cookie' => true,
));
$session = $facebook->getSession();
$fbme = null;
// Session based graph API call.
if (!empty($session)){
$fbme = $facebook->api('/me');
}
if ($fbme) {
$logoutUrl = $facebook->getLogoutUrl();
echo 'Logout';
}else{
$loginUrl = $facebook->getLoginUrl();
echo 'Logout';
}
$friends = $facebook->api('/me/friends?access_token='.$session["access_token"]);
$feeds = $facebook->api('/me/feed?access_token='.$session["access_token"]);
print('<pre>Herere:');print_r($feeds);die;
Did you ask for the read_stream permission during authentication?
What type of Authentication / "Allow" process did you go through?
JavaScript SDK? Facebook PHP SDK? XFBML Login Button?
EDIT- Here are helpful link that will get you started up:
Facebook PHP SDK
Authentication Process
Building Apps on Facebook.com
These are all official docs in Facebook and github.
EDIT: Follow this step by step:
From your original code, look for:
$loginUrl = $facebook->getLoginUrl();
Change it to:
$loginUrl = $facebook->getLoginUrl(array('req_perms'=>'read_stream'));
Uninstall your application first from your account:
http://www.facebook.com/settings/?tab=applications
Then try it again to show new Allow pop-up
EDIT:
It's also about the arrangement of code in the if statements. Use this code:
<?php
require_once 'src/facebook.php';
$session = $facebook->getSession();
$fbme = null;
if($session){
$fbme = $facebook->api('/me');
$friends = $facebook->api('/me/friends');
$feeds = $facebook->api('/me/feed');
$logoutUrl = $facebook->getLogoutUrl();
echo 'Logout';
echo "<pre>".print_r($feeds,TRUE)."</pre>";
}else{
$loginUrl = $facebook->getLoginUrl(array('req_perms'=>'read_stream','canvas'=>1,'fbconnect'=>0));
echo '<script> top.location.href="'.$loginUrl.'"; </script>>';
}
Uninstall your app again from
http://www.facebook.com/settings/?tab=applications
and re-open the application
The Facebook PHP SDK should handle your access token for you, you don't need to append it to your graph API endpoint in you Facebook::api() call.
As #dragonjet pointed out, you need to request the read_stream extended permission from your FB User in order to get access to their feed. Though, the exception you pasted doesn't really match that kind of problem, and your request to /me/home doesn't throw a similar exception (or one about not having access).
I still think this is a permissions issue, so start here for trying to fix it. Here's an example of how to request the appropriate permission.
$facebook = new Facebook(array(
'appId' => FB_APP_ID, //put your FB APP ID here
'secret' => FB_APP_SECRET, //put your FB APP SECRET KEY here
'cookie' => true
));
$session = $facebook->getSession();
if ($session)
{
//check to see if we have friends_birthday permission
$perms = $facebook->api('/me/permissions');
}
//we do this to see if the user is logged & installed
if (empty($session) || empty($perms['read_stream']))
{
//get url to oauth endpoint for install/login
$loginUrl = $facebook->getLoginUrl(array(
//put the URL to this page, relative to the FB canvas
//(apps.facebook.com) here vvv
'next' => 'http://apps.facebook.com/path_to_your_app/index.php',
'req_perms' => 'read_stream'
));
//use javascript to redirect. the oauth endpoint cant be loaded in an
//iframe, so we have to bust out of the iframe and load it in the browser
//and tell the oauth endpoint to come back to the fb canvas location
echo "<script>window.top.location='{$loginUrl}';</script>";
exit;
}
print_r($facebook->api('/me/home'));
print_r($facebook->api('/me/feed'));

Categories