开发者

Facebook Graph Api - Posting to Fan Page as an Admin

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, CURLOP开发者_开发知识库T_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:

Facebook Graph Api - Posting to Fan Page as an Admin

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();	
}

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜