I need to read the posts on facebook. I had create the application and the program works if I log with my credential. But when I log with another credential ( like another profile that I have just created) the program doesn't work anymore. This is my login page:
$config = array(
'appId' => APPID,
'secret' => APPSECRET,
'allowSignedRequest' => false // optional but should be set to false for non-canvas apps
);
$facebook = new Facebook($config);
$user_id = $facebook->getUser();
if(!empty($_SESSION)) {
if($user_id) {
try {
$user_profile = $facebook->api('/me','GET');
$login_url = $facebook->getLoginUrl(array('scope' => 'user_posts'));
$access_token=$facebook->getAccessToken();
$facebook->setAccessToken($access_token);
} catch(FacebookApiException $e) {
error_log($e->getType());
error_log($e->getMessage());
}
}
} else {
$login_url = $facebook->getLoginUrl(array('scope' => 'user_posts'));
header("Location: ".$login_url);
}
when I login I obtain the access token and I call graph api:
https://graph.facebook.com/******/posts?access_token=**
This is operation work if I m who is logged in the application. If another login in the app this is not work.
Maybe it's a authentication problem. Maybe I forget some operation that I must do to authentica with another account. Anyone can help me?
You need to submit your App to Facebook then Facebook will check and pass you app then you can access you app other account. If you want to check App Functionality you can use Facebook App test user Id. Below I have Explained how to get test user
Goto App Page.
Click on Roles.
Click on to Right Corner Test users.
It will show your test user details.
Use this details and access you App.
You have to make your app public for all users from here: https://developers.facebook.com
have a look on it:
Use /me/feed instead of /me in your API call
see example below
Permissions
Your app needs user_posts permission from the person who created the post or the person tagged in the post. Then your app can read:
Timeline posts from the person who gave you the permission.
The posts that other people made on that person Timeline.
The posts that other people have tagged that person in.
If you attempt to read data from a feed that your app has not been authorized to access, the call will return an empty array.
please read this thread https://stackoverflow.com/questions/30719556/read-post-from-facebook-home/30732874#30732874
READING
/* PHP SDK v4.0.0 */
/* make the API call */
$request = new FacebookRequest(
$session,
'GET',
'/me/feed'
);
$response = $request->execute();
$graphObject = $response->getGraphObject();
/* handle the result */
Related
I have been trying for several days now to successfully post to a client's Facebook Page wall from their website. I need to be able to do this without having a user logged in, which I was able to achieve with an extended access token generated by going to the URL provided in the docs.
What I am trying to do is to fetch an extended token using the PHP SDK as in this question - Facebook PHP SDK: getting "long-lived" access token now that "offline_access" is deprecated, however I receive the following error:
(#200) The user hasn't authorized the application to perform this action
The debug of the auth token generated by the Graph API Explorer shows myself as the User and includes the needed manage_pages and status_update scopes. However, if I run me/accounts, the perms array does not list these under the data for the page in question - not sure if this is relevant.
Here is the code that I have attempted to use:
$facebook = new Facebook(array('appId' => 'xxxxxxx', 'secret' => 'xxxxxx'));
$pageID = 'xxxxxxxx';
$facebook->setExtendedAccessToken();
$accessToken = $facebook->getAccessToken();
try {
$page_info = $facebook->api("/$pageID?fields=access_token");
print_r ($page_info);
} catch (FacebookApiException $e) {
echo $e->getMessage();
}
if( !empty($accessToken) ) {
$args = array(
'access_token' => $accessToken,
'message' => "Catch phrase!"
);
$facebook->api("/$pageID/feed","post",$args);
} else {
// Handle error
}
UPDATE
I found that if I echoed the output of getAccessToken() the result was the app ID and the secret separated by an | - is this what I should be receiving? Seems odd to me since all of the other tokens I have seen are random and much longer.
ANY help at all would be appreciated, I have wasted so much time on this so far. It just seems to work for everyone else.
UPDATE 2
Hi Warren! Looks like you're new around these parts, welcome! Thanks for your research into this, do I need to save these tokens into a DB table and check to see if they are expired every time I try to post? I am ONLY posting to a Page as the Page, apparently this requires the Page access_token rather than what I am assuming is the USER access_token. I believe I also read somewhere that the Page access token never expires, although it changes if I refresh the Graph API Explorer page or request a new user token. Very puzzling.. do not know if I even need to deal with getting new tokens in this app or just use a Page access_token that appears to work?
Also just looking at the base_facebook.php file and the following function:
/**
* Returns the access token that should be used for logged out
* users when no authorization code is available.
*
* #return string The application access token, useful for gathering
* public information about users and applications.
*/
protected function getApplicationAccessToken() {
return $this->appId.'|'.$this->appSecret;
}
Shows what you are experiencing the function setExtendedAccessToken() calls getAccessToken() which calls the function above to do the following inside setExtendedAccessToken:
$access_token_response = $this->_oauthRequest(
$this->getUrl('graph', '/oauth/access_token'),
$params = array(
'client_id' => $this->getAppId(),
'client_secret' => $this->getAppSecret(),
'grant_type' => 'fb_exchange_token',
'fb_exchange_token' => $this->getAccessToken(),
)
);
the return of this function is then {"error":{"message":"No user access token specified","type":"OAuthException","code":1}} but because there is no access_token the function just returns false
the fb_exchange_token can not be the app id and app secret combined.
I have done some testing and what I have found out is if you get the user to login, you can get there access token. If you pass this token into setAccessToken then run setExtendedToken. If you then save the toke by running getAccessToken you can use this token later when the user is logged out.
$facebook->setAccessToken($facebook->getAccessToken());
$facebook->setExtendedAccessToken();
$access_token = $facebook->getAccessToken(); // save this for later use
You need to get the user to login to ask them for permission to get access to there account. If you need to get access to a facebook page make sure they are an admin and ask for the manage_page permission.
Hope this helps
From what I have found so far the extended token that is returned when the user is logged in does not expire as you do not get back a unix timestamp so you would have no way of knowing when it expires.
This is what I have done in my application.
Request the user to login to facebook and except the access permissions. Use getAccessToken to get the current access token. With this I pass into getExtendedAccessToken then run getAccessToken again to finally get the extended access token which I store in a database for later use.
$facebook = new Facebook(array(
'appId' => 'YOURAPPID',
'secret' => 'YOURSECRET',
));
$params = array(
'scope'=>'publish_stream,manage_pages'
);
$loginUrl = $facebook->getLoginUrl($params); // Use this to request them to login in then when they are do the following you will need them to return to your app
$facebook = new Facebook(array(
'appId' => 'YOURAPPID',
'secret' => 'YOURSECRET',
));
$facebook->setAccessToken($facebook->getAccessToken());
$facebook->setExtendedAccessToken();
$access_token = $facebook->getAccessToken(); // store $access_token for later use
Hi I have a problem with the Facebook API although I am asking for the permission to get the email I can't get the mail value, what do I do wrong? Here my code:
$facebook = new Facebook(array(
'appId' => 'xxxxxxxx',
'secret' => 'xxxxxxxxxx',
'cookie' => false
));
// See if there is a user from a cookie
$fbuser = $facebook->getUser();
if ($fbuser) {
try {
// Proceed knowing you have a logged in user who's authenticated.
$FBUSER = $facebook->api('/me');
$FBUSER1 = $facebook->api('/me');
print_r($FBUSER1);
} catch (FacebookApiException $e) {
print_r($e);
$USER=false;
}
}
$loginUrl = $facebook->getLoginUrl(array("scope"=>"email, publish_actions"));
A few days ago I was coding a similar login/authorization bit of my app and I had similar results until I properly ordered the flow steps.
From your snippet it looks like you print the $fbuser array before the user actually grants the extended permissions to your app. Let's imagine you were doing some tests with your own account being logged in to facebook: you might have authorized the app once with the basic permission and now it returns these basic data from your account (with no "email" as it belongs to the extended perms).
More code could help to better understand but I would still double check that:
1. the page/popup coming from the FB getLoginURL() method is shown and the user accepts both to login (if not) and to authorize the extended permissions if needed.
2. the return_uri code on your website is ready to catch any data coming from the previous step (eg. print the user details).
Watchout as I see from your code that the return_uri is not defined.
If you send request without access_token, you will get short field set without email and some different fields.
My client has a e-commerce website where they sell their products and they also have facebook page for that website. I want to to publish wall post on that page when ever the product price is reduced or new product is lunched. But i want to make this automatic, so i want to authorize facebook automatic, means that i don't want any login dialog box. the script should authorize itself. now the code i am using is as below but it ask me for log in. and also tell me which method is good(easy) to publish page wall post?
require 'API_Library/Facebook/src/facebook.php';
$page_id = '111111111111111';
$appId = '111111111111111';
$appSecret = 'aaaaaaaaaaaaaaaaaaaaa22222222222';
$facebook = new Facebook(array(
'appId' => $appId,
'secret' => $appSecret,
'cookie' => true
));
$session = $facebook->getAccessToken();
$me = NULL;
if($session)
{
try
{
$me = $facebook->api('/me');
$facebook->api('me/feed', 'post', array(
'message' => 'Hello World!'
));
}
catch(FacebookApiException $e)
{
echo $e->getMessage();
}
}
OUTPUT:
(#200) The user hasn't authorized the application to perform this action
In order to post something to a page, you will need the administrator of the page to be authenticated with the application. You cannot post to a page without being authenticated. So there will be some user interaction required before you can set this up automatically.
The process would be as follows:
Setup a Facebook App to get a App ID and app secret - you'll need this to query the API and post updates to the page
As the page administrator, login to your app with the manage_pages permission.
After logging in, an API call to /me/accounts will give you an access_token to access the page and publish updates
Using the page's accesss_token, you can then POST updates using /{page_id}/feed
Hope this helps.
I'm trying to use the Graph API and the PHP SDK for Facebook to try and return the current users name, but I'm only having luck with it displaying my name. This is pretty straight forward and someone that knows the Graph API shouldn't have any problem helping me out just by looking at the code I'm using.
require 'facebook.php';
$appid=get_post_meta($thisID,'_EFBPDAppID',true);
$appsec=get_post_meta($thisID,'_EFBPDAppSec',true);
$facebook = new Facebook(array(
'appId' => $appid,
'secret' => $appsec,
'cookie' => true
));
$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;
}
}
And then I use this: echo $user_profile['name']; to display the users name, but it is only displaying my name. On any other profile it just shows where that variable is as blank. On my profile, it shows my name. I also used print_r($user); and it is displaying my ID, but for any other profile it displays 0.
Do users need to authenticate themselves or should there already be a session with this info? How do I get that session info if there is one?
Anyone who can help out I would be very grateful. Thanks.
For security and privacy as well, Facebook users must login and allow the current application to have access to their account information. You can accomplish this using different SDK. Most people use Javascript but I persoally prefer PHP. As simple implementation in HTML is shown below:
Login to Facebook
It will generate something like:
Login to Facebook
you should be able to access the user's information after that process using Graph API.
$fbuser = $facebook->api('/me');
echo "Hello ".$fbuser['name'];
Let me know if works for you.
http://www.9lessons.info/2011/02/login-with-facebook-and-twitter.html
Your user must authenticate the application that your going to create.
After that facebook will redirect with the access_token (and the process is called as callback.)
Save the access_token and user id so that you can access data or Post message automatically without login into the facebook.
I've got the rectification for your problem. I use a simple Facebook application. It works but under development.
You must authorize the user first and get his user ID. After that just replace the "me" by user_id, and you are done.
<?php
require_once 'facebook-php-sdk/src/facebook.php';
$facebook = new Facebook(array(
'appId' => '[your app id]',
'secret' => '[your app secreat]',
'cookie' => true,
));
// Then authorize the current user in the way you desire
// get his user_id
$user_profile = $facebook->api('/[the user's user id]');
echo $user_profile['name'];
?>
I am building a web app (PHP) that uses FB connect. I successfully register / sign in user with the help of the PHP lib provided by facebook. Also I can post to wall, using this code
Facebook::$CURL_OPTS[CURLOPT_SSL_VERIFYPEER] = false;
Facebook::$CURL_OPTS[CURLOPT_SSL_VERIFYHOST] = 2;
$facebook = new Facebook(array(
'appId' => $fb_key,
'secret' => $fb_secret,
'cookie' => true, // enable optional cookie support
));
$session = $facebook->getSession();
if ($session)
{
$facebook->api('/me/feed', 'POST', array('message'=>$message, 'link'=>$link['href'], 'name'=>$link['text']));
}
However, if I manually go to my browser's cookie manager and delete the cookie that stores FB session, the code doesn't work. The only thing I have is user's FB ID which I store in DB. Is there any way to post to user's wall even if FB sessions is lost? Does it make sense to store user's FB access token in DB to post to wall later or is the access token relatively short-lived?
Here's an example situation that might happen in my app:
user clicks fb button, authorizes my app, gets redirected back to my site where I automatically create an account based on data provided by FB, also I store user's FB ID so that I could sign in this user later. Now he browses site, enters some info and this info gets posted to his wall. Everything is fine so far because user's browser holds the cookie created by FB. Now user leaves the site and contacts site admin. Admin opens his own browser, goes to admin interface and posts something on behalf of this user. Now, having that user's FB ID and assuming that user hasn't revoked permissions, can I still post this to his wall?
With the Facebook PHP SDK v3 (see on github), it is pretty simple to ask and use a user offline access token. Here is how you do that.
Get the offline access token
First you check if the user is logged in or not :
require "facebook.php";
$facebook = new Facebook(array(
'appId' => YOUR_APP_ID,
'secret' => YOUR_APP_SECRET,
));
$user = $facebook->getUser();
if ($user) {
try {
$user_profile = $facebook->api('/me');
} catch (FacebookApiException $e) {
$user = null;
}
}
If he is not, you generate the "Login with Facebook" URL asking for the offline_access permission :
if (!$user) {
$args['scope'] = 'offline_access';
$loginUrl = $facebook->getLoginUrl($args);
}
And then display the link in your template :
<?php if (!$user): ?>
Login with Facebook
<?php endif ?>
Then, when the user is logged in, you can retrieve the offline access token and store it. To get it, call :
if ($user) {
$token = $facebook->getAccessToken();
// store token
}
Use the offline access token
To use the offline access token when the user is not logged in :
require "facebook.php";
$facebook = new Facebook(array(
'appId' => YOUR_APP_ID,
'secret' => YOUR_APP_SECRET,
));
$facebook->setAccessToken("...");
And now you can make API calls for this user :
$user_profile = $facebook->api('/me');
Hope that helps !
UPDATE: This answer is no longer valid as offline_access is deprecated.
You need to request the offline_access permission. Check the permissions doc.
EDIT Per the update and comments - some info on the removal of the offline_access can be found here.