How to autopost to facebook page with app id - facebook

How to post to Facebook page with the App ID & Secret & Page ID without need to login with the user Admin of the page to get access token, the App owner who is the Admin of the page shouldn't be enough to auto post !?
I am using PHP & SDK4 of Facebook API.

You can´t post anywhere on Facebook without authorizing. If you want to post "as Page", you need to authorize a Page admin with the "publish_pages" permission and use a Page Token. You can´t get a User or Page Token without authorization, and of course you can´t automate the authorization process. Check out the docs for detailed information: https://developers.facebook.com/docs/graph-api/reference/v2.3/page/feed#publish
You will also need to learn about Access Tokens:
https://developers.facebook.com/docs/facebook-login/access-tokens
http://www.devils-heaven.com/facebook-access-tokens/

In fact all i wanted specifically to have permanent page access token so i can auto post forever without requiring authentication from the user each time for posting.
follow these steps to get it: Permanent Access Token
then use auto post code :
session_start();
define('FACEBOOK_SDK_V4_SRC_DIR', 'facebook-php-sdk-v4-4.0-dev/src/Facebook/');
require __DIR__ . '/facebook-php-sdk-v4-4.0-dev/autoload.php';
use Facebook\FacebookSession;
use Facebook\FacebookRequest;
use Facebook\GraphUser;
use Facebook\FacebookRequestException;
use Facebook\FacebookRedirectLoginHelper;
// Facebook App
$api_key = 'xxxxxxxxxxxxxxxx'; //App ID
$api_secret = 'xxxxxxxxxxxxxxxx'; //App Secret
$page_id = 'xxxxxxxxxxxxxxxx'; //Page ID
$page_token = 'from the steps in the url';
$fb_post = array(
'message'=> 'test message',
'name'=> '',
'link'=> 'http://www.example.com/',
'picture'=> 'http://www.example.com/image.jpg',
'caption'=> '',
);
// start a session for this App
FacebookSession::setDefaultApplication($api_key, $api_secret);
try {
$session = new FacebookSession($page_token);
} catch(FacebookRequestException $e) {
die(" Error : " . $e->getMessage());
} catch(\Exception $e) {
die(" Error : " . $e->getMessage());
}
try {
// Auto posting
$page_post = (new FacebookRequest( $session, 'POST', '/'. $page_id .'/feed', $fb_post))->execute()->getGraphObject()->asArray();
// return post_id, optional
print_r( $page_post );
} catch (FacebookRequestException $e) {
// The Graph API returned an error
echo '<b style="color:blue;">'.$e->getMessage().'</b>';
} catch (\Exception $e) {
// Some other error occurred
echo '<b style="color:red;">'.$e->getMessage().'</b>';
}

Related

Posting facebook api not as page

I've made facebook app, got appID and secret, and I am trying to post to a page as the page. I've granted the app permission.
But when I'm posting, new post creates "as user", not as page.
My code:
require '../lib/fb/autoload.php';
use Facebook\FacebookSession;
use Facebook\FacebookRequest;
use Facebook\GraphUser;
use Facebook\FacebookRequestException;
FacebookSession::setDefaultApplication('APP_ID','SECRET');
$session = new FacebookSession('ACCESS_TOKEN');
try {
$response = (new FacebookRequest(
$session, 'POST', '/1429642034012499/feed', array(
'message' => 'test',
'link' => 'http://mylink',
)
))->execute()->getGraphObject();
print_r($response);
} catch (FacebookRequestException $e) {
echo "Exception occured, code: " . $e->getCode();
echo " with message: " . $e->getMessage();
} catch (\Exception $e) {
}
Page to view.
This Answer is for C#, using the .NET Facebook API Library. But Logic should be same in PHP.
You have to get the Page Access Token:
Go Here: developers.facebook.com/tools/
Then Go to this Link:
Then Click on: "Get Access Token"
Then Add these Permissions:
Then Copy New access Token:
Now in C# Class I do (This is the POST A Comment as Page):
var userClient = new FacebookClient("THE NEW ACCESS TOKEN YOU JUST GENERATED");
dynamic accountInfo = userClient.Get("USER_ID" + "/accounts");
//USER_ID Should be Digits, this is the UserID when you do: facebook.com/USERID it should come up with the Admin Profile
var pageAccessToken = accountInfo.data[0].access_token;
var pageClient = new FacebookClient(pageAccessToken);
dynamic parameters = new ExpandoObject();
parameters.message = model.Message;
dynamic pageResult = pageClient.Post(string.Format("{0}/comments",), parameters);

Redirect to Index page when Facebook PHP SDK Access Token is Expired

I'm working on a site that uses the Facebook PHP SDK. It is working great, and after 2 hours, whenever I try to get onto one of the general pages on the site, I get...
Fatal error: Uncaught OAuthException: An active access token must be used to query information about the current user.
If I go back to the index page, I get a new access token and everything works properly again...for 2 hours.
What code can I put on my webpages to redirect to the index page when the access token has expired?
Thanks for helping this noob.
You must redirect user to page that has authorized code.
If your user not deauthorized app , the Oauth dialog isn't appear.
For more information go to
Access Token & Handling
You can put a try / catch block in your code.
Put each Facebook API call in such block and if an exception occurs you can redirect the user to the right resource by header('Location: <url>');:
try {
# FB API call
}
catch(OAuthException e) {
header('Location: <url>');
}
Have a file that goes like this and include it in your webpages.
$facebook = new Facebook(array(
'appId' => "app id",
'secret' => "app secret",
));
$user = $facebook->getUser();
$loginUrl = $facebook->getLoginUrl();
if ($user) {
try {
$me = $facebook->api('/me');
} catch (FacebookApiException $e) {
error_log($e);
}
}
else {
echo "<script type='text/javascript'>top.location.href = '$loginUrl';</script>";
}

CodeIgniter and Facebook Connect

I am trying to integrate my Codeigniter website with the Facebook PHP SDK. What I want to do is let a user share an article from my site on their facebook wall, if they are logged into a facebook account. My library appears to load correctly, but everytime I try to do something, I get some kind of error... primarily with the auth. getUser does not appear to return the correct results. I set up my facebook application and set the config vars for my library, but no luck. It says I am not logged into facebook. When I click on the "login" anchor, the link takes me to the same page, but with the facebook url, and doesn't ask me to login with the app. Here's my code:
function facebook($article_id){
$config = array(
'appId' => '276870792431073',
'secret' => '8d49eee575413fb9a8063d22f65dbf6a'
);
$this->load->library('facebook', $config);
$user = $this->facebook->getUser();
if($user){
try {
$user_profile = $this->facebook->api('/me');
} catch (FacebookApiException $e){
error_log($e);
$user = null;
}
}
if($user){
$article = $this->article->fetch_article($article_id);
$config = array(
'message' => 'I just read an '.anchor('articles/'.url_title($article['title']).'/'.$article_id, 'article').' on '.anchor('', 'TrackTheOutbreak.com').'!',
);
$this->facebook->api('/me/feed', 'post', $config);
} else {
$data['MESSAGE_TITLE'] = 'Authentication Error';
$data['MESSAGE_TEXT'] = 'You must be logged into an existing Facebook account to use this feature. Click '.anchor($this->facebook->getLoginUrl(), 'here').' to login.';
$this->parser->parse('error_body.tpl', $data);
}
}
In order to access a users information and post anything to their wall you first need to get a access token from them. To do that you need to make sure that you have gained their permission through Facebook's FB_login (and then Open Graph). I would double check with this guide and make sure that you have everything set up properly to post to their timeline.
https://developers.facebook.com/docs/reference/javascript/FB.login/
I hope this helps

How to publish photos on behalf of the user with application access token ? (not with user access token)

I want my application to publish photos, user has already registered my app with publish_stream permission and is currently disconnected from facebook.
Documentation https://developers.facebook.com/docs/publishing/ said :
To publish a 'photo' object you need
a valid access token
publish_stream permission
I tried a HTTP POST request :
https://graph.facebook.com/<USER_ID>/photos?access_token=<APPLICATION_ACCESS_TOKEN>
POST param : "url":"<link_to_some_picture>"
And i got an exception :
content={"error":{"message":"A user access token is required to request this resource.","type":"OAuthException","code":102}}
To publish photos on behalf of user i cannot pass a user access token... Why i can post links but not photos with my application access token?
Your title states that you are using an application access token - the error you are getting clearly states the problem. You need a user access token.
You'll need to extend your users access token in order to perform actions on his/her behalf when they are not connected to Facebook.
Here is a good resource for information about dealing with expired tokens and how to refresh them -
https://developers.facebook.com/docs/authentication/access-token-expiration/
When user registered your application then you can store the user's user access token after you can used that access token to post on behalf of user.When user come to your application next time you can update that access token.
You can use following function to get extended access token:
public function getExtendedAccessToken(){
try {
// need to circumvent json_decode by calling _oauthRequest
// directly, since response isn't JSON format.
$access_token_response =
$this->_oauthRequest(
$this->getUrl('graph', '/oauth/access_token'),
$params = array( 'client_id' => $this->getAppId(),
'client_secret' => $this->getApiSecret(),
'grant_type'=>'fb_exchange_token',
'fb_exchange_token'=>$this->getAccessToken(),
));
} catch (FacebookApiException $e) {
// most likely that user very recently revoked authorization.
// In any event, we don't have an access token, so say so.
return false;
}
if (empty($access_token_response)) {
return false;
}
$response_params = array();
parse_str($access_token_response, $response_params);
if (!isset($response_params['access_token'])) {
return false;
}
return $response_params['access_token'];
}
$fid = $row[1];
echo "fid = $fid\n";
$message =$row[2];
echo "msg = $message\n";
$friends = $facebook->api("/$user/friends?fields=id");
$args= array(
'app_id' => $facebook->getAppId(),
'to' => $fid,
'link' => 'http://www.facebook.com',
'message'=>$message,
);
$post_id = $facebook->api('/fid /feed', 'POST', $args);
var_dump($post_id);

How to avoid my this facebook app api login page?

I got a problem regrading with my apps which is once I go to my apps, it sure will show me a login page instead of allow page?
it always display the login page 1st then only display allow page, I had tried other apps, if I am 1st time user, It sure will appear the allow page only, it did not show me the login page.
my question is how to I avoid my login page direct go to allow page?
here is my login page picture
here is my apps link
https://apps.facebook.com/christmas_testing/
here is my facebook php jdk api coding
<?php
$fbconfig['appid' ] = "XXXXXXXXXXXXX";
$fbconfig['secret'] = "XXXXXXXXXXXXX";
$fbconfig['baseUrl'] = "myserverlink";
$fbconfig['appBaseUrl'] = "http://apps.facebook.com/christmas_testing/";
if (isset($_GET['code'])){
header("Location: " . $fbconfig['appBaseUrl']);
exit;
}
if (isset($_GET['request_ids'])){
//user comes from invitation
//track them if you need
header("Location: " . $fbconfig['appBaseUrl']);
}
$user = null; //facebook user uid
try{
include_once "facebook.php";
}
catch(Exception $o){
echo '<pre>';
print_r($o);
echo '</pre>';
}
// Create our Application instance.
$facebook = new Facebook(array(
'appId' => $fbconfig['appid'],
'secret' => $fbconfig['secret'],
'cookie' => true,
));
//Facebook Authentication part
$user = $facebook->getUser();
$loginUrl = $facebook->getLoginUrl(
array(
'scope' => 'email,publish_stream,user_birthday,user_location,user_work_history,user_about_me,user_hometown'
)
);
if ($user) {
try {
// Proceed knowing you have a logged in user who's authenticated.
$user_profile = $facebook->api('/me');
} catch (FacebookApiException $e) {
//you should use error_log($e); instead of printing the info on browser
d($e); // d is a debug function defined at the end of this file
$user = null;
}
}
if (!$user) {
echo "<script type='text/javascript'>top.location.href = '$loginUrl';</script>";
exit;
}
//get user basic description
$userInfo = $facebook->api("/$user");
function d($d){
echo '<pre>';
print_r($d);
echo '</pre>';
}
?>
This is an effect of the new auth dialog features facebook recently rolled out.
There are two "allow/login" screens when using this new dialog :
Regular permissions such as - user_about_me, user_birthday, user_photos.
Extended permissions such as - read_insights, offline_access, publish_actions.
Each will display its own dialog. First the regular permissions will appear and after that the extended permissions will appear (if you have requested extended permissions)... This happens when the user first logs in, and possibly later if you want decide to add additional permissions to your app.
Taken from the Open Graph Beta › Auth Dialog
The updated Auth Dialog will display a set of user and friends permissions on the first dialog, and other extended permissions (if any) on a second dialog screen.
You can disable this feature and go back to the older auth dialog by changing the setting inside your app. Goto the advanced tab in the settings of your app and uncheck the Enhanced Auth Dialog check-box.
On the scope parameter, add 'offline_access' permission. With this,the user grant permission to the application even if the user is offline. The access_token that you will get is non-expiry.