Facebook PHP SDK - An active access token must be used to query information about the current user - facebook

I have problem with Facebook PHP SDK. It always throws that exception. I tried many solutions listed here, but nothing works for me.
It seems that Facebook returns to me valid access token, because I tested it with Debug tool in dashboard of my application.
What's my scenario?
I want to post to publish simple content to user's wall by calling static function:
function social_publish($network, $title, $message, $link = '', $image = '') {
global $_config;
// Initialize Facebook SDK
$facebook = new Facebook(array(
'appId' => $_config['fb_app']['app_id'],
'secret' => $_config['fb_app']['app_security_key']
));
// Set data
$attachment = array(
'name' => $title,
'caption' => $title,
'message' => $message,
'link' => $link,
'picture' => $image,
'actions' => array('name' => 'Test', 'link' => 'Link')
);
try {
$access_token = $facebook->getAccessToken(); // returns valid access token
$uid = $facebook->getUser(); // always return 0
$result = $facebook->api( '/' . $_config['fb_profile'] . '/feed/', 'post', $attachment); // $_config['fb_profile'] procudes 'me' in this case
} catch (FacebookApiException $e) {
echo $e->getMessage();
}
}
Just to note: I am not working on local environment.

problem solve it as asked in scope request to Facebook for authentication, as I decided to use the JavaScript SDK-and then, here's the solution:
FB.getLoginStatus(function(response) {
if ( ! response.authResponse ) {
FB.login(function(response) {
// handle the response if needed
}, {scope: 'publish_actions, publish_stream'});
}
});
Thank you! :-)

Related

Facebook Fan Page Wall Post from website using php sdk returning code parameter

I try to post facebook fan page wall from my website using php sdk 3.0.Its Working fine
Sometimes the redirecturl contains Code parameter and stopped all process.
The url look like www.mysite.com/posttofacebook.php?code='somerandomstring'
i am searching lot of times but i cant get correct solution.I have mention my complete code below.
Pls help me.
Thanks.
<?php
require_once 'src/facebook.php';
// configuration
$appid = 'myappid';
$appsecret = 'myappsecret';
$pageId = 'mypageid';
$msg ='Test ';
$title = 'TestTestTestTestTestTest';
$uri = 'http://www.welcome.com';
$desc = 'TestTestTestTestTestTestTestTestTestTestTest';
$pic = 'http://www.welcome.com';
$facebook = new Facebook(array(
'appId' => $appid,
'secret' => $appsecret,
'cookie' => false,
));
$user = $facebook->getUser();
if ($user)
{
try
{
$page_info = $facebook->api("/$pageId?fields=access_token");
if (!empty($page_info['access_token'])) {
$attachment = array(
'access_token' => $page_info['access_token'],
'message' => $msg,
'name' => $title,
'link' => $uri,
'description' => $desc,
'caption' => $caption,
'picture'=>$pic,
);
$status = $facebook->api("/$pageId/feed", "post", $attachment);
$msg="<h2 align='center'>Sucessfully Posted On Facebook Wall</h2>";
}
else
{
$status = 'No access token recieved';
}
}
catch (FacebookApiException $e)
{
error_log($e);
$user = null;
}
}
else
{
header("Location:{$facebook->getLoginUrl(array('scope' =>
'photo_upload,user_status,publish_stream,user_photos,manage_pages'))}");
}
?>

facebook app wont ask for extended permissions when validating

Have been trying for weeks, but my App won't ask for extended permissions, obviously that means that it wont POST to the timeline afterwards either.
require_once('/wp-content/php-sdk/src/facebook.php');
$facebook = new Facebook(array(
'appId' => 'xxxxxx',
'secret' => 'xxxxxxx',
));
$user = $facebook->getUser();
if ($userID) {
try {
// Proceed knowing you have a logged in user who's authenticated.
$ret_obj = $facebook->api('/me/feed', 'POST',
array(
'link' => 'www.theaandrdepartment.com/raw',
'message' => 'I just helped an Aussie band make it to
radio play! By voting, you can too.'
));
echo '<pre>Post ID: ' . $ret_obj['id'] . '</pre>';
} catch (FacebookApiException $e) {
error_log($e);
$user = null;
}
} else { $login_url = $facebook->getLoginUrl(array(
'scope' => 'publish_stream'
));
header("Location: ".$login_url);
}
If anyone could help that would amazing.
I copied most of this code straight from the Facebook example, but to no avail.

Error 100 schedule a post on Facebook Page

I've used the following code. It works fine without 'scheduled_publish_time', otherwise I get this error "(#100) You cannot specify a scheduled publish time on a published post".
I've previously registered my app with another piece of code. It's so weird.
include_once("inc/facebook.php"); //include facebook SDK
$appId = '21xxxxxxxxxxx'; //Facebook App ID
$appSecret = '6b8f4bxxxxxxxxxxxxxd56'; // Facebook App Secret
$return_url = 'http://localhost:8888/...'; //return url (url to script)
$homeurl = 'http://localhost:8888/...'; //return to home
$fbPermissions = 'publish_stream,manage_pages'; //Required facebook permissions
//Call Facebook API
$facebook = new Facebook(array(
'appId' => $appId,
'secret' => $appSecret,
'cookie' => true,
'fileUpload' => true
));
$accounts = $facebook->api('/me/accounts');
$PAGE_ID = get_option('fb_post_cron_page'); // it is an option saved in WordPress
foreach($accounts['data'] as $account){
if($account['id'] == $PAGE_ID){
$ACCESS_TOKEN = $account['access_token'];
}
}
$post_url = '/'.$PAGE_ID.'/photos';
$upload_dir = wp_upload_dir();
$upload_dir= $upload_dir['path'];
$timezone= 'Europe/Rome';
$date = new DateTime($dateStr, new DateTimeZone($timezone));
//posts message on page statues
$args = array(
'access_token' => $ACCESS_TOKEN,
'source' => '#' . $image_abs_path,
'message' => $post_message,
'published' => true,
'scheduled_publish_time' => $date->getTimestamp()
);
try {
$postResult = $facebook->api($post_url, 'post', $args );
} catch (FacebookApiException $e) {
echo $e->getMessage();
}
you have to set 'published' to false
$args = array(
'access_token' => $ACCESS_TOKEN,
'source' => '#' . $image_abs_path,
'message' => $post_message,
'published' => false,
'scheduled_publish_time' => $date->getTimestamp()
);

Facebook API offline access

I have a script I'd like to run via a cron job:
<?
require_once 'fb_access.php';
$user = $facebook->getUser();
if ($user) {
try {
$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' => 'This is the message',
'link' => 'http://thisisthelink',
'caption' => 'This is the caption',
'description' => 'This is the description',
);
$post_id = $facebook->api("/$page_id/feed","post",$args);
}
} catch (FacebookApiException $e) {
error_log($e);
$user = null;
}
}
?>
However when I try to run it via the cron job, it doesn't work. I've figured out this has something to do with the offline_access token. But from what I've read, a user must manually login to get the token. As I'd like to run this via a cron job, that's not feasible. Any ideas?
UPDATE:
I tried this; is it completely wrong?
require_once 'fb_access.php';
$user = $facebook->getUser();
$token = $facebook->getAccessToken();
if ($user) {
try {
$page_id = '**********';
$args = array(
'access_token' => $token,
'message' => 'This is the message',
'link' => 'http://thisisthelink',
'caption' => 'This is the caption',
'description' => 'This is the description',
);
$post_id = $facebook->api("/$page_id/feed","post",$args);
}
catch (FacebookApiException $e) {
error_log($e);
$user = null;
}
}
UPDATE #2:
<?php
require_once 'fb_access.php';
$user = $facebook->getUser();
$token = '*******LONG_ACCESS_TOKEN*******';
$page_id = '**********';
$args = array(
'access_token' => $token,
'message' => 'This is the message',
'link' => 'http://www.thisisthelink.com',
'caption' => 'This is the caption',
'description' => 'This is the description',
);
$post_id = $facebook->api("/$page_id/feed","post",$args);
?>
Using this I get: Fatal error: Uncaught OAuthException: (#200) The user hasn't authorized the application to perform this action thrown in /base_facebook.php on line 1106
First of all, you do not need offline_access, if you're requiring publish_stream permission.
You need manage_pages permission if you want to login/manage/share as your page.
You need user access token in order to get page access token. You need to authenticate once manually
header("Location: $facebook->getLoginUrl(array("scope" => "publish_stream,manage_pages")));
After you get an access token, save it to the persistent place (file, for example)
When in need, get the access token from your file and use it (just add access_token to your arguments)
Following code worked to me:
<?php
include(dirname(__FILE__)."/fb/facebook.php");
define('PAGE_ID', '123456498798');
$facebook = new Facebook(array(
'appId' => '178645249555182',
'secret' => 'csdf64sd65f4sd6f54f1c',
));
$a = array(
'access_token' => 'werf564s6d1cr98f965d6gf49w8sd49f87w9ed5c16d5f49s8f74w9e8rf74',
'message' => 'This is the message',
'caption' => 'This is the caption',
'description' => 'This is the description'
);
print_r($facebook->api('/'.PAGE_ID.'/feed', 'post', $a));
If it's a cron job, there's no-one there to do authorization with. You cannot do what you want. You'll need to look for an alternative.
An alternative like taking a valid auth token from one of the page admins that you've requested the extended token for (offline_access is being quickly deprecated see https://developers.facebook.com/docs/offline-access-deprecation/).
This 60 day token will need to be put into some config that the cron job can access.
You will need to manually update the 60 day token every couple of months.
You can get valid access tokens from the https://developers.facebook.com/tools/explorer.

How to on Facebook wall using Graph API

I have developed an application for facebook. I want that whenever any user add my application by clicking on allow permission dialog, a message is automatically posted on the users wall only for the first time.
<?php
include_once 'fb_sdk_212/src/facebook.php';
include_once 'config.php';
$flag_post=0;
$facebook = new Facebook(array(
'appId' => FACEBOOK_APP_ID,
'secret' => FACEBOOK_SECRET_KEY,
'cookie' => true,
'domain' => 'xxxxx.in'
));
$session = $facebook->getSession();
if (!$session) {
$flag_post=1;
$url = $facebook->getLoginUrl(array(
'canvas' => 1,
'fbconnect' => 0,
'req_perms' => 'email,user_birthday,status_update,publish_stream'
));
echo "<script type='text/javascript'>top.location.href = '$url';</script>";
} else {
try {
$uid = $facebook->getUser();
$me = $facebook->api('/me');
$updated = date("l, F j, Y", strtotime($me['updated_time']));
echo "Hello " . $me['name'] . "<br />";
echo "You last updated your profile on " . $updated."<br/>";
if($flag_post == 1){
# let's check if the user has granted access to posting in the wall
$api_call = array(
'method' => 'users.hasAppPermission',
'uid' => $uid,
'ext_perm' => 'publish_stream'
);
$can_post = $facebook->api($api_call);
echo $can_post;
$attachment = array(
'name' => 'Tracer',
'description' => 'xxxx',
'caption' => 'xxxxx',
'picture' => 'images/mt75.jpg',
'link' => 'tracer/'
);
if($can_post){
# post it!
$facebook->api('/'.$uid.'/feed', 'post', $attachment );
echo 'posted';
} else {
die('Permissions required!');
}
}
} catch (FacebookApiException $e) {
echo "Error:" . print_r($e, true);
}
}
?>
Well you need to get publish_stream extended permission.
http://developers.facebook.com/docs/authentication/permissions
This can be done in the permission dialog
http://developers.facebook.com/docs/reference/javascript/FB.login
by adding publish_stream to the perms list.
After that you will be able to publish to the user's wall at any time.
I would do one of the following:
Add a field in a database table to indicate that it has been done. Then just check if it has been set. If cookies are enabled on the users PC you could use but using a database would be best.
Get the user to take an action to do the post. So it requires a user action. This has the disadvantage that some users may not do it.
I feel like you can handle this fairly easily without Facebook being involved in decision to publish to the users wall or not. In your database's user table you should have a column for first_fb_post. When a user account is created it should default to 0, then once you publish the wall post it should be updated to 1.
And your facebook publish function would be set like:
if($first_fb_post == 0)
{
//your FB publishing code here
//update your user table to mark this users first_fb_post to 1
}
You could hook into the first time the user "installs" your app. When they do this they are redirected to your site with a get parameter of 'code' set in the url:
if(isset($_GET['code'])){
// User Authorized app. Lets hook the install event.
if($can_post){
# post it!
$facebook->api('/'.$uid.'/feed', 'post', $attachment );
echo 'posted';
} else {
die('Permissions required!');
}
}