I've setup a script which allows users to post messages to a fan page on Facebook. It all works but there's one small issue.
The Problem:
When the post is added to the page feed it displays the posting user's personal account.
I would prefer it to show the account of the page (like when you're admin of the page it says it came from that page). The account I'm posting with have admin rights to the page, but it still shows as a personal post.
HTTP POST
$url = "https://graph.facebook.com/PAGE_ID/feed";
$fields = array (
'message' => urlencode('Hello World'),
'access_token' => urlencode($access_token)
);
$fields_string = "";
foreach ($fields as $key => $value):
$fields_string .= $key . '=' . $value . '&';
endforeach;
rtrim($fields_string, '&');
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, count($fields));
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string);
$result = curl_exec($ch);
curl_close($ch);
To post as Page not as User, you need the following:
Permissions:
publish_stream
manage_pages
Requirements:
The page id and access_token (can be obtained since we got the required permissions above)
The current user to be an admin (to be able to retrieve the page's access_token)
An access_token with long-lived expiration time of one of the admins if you want to do this offline (from a background script)
PHP-SDK Example:
<?php
/**
* Edit the Page ID you are targeting
* And the message for your fans!
*/
$page_id = 'PAGE_ID';
$message = "I'm a Page!";
/**
* 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_info = $facebook->api("/$page_id?fields=access_token");
if( !empty($page_info['access_token']) ) {
$args = array(
'access_token' => $page_info['access_token'],
'message' => $message
);
$post_id = $facebook->api("/$page_id/feed","post",$args);
} else {
$permissions = $facebook->api("/me/permissions");
if( !array_key_exists('publish_stream', $permissions['data'][0]) ||
!array_key_exists('manage_pages', $permissions['data'][0])) {
// We don't have one of the permissions
// Alert the admin or ask for the permission!
header( "Location: " . $facebook->getLoginUrl(array("scope" => "publish_stream, manage_pages")) );
}
}
} 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'));
}
// ... rest of your code
?>
Here the connected $user is supposed to be the admin.
Result:
More in my tutorial
As far as I know, all you have to do is specify a uid (that is, the page's ID) in your call to stream.publish
EDIT
Have a look at impersonation
Because the is the only relevant posting in the google results for "facebook graph won't post to page as page" I want to make a note of the solution I found. You need an access token with manage_pages permissions. Then call
https://graph.facebook.com/<user_id>/accounts?access_token=<access_token>
This will list all the pages the user has access to and will provide the access tokens for each. You can then use those tokens to post as the page.
The Graph API expects the parameter page_id (The Object ID of the Fan Page) to be passed in as an argument to API calls to get the events posted in a Fanpage wall. Not mentioned anywhere in the official Graph API documentation, but it works. I have tested it successfully with the Official PHP SDK v3.0.1
The required application permissions would be create_event and manage_pages
An Example would look something like this:
//Facebook/Fan Page Id
$page_id = '18020xxxxxxxxxx';
//Event Start Time
$next_month = time() + (30 * 24 * 60 * 60);
//Event Paramaeters
$params = array(
'page_id' => $page_id, // **IMPORTANT**
'name' => 'Test Event Name',
'description' => 'This is the test event description. Check out the link for more info: http://yoursite.com',
'location' => 'Kottayam, Kerala, India',
'start_time' => $next_month
);
$create_event = $facebook->api("/$page_id/events", "post", $params);
The answer lies with acquiring a permission of "manage_pages" on the FB:login button, like so:
<fb:login-button perms="publish_stream,manage_pages" autologoutlink="true"></fb:login-button>`
When you get those permissions, you can then get a structured list back of all the pages the logged-in user is an Admin of. The URL to call for that is:
https://graph.facebook.com/me/accounts?access_token=YourAccessToken
I HATE the Facebook documentation, but here is a page with some of the information on it: https://developers.facebook.com/docs/reference/api/
See the 'Authorization' and 'Page Login' sections in particular on that page.
A great resource to put all of this together (for Coldfusion Developers) is Jeff Gladnick's CFC on RIA Forge: http://facebookgraph.riaforge.org/
I added the following UDF to Jeff's CFC if you care to use it:
<cffunction name="getPageLogins" access="public" output="true" returntype="any" hint="gets a user's associated pages they manage so they can log in as that page and post">
<cfset var profile = "" />
<cfhttp url="https://graph.facebook.com/me/accounts?access_token=#getAccessToken()#" result="accounts" />
<cfif IsJSON(accounts.filecontent)>
<cfreturn DeserializeJSON(accounts.filecontent) />
<cfelse>
<cfreturn 0/>
</cfif>
</cffunction>
What this returns is a structure of all the pages the logged-in user is an Admin of. It returns the page NAME, ID, ACCESS_TOKEN and CATEGORY (not needed in this context).
So, VERY IMPORTANT: The ID is what you pass to set what page you are posting TO, and the ACCESS_TOKEN is what you pass to set who you are POSTING AS.
Once you have the list of pages, you can parse the data to get a three-element array with:
ID - ACCESS_TOKEN - NAME
Be careful though, because the Facebook ACCESS_TOKEN does use some weird characters.
Let me know if you need any additional help.
You must retrieve access_tokens for Pages and Applications that the user administrates.
The access tokens can be queried by calling /{user_id}/accounts via the Graph API.
More details:
https://developers.facebook.com/docs/facebook-login/permissions/v2.0 -> Reference -> Pages
This is how I do it with PHP SDK 4.0 and Graph API 2.3:
/**
* Posts a message, link or link+message on the page feed as a page entity
*
* #param FacebookSession $session (containing a page admin user access_token)
* #param string $pageId
* #param string $message - optional
* #param string $link - optional
*
* #return GraphObject
*/
function postPageAsPage( $session, $pageId, $message = '', $link = '' ){
// get the page token to make the post request
$pageToken = ( new FacebookRequest(
$session,
'GET',
"/$pageId" . "?fields=access_token"
))->execute()->getGraphObject();
return ( new FacebookRequest(
$session,
'POST',
"/$pageId/feed",
array(
'access_token' => $pageToken->getProperty( 'access_token' ),
'message' => $message,
'link' => $link,
)
))->execute()->getGraphObject();
}
Related
I would like to know if it's possible to login on Facebook api without a callback URL.
What I want to do is really "simple":
- Login on Facebook.
- Post or Delete on the wall.
- Logout of Facebook.
This is my code for login and post:
$fb = new Facebook\Facebook([
'app_id' => 'xxxx',
'app_secret' => 'xxxx',
'default_graph_version' => 'v2.5',
]);
$helper = $fb->getRedirectLoginHelper();
$permissions = ['publish_actions'];
$loginUrl = $helper->getLoginUrl(null, $permissions);
echo 'Log in with Facebook!';
try {
$accessToken = 'xxxx';
//$accessToken = $helper->getAccessToken();
//echo 'Log in with Facebook!';
$linkData = [
'link' => 'http://www.desarrollolibre.net/blog/tema/50/html/uso-basico-del-canvas',
'message' => $model->value,
];
$response = $fb->post('/feed', $linkData, $accessToken);
$graphNode = $response->getGraphNode();
The problem here is that I have to specify the access token getting directly from developers app, because $accessToken = $helper->getAccessToken() returns nothing to me.
Any help will be appreciate.
You can't "auto-login", you have to implement a proper login process. If you want to automate things (and you really should not autopost, because that is not allowed), you need to store a User Access Token somewhere and use it later. You may want to use an Extended User Token for this, because the default one is only valid for 2 hours. The Extended User Token is valid for 60 days.
More information about Tokens and how to generate them:
https://developers.facebook.com/docs/facebook-login/access-tokens
http://www.devils-heaven.com/facebook-access-tokens/
I'm generating a Login URL, which works great, but in my case the email permission is mandatory so I need to explain to the user and re-ask the email permission.
Here's how I'm generating the URL:
$fb = new Facebook\Facebook([
'app_id' => fbappid,
'app_secret' => fbappsecret,
'default_graph_version' => 'v2.2',
]);
$helper = $fb->getRedirectLoginHelper();
$permissions = ['email', 'user_birthday', 'user_location', 'user_hometown', 'user_relationships']; // Optional permissions
$loginUrl = $helper->getLoginUrl('http://localhost/urbanportal/wifilogin.php?origlink='.$_SESSION['origlink'].'&routerlink='.$_SESSION['routerlink'].'&siteid='.$_SESSION['siteid'], $permissions);
I read that you can pass a third parameter that says you're doing a re-request like so:
$loginUrl = $helper->getLoginUrl('http://localhost/urbanportal/wifilogin.php?origlink='.$_SESSION['origlink'].'&routerlink='.$_SESSION['routerlink'].'&siteid='.$_SESSION['siteid'], $permissions, true);
But I'm getting a "Length of param app_id must be less than or equal to 32" Facebook error, maybe that was for SDK 4.0?
The documentation always seems to navigate me to:
FB.login(
function(response) {
console.log(response);
},
{
scope: 'user_likes',
auth_type: 'rerequest'
}
);
But this is for Javascript SDK...
A quick look in the source code of the SDK reveals that there’s a dedicated method getReRequestUrl for that:
/**
* Returns the URL to send the user in order to login to Facebook with permission(s) to be re-asked.
*
* #param string $redirectUrl The URL Facebook should redirect users to after login.
* #param array $scope List of permissions to request during login.
* #param string $separator The separator to use in http_build_query().
*
* #return string
*/
public function getReRequestUrl($redirectUrl, array $scope = [], $separator = '&')
https://github.com/facebook/facebook-php-sdk-v4/blob/5.0-dev/src/Facebook/Helpers/FacebookRedirectLoginHelper.php#L202
I hope you are aware though that you will not get an email address for every FB user; f.i. they simply might not have one on file with Facebook, so even with the email permission you won’t get an email address.
I have used this code for auto post on my facebook fan page
<?php
// Requires Facebook PHP SDK 3.0.1: https://github.com/facebook/php-sdk/
require ('facebook.php');
define('FACEBOOK_APP_ID',"YOUR-APP-ID");
define('FACEBOOK_SECRET',"YOUR-APP-API-SECRET");
$user = null;
$facebook = new Facebook(array(
'appId' => FACEBOOK_APP_ID,
'secret' => FACEBOOK_SECRET,
'cookie' => true
));
$user = $facebook->getUser(); // Get the UID of the connected user, or 0 if the Facebook user is not connected.
if($user == 0) {
/**
* Get a Login URL for use with redirects. By default, full page redirect is
* assumed. If you are using the generated URL with a window.open() call in
* JavaScript, you can pass in display=popup as part of the $params.
*
* The parameters:
* - redirect_uri: the url to go to after a successful login
* - scope: comma separated list of requested extended perms
*/
$login_url = $facebook->getLoginUrl($params = array('scope' => "publish_stream"));
echo ("<script> top.location.href='".$login_url."'</script>");
} else {
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();
}
}
?>
But I need to post on my facebook fan page with my fan page name, this scrpit work so good but this code post on my fan page with my admin account and not like my fan page.
PLZ HELP ME :(
I think you need to take a look to this article carefully, I did it using the steps mentioned there.
Just put you token here:
https://graph.facebook.com/me/accounts?access_token=token
Then you will find the access token for posting as a page.
Hope that helps.
i am trying to post to my friends' feeds using this code, but it is not working . i am stuck, any help ??
$app_url ="http://localhost.local/PMS/facebook/PostWithPHP.php";
$facebook = new Facebook(array(
'appId' => 'APPID',
'secret' => 'APPSECRET',
'cookie' => true,
));
// Get User ID
$user = $facebook->getUser();
if ($user) {
$user_friends = $facebook->api('/me/friends');
sort($user_friends['data']);
try {
// Proceed knowing you have a logged in user who's authenticated.
$access_token = $facebook->getAccessToken();
$vars = array(
'message' => 'My Message',
'name' => 'title',
'caption' => 'Caption',
'link' => 'Link',
'description' => 'Description',
'picture' => 'image'
);
foreach($user_friends['data'] as $f){
$sendTo = $f['id'];
$sendToName = $f['name'];
$result = $facebook->api("/".$sendTo ."/feed", 'post', $vars);
}
} 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('redirect_uri'=> $app_url));
echo "<script type='text/javascript'>";
echo "top.location.href = '{$loginUrl}';";
echo "</script>";
}
and another question is that using this code, but with replacing $facebook->api("/".$sendTo ."/feed", 'post', $vars); by $facebook->api("/me/feed", 'post', $vars); and of course without looping friends, posts on my timeline. how can i make it post on my wall ??
I guess for a post to a timeline you will need an accessToken from the user where to publish the content. In your case you just have the accessToken of the registered user, not of his friends. That is a restriction by FB I think.
1st check you getting the user id(place echo and check) if not try this... I think this will help you brother
$token_url = "https://graph.facebook.com/oauth/access_token?" ."client_id=" . $app_id ."&client_secret=" . $app_secret .
"&grant_type=client_credentials";
$access_token = file_get_contents($token_url);
$signed_request = $_REQUEST["signed_request"];
list($encoded_sig, $payload) = explode('.', $signed_request, 2);
$data = json_decode(base64_decode(strtr($payload, '-_', '+/')), true);
$user_id = $data["user_id"];
There are a few things wrong with your code. First of all, make sure the link and picture parameters for the post are valid URLs. Facebook will give you a error message otherwise ((#100) link URL is not properly formatted). Also, the link must go to the Canvas or Site URL for your application.
That should solve the issues with posting to a friend's wall.
However, may I remind you that your application is in violation of the Facebook Platform Policy. Facebook doesn't allow multiple posts to the stream (whether its yours or a friends) unless there is explicit permission from the user. It also to stop common friends seeing the same message from multiple friends.
You can follow the tutorial here:
https://www.webniraj.com/2012/11/22/facebook-api-posting-a-status-update/
But, instead of making a API call to: /me/feed, you replace me with the friend's User ID, so it looks like /12345/feed
Please note that Facebook has now disabled posting to Friends' walls via the API. Instead, you should either tag the user in an action or use the Requests API.
I have a blog site written in php and it posts new blog posts to twitter and a blog ping automatically under the hood using simple http post requests passed using php curl.
I have a facebook page for the blog site and want the updates to be posted to the wall on the page, is there a simple way to do this?
What I really want is a url and set of params to parcel up as an http post request.
Note that this is to post to the wall on a new style page not a profile.
Get PHP SDK from github and run the following code:
<?php
$attachment = array(
'message' => 'this is my message',
'name' => 'This is my demo Facebook application!',
'caption' => "Caption of the Post",
'link' => 'http://mylink.com',
'description' => 'this is a description',
'picture' => 'http://mysite.com/pic.gif',
'actions' => array(
array(
'name' => 'Get Search',
'link' => 'http://www.google.com'
)
)
);
$result = $facebook->api('/me/feed/', 'post', $attachment);
the above code will Post the message on to your wall... and if you want to post onto your friends or others wall then replace me with the Facebook User Id of that user..for further information look out the API Documentation.
This works for me:
try {
$statusUpdate = $facebook->api('/me/feed', 'post',
array('name'=>'My APP on Facebook','message'=> 'I am here working',
'privacy'=> array('value'=>'CUSTOM','friends'=>'SELF'),
'description'=>'testing my description',
'picture'=>'https://fbcdn-photos-a.akamaihd.net/mypicture.gif',
'caption'=>'apps.facebook.com/myapp','link'=>'http://apps.facebook.com/myapp'));
} catch (FacebookApiException $e) {
d($e);
}
Harish has the answer here - except you need to request manage_pages permission when authenticating and then using the page-id instead of me when posting....
$result = $facebook->api('page-id/feed/','post',$attachment);
You can not post to Facebook walls automatically without creating an application and using the templated feed publisher as Frank pointed out.
The only thing you can do is use the 'share' widgets that they provide, which require user interaction.
If your blog outputs an RSS feed you can use Facebook's "RSS Graffiti" application to post that feed to your wall in Facebook. There are other RSS Facebook apps as well; just search "Facebook for RSS apps"...
You can make api calls by choosing the HTTP method and setting optional parameters:
$facebook->api('/me/feed/', 'post', array(
'message' => 'I want to display this message on my wall'
));
Submit Post to Facebook Wall :
Include the fbConfig.php file to connect Facebook API and get the
access token.
Post message, name, link, description, and the picture will be submitted to Facebook wall.
Post submission status will be shown.
If FB access token ($accessToken) is not available, the Facebook Login
URL will be generated and the user would be redirected to the FB login
page.
Post to facebook wall php sdk
<?php
//Include FB config file
require_once 'fbConfig.php';
if(isset($accessToken)){
if(isset($_SESSION['facebook_access_token'])){
$fb->setDefaultAccessToken($_SESSION['facebook_access_token']);
}else{
// Put short-lived access token in session
$_SESSION['facebook_access_token'] = (string) $accessToken;
// OAuth 2.0 client handler helps to manage access tokens
$oAuth2Client = $fb->getOAuth2Client();
// Exchanges a short-lived access token for a long-lived one
$longLivedAccessToken = $oAuth2Client->getLongLivedAccessToken($_SESSION['facebook_access_token']);
$_SESSION['facebook_access_token'] = (string) $longLivedAccessToken;
// Set default access token to be used in script
$fb->setDefaultAccessToken($_SESSION['facebook_access_token']);
}
//FB post content
$message = 'Test message from CodexWorld.com website';
$title = 'Post From Website';
$link = 'http://www.codexworld.com/';
$description = 'CodexWorld is a programming blog.';
$picture = 'http://www.codexworld.com/wp-content/uploads/2015/12/www-codexworld-com-programming-blog.png';
$attachment = array(
'message' => $message,
'name' => $title,
'link' => $link,
'description' => $description,
'picture'=>$picture,
);
try{
//Post to Facebook
$fb->post('/me/feed', $attachment, $accessToken);
//Display post submission status
echo 'The post was submitted successfully to Facebook timeline.';
}catch(FacebookResponseException $e){
echo 'Graph returned an error: ' . $e->getMessage();
exit;
}catch(FacebookSDKException $e){
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}
}else{
//Get FB login URL
$fbLoginURL = $helper->getLoginUrl($redirectURL, $fbPermissions);
//Redirect to FB login
header("Location:".$fbLoginURL);
}
Refrences:
https://github.com/facebookarchive/facebook-php-sdk
https://developers.facebook.com/docs/pages/publishing/
https://developers.facebook.com/docs/php/gettingstarted
http://www.pontikis.net/blog/auto_post_on_facebook_with_php
https://www.codexworld.com/post-to-facebook-wall-from-website-php-sdk/