17

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);
Kara
  • 6,115
  • 16
  • 50
  • 57
diggersworld
  • 12,770
  • 24
  • 84
  • 119
  • Did you know that you can pass an array to `CURLOPT_POSTFIELDS`? No need to build a query string and escape stuff on your own. -- Oh, and the `endforeach;` syntax looks horrible ;x – ThiefMaster Mar 04 '11 at 08:24
  • I didn't at the time, but I do now. :) – diggersworld Mar 07 '11 at 12:58
  • [Here this process is described in details.](http://www.sergiy.ca/post-on-facebook-app-wall-and-fan-page-wall-as-admin/) – serg Sep 02 '10 at 15:11

7 Answers7

17

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:
enter image description here

More in my tutorial

sakibmoon
  • 2,026
  • 3
  • 22
  • 32
ifaour
  • 38,035
  • 12
  • 72
  • 79
  • 1
    i seem to be having problems with this line `$page_info = $facebook->api("/$page_id?fields=access_token");` anything i place after that doesnt execute. this works, but obviously it would not post as page `$page_info = $facebook->api("/me");` – t q Jul 11 '12 at 13:16
  • 2
    Thanks, I've been searching for hours for a simple working code like this one. –  Mar 27 '13 at 13:23
9

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

Peter Bailey
  • 105,256
  • 31
  • 182
  • 206
  • When using the Graph API I can only set the following parameters: message, picture, link, name, caption, description, source. There doesn't appear to be an option for the ID of sender. http://developers.facebook.com/docs/reference/api/post – diggersworld Sep 02 '10 at 14:53
  • I think it gets user ID from the access_token. But because I am admin of the page I would expect Facebook to recognise that. Doesn't seem to though. – diggersworld Sep 02 '10 at 14:55
  • I did try specifying the pages ID as the UID and nothing happened. Anyway... it appears from your link that I was missing the manage_pages permission, so I'm going to try that now. – diggersworld Sep 02 '10 at 15:18
  • Okay... I have allowed permissions for manage_pages and can now see my pages in the accounts. However it still posts as if I'm commenting from my personal profile rather than as an admin, added my code above. – diggersworld Sep 02 '10 at 15:42
1

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

Max
  • 519
  • 1
  • 7
  • 14
1

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(); 
}
achasinh
  • 530
  • 8
  • 17
1

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.

sakibmoon
  • 2,026
  • 3
  • 22
  • 32
1

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);
sakibmoon
  • 2,026
  • 3
  • 22
  • 32
skepticNeophyte
  • 399
  • 4
  • 8
1

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.

Adam
  • 1,080
  • 1
  • 9
  • 17