Posting to a Facebook wall using the Graph API

First, instantiate a new Facebook object. Nothing exciting here:

require '../src/facebook.php';
 
$facebook = new Facebook(array(
  'appId'  => '..............',
  'secret' => '..........................',
));

As of PHP SDK version 3.0.0 you shouldn’t use getSession() to verify a user’s connectivity. Instead use getUser() directly:

$user = $facebook->getUser();

Offer a login screen when the user is not connected. You may want to read through Facebook’s new OAuth 2.0 authentication protocol, but you should be aware that the entire process can be handled over the API. Simply add the required permissions to the ‘scope’ (not ‘req_perms’) parameter of getLoginUrl():

if (!$user) {
    $url = $facebook->getLoginUrl(array(
        'canvas' => 1,
        'fbconnect' => 0,
        'scope' => 'publish_stream'
    ));
    echo "<script type='text/javascript'>top.location.href = '$url';</script>";
} else {
    <execute your app code here>

The Graph API can be used to post a status update:

    $postarray = array('message' => 'Status update');
    $statusUpdate = $facebook->api('/me/feed', 'post', $postarray);

Use the legacy REST API to post more than a status update, an ‘attachment’ (a picture should be up to 90 pixels in both height and width):

    $attachment = array(
       'name' => 'Your title',
       'caption' => 'Your subtitle',
       'description' => 'yaddah, yaddah',
       'media' => array(array(
          'type' => 'image',
          'src' => "$appurl/picture.jpg",
          'href' => 'http://pygmalion.nitri.de/'
       ))
    );
    $facebook->api(array(
       'method' => 'stream.publish',
       'target_id' => $user,
       'attachment' => $attachment
    ));

If you want a popup, so the user can skip the post or add a message, use de JavaScript API. The method should be ‘stream.publish’, not ‘feed’. Be sure to include the empty div section:

    <div id="fb-root"></div>
    <script src="http://connect.facebook.net/en_US/all.js"></script>
    <script>
    FB.init({
              appId  : '<?php echo $appapikey; ?&gt',
              status : true, // check login status
              cookie : true, // enable cookies to allow the server to access the session
              xfbml  : true  // parse XFBML
            });
 
    FB.ui(
  {
    method: 'stream.publish',
    attachment: {
      name: 'JSSDK',
      caption: 'The Facebook JavaScript SDK',
      description: (
        'A small JavaScript library that allows you to harness ' +
        'the power of Facebook, bringing the user\'s identity, ' +
        'social graph and distribution power to your site.'
      ),
      href: 'http://fbrell.com/'
    },
    action_links: [
      { text: 'fbrell', href: 'http://fbrell.com/' }
    ]
  },
  function(response) {
    if (response && response.post_id) {
      alert('Post was published.');
    } else {
      alert('Post was not published.');
    }
  }
);
    </script>

Leave a Reply