This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Facebook Graph Api - Posting to Fan Page as an Admin
I am trying to have a form on my site where I can submit a blog post and then send that same blog post to my page on facebook.
My page is: https://www.facebook.com/foreveraloneminecraft
I want it to post it as if I was logged in and manually posted (like all the other posts on there).
I have been searching all over the place and everything I find either never actually posts something or throws an error.
This is what I got so far after searching all over:
<?php
include('core/init.inc.php');
require_once('libs/parser.php'); // path to Recruiting Parsers' file
$parser = new parser; // start up Recruiting Parsers
if(isset($_POST['submit'], $_POST['user'], $_POST['title'], $_POST['body'])
{
//--- Facebook Posting ------
require_once('libs/facebook/facebook.php');
$appid = '286964398044671';
$appsecret = 'myappsecret';
$pageid = '215852885143861';
$token = 'mytoken';
// Create our Application instance (replace this with your appId and secret).
$facebook = new Facebook(array(
'appId' => $appid,
'secret' => $appsecret,
));
// Get the current access token
//$token = $facebook->getAccessToken();
//Information that makes up the facebook page post
$attachment = array(
'access_token' => $token,
'message' => $_POST['body'],
'link' => 'http://hgs1957.hostedd.com/news.php',
'picture' => 'http://hgs1957.hostedd.com/images/foreverAloneMCguy.png',
'name' => $_POST['title'],
'description'=> 'Latest news for foreveralonemc.com.'
);
//Try to post to the facebook page
try{
$res = $facebook->api('/'.$pageid.'/feed','POST',$attachment);
} catch (Exception $e){
echo $e->getMessage();
}
//Add the post to the sql database of posts
//add_post($_POST['user'], $_POST['title'], $_POST['body']);
//Redirect to news feed
header('Location: news.php');
die();
}
?>
I used the appsecret from the token is that I got when using https://developers.facebook.com/tools/explorer/ with the permissions: publish_stream, status_update, manage_pages, publish_actions, offline_access
After trying that it seems to post to the page wall but as me not as the page or admin.
Anyone know if this is just a bug or what I am doing wrong?
You should re-login to your app again to renew and store a new access token after it is expired.
I Hope This will help you.
Related
I am working on a module, where requirement is When Admin creates any new post on website or blog, then it should get post on its related Facebook Page also.
I want something like this. But its not working in my case.
Here is code
// require Facebook PHP SDK
// see: https://developers.facebook.com/docs/php/gettingstarted/
require_once("php-graph-sdk-5.5/src/Facebook/facebook.php");
require_once("php-graph-sdk-5.5/src/Facebook/autoload.php");
// initialize Facebook class using your own Facebook App credentials
// see: https://developers.facebook.com/docs/php/gettingstarted/#install
$config = array();
$config['app_id'] = 'myappud';
$config['app_secret'] = 'myappsecret';
$config['fileUpload'] = false; // optional
$fb = new \Facebook\Facebook($config);
// define your POST parameters (replace with your own values)
$params = array(
"access_token" => "myaccesstoek", // see: https://developers.facebook.com/docs/facebook-login/access-tokens/
"message" => "Here is a blog post about auto posting on Facebook using PHP #php #facebook",
"link" => "http://www.pontikis.net/blog/auto_post_on_facebook_with_php",
"picture" => "http://i.imgur.com/lHkOsiH.png",
"name" => "How to Auto Post on Facebook with PHP",
"caption" => "www.pontikis.net",
"description" => "Automatically post on Facebook with PHP using Facebook PHP SDK. How to create a Facebook app. Obtain and extend Facebook access tokens. Cron automation."
);
// post to Facebook
// see: https://developers.facebook.com/docs/reference/php/facebook-api/
try {
$ret = $fb->post('myfburl/feed', $params);
echo 'Successfully posted to Facebook';
}
catch(Exception $e) {
echo $e->getMessage();
}
It giving error as
An unknown error occurred
For more refer this link => http://www.pontikis.net/blog/auto_post_on_facebook_with_php
Help to figure it out where I m making mistake.
Updated :
<?php
// Include facebook class (make sure your path is correct)
use Facebook\Facebook;
require_once ("php-graph-sdk-5.5/src/Facebook/autoload.php");
require_once("php-graph-sdk-5.5/src/Facebook/Facebook.php");
// Create our Application instance (replace this with your appId and secret).
$facebook = new Facebook(array(
'app_id' => 'myappid',
'app_secret' => 'myappsecret',
'cookie' => true,
));
//$token is the access token from the URL above
$post = array('access_token' =>'myaccesstoken', 'message' => 'new test post - ' . date('Y-m-d'));
try{
$res = $facebook->post('myfburl/feed',$post);
print_r($res);
} catch (Exception $e){
echo $e->getMessage();
}
for posting to a page you would need a page token with the manage_pages and publish_pages permissions
Example :
https://www.facebook.com/dialog/oauth?client_id=yourClientId&redirect_uri=yourUri/&scope=manage_pages,publish_pages
I have been reading the Facebook documentation and I must be missing something, as I just cant understand how to get the access token for a page without actually logging in first. I am trying to create a PHP function using the PHP facebook API so that when I add new stories or tutorials on my site, my site's apps can then automatically post as the page a blurb about them on myy facebook page.
I have this function working but only when I get the access token from the Graph API Explorer, though the access tokens expire in about an hour. I can't seem to figure out how to programatically obtain the access_token for the page and query for a new one each time from within my PHP scripts so they don't expire and do not require user interaction.
function post_to_facebook($title, $message, $link, $picture) {
require '../facebook/src/facebook.php';
$page_token = 'xxx';
$page_id = 'xx';
$facebook = new Facebook(array(
'appId' => '<app_id>',
'secret' => '<app_secret>',
'cookie' => false,
));
$facebook->setAccessToken($page_token);
try {
$ret_obj = $facebook->api('/'.$page_id.'/feed', 'POST', array(
'caption' => $title,
'link' => $link,
'message' => $message,
'picture' => $picture
));
} catch(FacebookApiException $e) {
error_log($e->getType());
error_log($e->getMessage());
return false;
}
return true;
}
Can someone explain how I can go about retrieving the access token without manually having to look it up via graph api explorer or having a user login?
It's not possible.
The only correct (and legal) way to achieve the access token is with user interaction (through login process).
I'm trying to add a feature to my app that will post a status to a admin user's page timeline with the same detail as if they posted on Facebook.com. The main feature I am focusing on is the link sharing and thumbnail images, like when you paste a link into your status and it auto-detects a thumbnail image, gives you a nice link, description, etc. I have tireless read through other forums and the Graph API documents, and I keep running into problems with the post showing as the admin user, rather than the page. Here is my code:
$facebook = new Facebook(array(
'appId' => $appID,
'secret' => $appSecret,
));
$loginUrl = $facebook->getLoginUrl(array(
"scope" => 'publish_stream, read_insights, manage_pages, photo_upload, video_upload, create_note, manage_notifications'
));
$access_token = $facebook->getAccessToken();
$fbpost = array();
$fbpost['access_token'] = $access_token;
$fbpost['message'] = $message;
$fbpost['link'] = $link;
$fbpost['description'] = $description;
$fbpost['caption'] = $caption;
$fbpost['picture'] = $fbimg;
$status = $facebook->api('/'.$pageID.'/feed', 'POST', $fbpost);
var_dump($status);
When I only post the $fbpost['message'] it correctly posts the status as the page, but when I add ANYTHING else it shows the post as the authenticated admin user instead of the page. Very frustrating. Any ideas?
I keep running into problems with the post showing as the admin user, rather than the page.
Then get a page access token, not a user access token for the admin user …
Thanks to CBroe for providing a link to the Facebook docs on the page/app access token. After checking that out, I came up with this PHP (since there is no good documentation in the PHP SDK for getting a page access token):
$user_token = $facebook->getAccessToken();
$accounts = $facebook->api('/me/accounts?access_token='.$user_token);
$account_token = 0;
foreach ($accounts['data'] as $account) {
if ($account['id'] == $_SESSION['facebook']) {
$account_token = $account['access_token'];
}
}
if ($account_token) {
/// your page token code
} else {
echo 'You must be an admin on this page!';
}
I know that there are lot's of questons on this, but all seem to be needing a user to be logged in... I have been using code snippets from all possible tutorials, but none seem to work.
Here is the scenario:
I have a photo community running on PHP and I have a fan page on Facebook. When an image on the main site collects a certain amount of votes a function is triggered to post the image link to the Facebook wall. The link (post) is posted as a page and not as admin. Admin of course will not be online... Is this even possible to do these days? I have the latest PHP SDK and this is the function that I need to get working in stand alone mode before pluggin' into the main site.
OK. This code works perfectly if I am logged into the Facebook, but if I am not - it will not post... The App has all necessary and unnecessary :) permissions to interact with my page on my (admin) behalf. Any ideas will be appreciated.
<?php
//facebook application
$fbconfig['appid' ] = "1848740815xxxxx";
$fbconfig['secret'] = "a5aa62bb3a8ddcb98d5d9dbe4a3xxxxx";
$fbconfig['pageid'] = "121409594622865";
$user = null; //facebook user uid
try{
include_once "facebook.php";
}
catch(Exception $o){
error_log($o);
}
// Create our Application instance.
$facebook = new Facebook(array(
'appId' => $fbconfig['appid'],
'secret' => $fbconfig['secret']
));
//Facebook Authentication part
$user = $facebook->getUser();
$loginUrl = $facebook->getLoginUrl(
array(
'scope' => 'offline_access,publish_stream'
)
);
$logoutUrl = $facebook->getLogoutUrl();
$pageid = $fbconfig['pageid'];
if ($user) {
try {
$page_info = $facebook->api("/$pageid?fields=access_token");
if( !empty($page_info['access_token']) ) {
$args = array(
'access_token' => $page_info['access_token'],
'message' => 'This is a test feed message',
'link' => 'http://www.fotodvor.com',
'picture' => 'http://www.fotodvor.com/data/media/15/1319971991.jpg',
'name' => 'Test Picture',
'description'=> 'Description of the test picture!'
);
$post_id = $facebook->api("/$page_id/feed","post",$args);
}
} catch (FacebookApiException $e) {
error_log($e);
$user = null;
}
}
?>
Thanks in advance
here is a modified script with explanations adjusted for the changes in the API
<?php
//facebook application
$fbconfig['userid'] = "5332534xx";
$fbconfig['appid' ] = "184874081548xxx";
$fbconfig['secret'] = "a5aa62bb3a8xxxb98d5d9dbe4a368xxx";
$fbconfig['pageid'] = "121409594622xxx";
$fbconfig['token1'] = "AAACoJFn1eLABAKpL9W0nZBrw0e3zzdSNVsTg6FWDMhSnOUeinjid6yAQ2z9JDxxxxxxc1hMHBC3GG18KZBwppGDehWMEwLe56wagZDZD"; // step 1 - returned by loggin in.
$fbconfig['token2'] = "AAACoJFn1eLABAC2Q8OLnqxjUSKzdn9CzaXhy8nsG61vzp2ufePr5iwHZA7TM7Ibxxxxxxyf868O04FeBxMrIo0RCumrNaB78hZAp2uRrbVlGVPXP"; // step 3 - this is a page access token as page
$fbconfig['my_ulr'] = 'http://'.$_SERVER['SERVER_NAME'];
include_once "facebook.php";
// Create our Application instance.
$facebook = new Facebook(array(
'appId' => $fbconfig['appid'],
'secret' => $fbconfig['secret'],
));
// 1. we need to get a user access_token first, (old approach with offline_access forces the tokens received not to expire (good examples here - http://developers.facebook.com/docs/authentication2/ and http://www.howtobe.pro/tag/graph-api)
// run the file and see step 1 instructions.
//offline_access has been deprecated in May 2012 and therefore excluded from the request below
$token_url1 = "https://www.facebook.com/dialog/oauth?"."client_id=".$fbconfig['appid']."&redirect_uri=".urlencode($fbconfig['my_ulr'])."&scope=manage_pages,publish_stream&response_type=token";
echo "<h2>This little working example should give you a working non expiring token to use in your PHP script to enable it to post to your Facebook page as a page and not as a user</h2><br>";
echo "1 - Click on the link below (this redirects to uri with token attached). Log in as admin of the page you are trying to post to. Then copy the token you will get in the address bar to be used in the script in step 2.<br>";
echo "<a href='".$token_url1."' target='_blank'>$token_url1</a>";
//2. then paste the token you received into "step 1" variable in the config section above. Run this script again when logged in to receive all info.
$token_url2 = "https://graph.facebook.com/me?access_token=".$fbconfig['token1'];
$me = json_decode(file_get_contents($token_url2), true);
//echo "<hr><br>this URL gives you all pages that you as admin have access to, but these are NOT what we need to post to the fan page as PAGE so this is just for the heck of it...<br>";
//echo "<a href='".$token_url2."' target='_blank'>$token_url2</a>";
//echo "<hr>this is a raw server reply<br>";
//echo d($me['id'])."<hr>";
//new changes to API - https://developers.facebook.com/roadmap/offline-access-removal/#extend_token
$new_token_url2 = "https://graph.facebook.com/oauth/access_token?client_id=".$fbconfig['appid']."&client_secret=".$fbconfig['secret']."&grant_type=fb_exchange_token&fb_exchange_token=".$fbconfig['token1'];
$new_token2 = file_get_contents($new_token_url2);
$vars = explode('&', $new_token2);
//d($vars);
echo "2. We now obtain a long lasting token (based on <a href='https://developers.facebook.com/roadmap/offline-access-removal/#extend_token' target='_blank'>this</a>)
<br><br>We send the request<br>'".$new_token_url2."'<br><br>and the reply is:<br>'".$new_token2."'<br><br>";
//http://developers.facebook.com/tools/explorer?method=GET&path=533253476&accounts&access_token=AAACoJFn1eLABAFZBftV0vtlBiHKA7ZAIrukrriyp2coWSavj3L4CbfJ9r3WY76IPi7pwUgt3wsubaI4iBbsr663PrbNyaLdZAhLxneOLAZDZD
echo"So now open this page <a href='http://developers.facebook.com/tools/explorer' target='_blank'>http://developers.facebook.com/tools/explorer</a>,
then put the token above to put into the 'Access Token: ' field and press enter... You will need to press 'accounts' link to the right from the response window.
<br>you will see another response and copy your page access token from there. Automating this task into one query did not work... I tried many times.. the token returned IS NOT THE SAME as you would get following the instructions step by step...
This approach does not work - <br>";
echo "http://developers.facebook.com/tools/explorer?method=GET&path=".$me['id']."%2Faccounts&".$vars[0]."<BR><BR><BR>";
echo "Please check it here <a href='http://developers.facebook.com/tools/debug' target='_blank'>https://developers.facebook.com/tools/debug</a> and make sure it never expires...";
$pageid = $fbconfig['pageid'];
try {
//Step 3. Run this script WHEN LOGGED IN to and paste the resulting token into step 3 variable above to check the functionality
/* $page_info = $facebook->api("/$pageid?fields=access_token&".$new_token2); //wrong approach to use this straight. THIS is the access token is that we need. BUT this will work only if user is logged in. so
echo "<hr>this is a page_info breakdown";
d($page_info);
echo "and the access token you needs to paste into fbconfig['token2'] variable is this:<br>";
echo $page_info['access_token']; */
$args = array(
'access_token' => $fbconfig['token2'], //do not attempt to plug the $page_info['access_token'] here... it will be empty once you log off Facebook
'message' => 'This is a test feed message',
'link' => 'http://www.test.com',
'picture' => 'https://www.google.com/intl/en_com/images/srpr/logo3w.png',
'name' => 'Test Picture',
'description'=> 'Description of the test picture!'
);
//uncomment this once you are ready to post and you can see all the access token in the last step. Then comment out all echo and d()'s to make the script silent...
//$post_id = $facebook->api("/$pageid/feed","post",$args);
echo "<hr>This will show once the message is posted - post_id is: <br>";
d($post_id);
} catch (FacebookApiException $e) {
error_log($e);
}
function d($d){
echo '<pre>';
print_r($d);
echo '</pre>';
}
?>
I think I have found the answer. After a long time of testing here is the solution:
Treat this as a little sample/guide for those who are new to this.
The code and output has all necessary info:
<?php
//facebook application
$fbconfig['appid' ] = "184874081XXXXXX";
$fbconfig['secret'] = "a5aa62bb3a8ddcb98d5d9dbe4aXXXXXX";
$fbconfig['pageid'] = "121409594XXXXXX";
$fbconfig['token1'] = "AAACoJFn1eLABAHn92JsWIHZCESQWXmkXZBCedXXXXXXcyUG5vrCYZBXcgsNHN0IUvBj0Sec9vOxVsUgtMHflXXF2cbOF1oZD"; // step 1 - returned by loggin in.
$fbconfig['token2'] = "AAACoJFn1eLABAAUAPthH5DaZCmasZCh5DGGSnZXXXXXXSDh8v1WYYUEWJYuFdua9E5EfJ63c03lfwXrVJbP4VQj35aVcztFgKRYZAheHPNfDeLfbkPys"; // step 3 - this is a page access token as page
$fbconfig['my_ulr'] = 'http://'.$_SERVER['SERVER_NAME'];
include_once "facebook.php";
// Create our Application instance.
$facebook = new Facebook(array(
'appId' => $fbconfig['appid'],
'secret' => $fbconfig['secret'],
));
// 1. we need to get a user access_token first, offline_access forces the tokens received not to expire (good examples here - http://developers.facebook.com/docs/authentication2/ and http://www.howtobe.pro/tag/graph-api)
//run the file and see step 1 instructions.
$token_url1 = "https://www.facebook.com/dialog/oauth?"."client_id=".$fbconfig['appid']."&redirect_uri=".urlencode($fbconfig['my_ulr'])."&scope=manage_pages,offline_access,publish_stream&response_type=token";
echo "1 - this redirects to uri with token attached. Copy and paste this line into your browser and log in as admin of the page you are trying to post to. Make sure you change redirect_uri to your own. Then copy the token you will get in the address bar to be used in the script in step 2.<br>";
echo $token_url1;
//2. then paste the token you received into "step 1" variable in the config section above. Run this script again when logged in to receive all info.
$token_url2 = "https://graph.facebook.com/me/accounts?access_token=".$fbconfig['token1'];
$app_token2 = file_get_contents($token_url2);
echo "<hr><br>2 - this URL gives you all pages that you as admin have access to, but these are NOT what we need to post to the fan page as PAGE<br>";
echo $token_url2;
echo "<hr>2 - this is a raw server reply<br>";
d($app_token2);
$pageid = $fbconfig['pageid'];
try {
//Step 3. Run this script WHEN LOGGED IN to and paste the resulting token into step 3 variable above
$page_info = $facebook->api("/$pageid?fields=access_token"); //wrong approach to use this straight. THIS is the access token is that we need. BUT this will work only if user is logged in. so
echo "this is a page_info breakdown";
d($page_info);
echo "and the access token you needs to paste into fbconfig['token2'] variable is this:<br>";
echo $page_info['access_token'];
$args = array(
'access_token' => $fbconfig['token2'], //do not attempt to plug the $page_info['access_token'] here... it will be empty once you log off Facebook
'message' => 'This is a test feed message',
'link' => 'http://www.test.com',
'picture' => 'https://www.google.com/intl/en_com/images/srpr/logo3w.png',
'name' => 'Test Picture',
'description'=> 'Description of the test picture!'
);
//uncomment this once you are ready to post and you can see all the access token in the last step. Then comment out all echo and d()'s to make the script silent...
//$post_id = $facebook->api("/$pageid/feed","post",$args);
echo "<hr>This will show once the message is posted - post_id is: <br>";
d($post_id);
} catch (FacebookApiException $e) {
error_log($e);
}
function d($d){
echo '<pre>';
print_r($d);
echo '</pre>';
}
?>
You should be using the page access token if i'm understanding what you're trying to do correctly - this is a token which allows your app to act as the page, not as one of the admins.
This is accessible at the /me/accounts endpoint when you have a user access token with manage_pages permission - if you use that access token to post to /{page id}/feed (or photos, etc) it'll appear as the page
I have looked at the developers' page but there tons of tons stuff. Application authentication (will my PHP called app?), setting permissions, how to make post after authentication?, where to store authentication? etc etc and so on I wasn't able to get all what all they mean, and what is need in all that stuff.
I only want to make a wall post to the community/fan page's wall as community/fan page. What steps should my PHP application follow to make a wall post?
I've written an in-depth tutorial about this subject: How To: Post On Facebook Page As Page Not As Admin User Using PHP-SDK
In short:
You need at least the publish_stream and manage_pages permissions
Query your page object to get a page access token
And post!
A starting code from my tutorial:
<?php
// This code is just a snippet of the example.php script
// from the PHP-SDK <http://github.com/facebook/php-sdk/blob/master/examples/example.php>
require '../src/facebook.php';
// Create our Application instance (replace this with your appId and secret).
$facebook = new Facebook(array(
'appId' => 'app_id',
'secret' => 'app_secret',
));
// Get User ID
$user = $facebook->getUser();
if ($user) {
try {
$page_id = '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' => "I'm a Page!"
);
$post_id = $facebook->api("/$page_id/feed","post",$args);
}
} catch (FacebookApiException $e) {
error_log($e);
$user = null;
}
}
// Login or logout url will be needed depending on current user state.
if ($user) {
$logoutUrl = $facebook->getLogoutUrl();
} else {
$loginUrl = $facebook->getLoginUrl(array('scope'=>'manage_pages,publish_stream'));
}
?>
Note: you may need the offline_access if you want to post while you are not connected to Facebook (e.g.: from your CMS)