Facebook API offline access - facebook

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.

Related

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.

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

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! :-)

Uncaught OAuthException: (#200) The user hasn't authorized the application to perform this action

I'm trying to post to my facebook group wall but I keep on getting the above error. Can anyone please tell me what I might be doing wrong here? I have checked the Facebook documentation but I still can't seem to fix it myself. My code is as follows:
$facebook = new Facebook(array(
'appId' => $app_id,
'secret' => $app_secret,
'perms' => 'offline_access, user_groups, publish_stream',
'cookie' => true
));
$result = $facebook->api(
'/xxxxxxxxxgroupid/feed/',
'post',
array('access_token' => $facebook->getAccessToken(), 'message' => 'Playing around with FB Graph..')
);
I think you need user_groups extended permission.
Use Try before, that sould work fine
try {
$params = array(
'message' => "Hurray! This works :)",
'name' => "This is my title",
'caption' => "My Caption",
'description' => "Some Description...",
'link' => "http://stackoverflow.com",
'picture' => "http://i.imgur.com/VUBz8.png",
);
$post = $facebook->api("/$user/feed","POST",$params);
echo "Your post was successfully posted to UID: $user";
}
catch (FacebookApiException $e) {
$result = $e->getResult();
}

Facebook OAuthException: Error validating application

I have a simple PHP page that is going to be used to post a message to my own wall.
I've obtained an offline_access token that has "read_stream" and "publish_stream" permissions.
define('FB_APIKEY', 'MY_APP_KEY');
define('FB_SECRET', 'MY_APP_SECRET');
define('FB_SESSION', 'MY_OFFLINE_TOKEN');
require_once('facebook.php');
try {
$facebook = new Facebook(FB_APIKEY, FB_SECRET);
$facebook->api_client->session_key = FB_SESSION;
$attachment = array(
'message' => 'some meesgae',
'name' => 'This is my demo Facebook application!',
'caption' => "Caption of the Post",
'link' => 'mylink.com',
'description' => 'this is a description',
'actions' => array(array(
'name' => 'Get Search',
'link' => 'google.com'
))
);
$result = $facebook->api('/me/feed?access_token=' . FB_SESSION,
'post',
$attachment);
var_dump($result);
} catch(Exception $e) {
echo $e;
}
When I run this, I get "OAuthException: Error validating application".
I confirmed that my offline token is good. When I go to https://graph.facebook.com/me?access_token=[MY_OFFLINE_TOKEN], it returns my public profile in JSON format correctly.
So, I'm thinking I'm doing something wrong with the API call somewhere but for the life of me I can't seem to figure it out. I've been wrestling with this issue for the last two days. Could someone please help! :(
You don't have APP ID here. And make calls like this:
require_once('facebook.php');
$facebook = new Facebook( array(
'appId' => 'APP_ID',
'secret' => 'APP_SECRET',
'cookie' => true
));
try {
$attachment = array(
'message' => 'some meesgae',
'name' => 'This is my demo Facebook application!',
'caption' => "Caption of the Post",
'link' => 'mylink.com',
'description' => 'this is a description',
'actions' => array(array(
'name' => 'Get Search',
'link' => 'google.com'
))
);
$attachment['access_token'] = $offline_access_token; // add it to the array
$result = $facebook->api('/me/feed', 'POST', $attachment );
var_dump($result);
} catch(Exception $e) {
// error_log( $e ); // should use something like this when in production
echo $e;
}
Untested, but should work. Let me know if it doesn't.

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!');
}
}