I am trying to write a script that will post to my facebook page and I assume all I have to do is modify my code for posting to a users stream.
$attachment = array
(
...
);
$result = $facebook->api($user.'/feed/','post',$attachment开发者_Python百科);
What do I put instead of the user's id? I am not sure if it is simply my page's id. Any ideas?
Assuming that my facebook page means my feed you simply do
$user = 'me';
1. POST ON PAGE'S WALL AS USER:
Publishing on a Page's wall as user is straight forward, you could use something like:
<?php
// path to sdk
require './src/facebook.php';
$facebook = new Facebook(array(
'appId' => 'APP_ID',
'secret' => 'APP_SECRET',
));
$user = $facebook->getUser();
try {
$post_id = $facebook->api('/TARGET_PAGE_ID/feed', 'POST', array('message'=>"I am a user!"));
var_dump($post_id);
} catch (FacebookApiException $e) {
error_log($e);
$user = null;
}
if ($user) {
$logoutUrl = $facebook->getLogoutUrl();
} else {
$loginUrl = $facebook->getLoginUrl(array('scope'=>'publish_stream'));
}
// rest of code here
Note:
- The owner of the post will be the current connected user.
- the above depends on the page's Posting Ability settings.
- you need the
publish_stream
permission
2. POST ON PAGE'S WALL AS PAGE:
Now to post as a Page you could use something like:
<?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 = 'TARGET_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'));
}
// rest of code
?>
Notes:
- You need the
manage_pages
andpublish_stream
permissions - Once you obtain the page's
access_token
you can start posting on its behalf - More about this is explained in depth in my tutorial.
精彩评论