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.
Related
I have built a site with codeigniter and implemented facebook login for users. Everything is working great there. App is connected user tokens beig saved the whole nine yards. What I am having trouble doing is having the website itself NOT the logged in user post to the connected company facebook page on a user post completion. essentially the user posts a listing. the website then on submit of that posting posts to my facebook company page NOT the logged in users facebook wall. (i have that working already. Can i leave the website logged into Facebook to post to the wall while a user is logged on as well?
You will need to get the Appid, App secret and an access token. You can extend the access token so that it doesn't expire.
$graphUrl = 'https://graph.facebook.com/oauth/access_token?client_id='.APPID .'&client_secret='.APPSECRET.'&grant_type=fb_exchange_token&fb_exchange_token='.ACCESS_TOKEN;
$accessToken = #file_get_contents($graphUrl);
parse_str($accessToken); //get the access_token param in the string and would be named $access_token
if(!$access_token) $access_token = $accessToken; //if cannot be extended then just return the access token with 2 hours expiry
In order to post as your company page, you will need their page id.
Here is part of my script that I used to get all this working. Its not codeigniter, but you will be able to see how it works.
$config = array(
'appId' => APPID,
'secret' => APPSECRET,
);
$facebook = new Facebook($config);
$facebook->setAccessToken(ACCESS_TOKEN);
// Get User ID
$user = $facebook->getUser();
if ($user) {
try {
$page_id = '************'; //
$page_info = $facebook->api("/$page_id?fields=access_token");
if(!empty($page_info['access_token']) ) {
// do your code stuff
}
} catch etc etc
Hope this is helpful to you
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 have a Facebook app that I want to use to post on my customer's Facebook Page Walls on their behalf. I have it setup now so that when they authenticate my app I get the Access token, but when I go to post to the wall I am getting the following error: "OAuthException: Error validating access token: The session is invalid because the user logged out."
How can I post from my script without being logged in?
Here is my code:
include_once('fb-php-sdk/src/facebook.php');
$facebook = new Facebook(array(
'appId' => 'XXX',
'secret' => 'XXX',
));
try {
$page_id = '215133535279290'; //page id of the customer's facebook page
$args = array(
'access_token' => 'XXX', //access token received when user authenticated app
'message' => 'A test message'
);
$post_id = $facebook->api("/$page_id/feed","post",$args);
} catch (FacebookApiException $e) {
echo "Error:" . $e;
}
The new facebook API has what is called an extended access token (it replaces offline access: https://developers.facebook.com/roadmap/offline-access-removal/ I think) which I believe lasts upto 60 days (or something like that). To use it simply get the access token when the logs in through your website:
$token = $facebook->getAccessToken();
Save it to Db and use this token later:
$facebook = new Facebook();
$facebook->setAccessToken($accessTokenFromDB);
Then you should be able to continue as though the user is logged in.
As for the user being logged out part, make sure you are using the latest version of the API and not an old version and also make sure the stuff under the "Scenario 2: If you have been previously requesting offline_access - updated 4/30/2012" heading of the page I linked.
You could carry on using offline_access until 3rd of October, but then why if it's being turned off for real in 2 months time and would have to rewrite your code.
Get the publish_stream extended permission. Once you have this permission you can post feed stories using your app access token while the user is offline. There is no need for offline_access permissions or saving and using a user access token in this scenario.
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've been trying for couple days now without luck, I managed to use the example.php that comes with PHP-SDK and worked perfectly. I just need to store the returned session and use it later on so I could access without re-authenticating.
I tried storing the sessions in a serialized field in a database and then, restoring the data, unserializing it and using setSession function in the php-sdk to retrieve the authentication. Unfortunately, that did not work,
Here is a link to a previous question with the code samples..
Facebook OAuth retrieve information based on stored session
Please advice?
Update: Offline Access in now deprecated. Use something else instead.
If you want to use the access token of the user even after he has logged out of your app, you have to ask for the offline_access permission.
With the Facebook PHP SDK v3 (see on github), it is pretty simple. To log someone with the offline_access permission, you ask it when your generate the login URL. 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 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 !