• support@answerspoint.com

How to post into a Facebook Page with PHP using Graph API..?

1165

I have a site made with PHP and when I submit a particular form in my admin area, I want to publish to my Facebook "fan page

how to publish post on Facebook page wall as page admin user using facebook php sdk v4 and graph api 2.x?

1Answer


0

n this post you will learn how to post to Facebook page wall (Not User Wall) using PHP and Facebook API. To understand this article you must have knowledge of Facebook application development and their API usage. Before we begin I assume you have created Facebook Application and you have a running Facebook Page where you want  your message to appear.  

Configuration

Config.php stores variables, such as facebook Application ID, secret, return url etc. Change these settings with your own. Notice include_once(“inc/facebook.php”); , inc folder contains Facebook PHP SDK files, which can be downloaded from https://github.com/facebook/php-sdk, but I have already included these files in downloadable zip file at the bottom of the page.

<?php
include_once("inc/facebook.php"); //include facebook SDK

######### edit details ##########
$appId = 'xxxxxxxxxxxxxx'; //Facebook App ID
$appSecret = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxx'; // Facebook App Secret
$return_url = 'http://yoursite.com/script/process.php';  //return url (url to script)
$homeurl = 'http://yoursite.com/script/';  //return to home
$fbPermissions = 'publish_stream,manage_pages';  //Required facebook permissions
##################################

//Call Facebook API
$facebook = new Facebook(array(
  'appId'  => $appId,
  'secret' => $appSecret
));

$fbuser = $facebook->getUser();
?>

Front Page

Index.php contains a message form for this demo, user is redirected to facebook authentication page, where s/he is required to authenticate and grant mainly two extended permissions publish_stream and manage_pages. It seems permission manage_pages is required to read user pages, and to post on page wall, application requires publish_stream.

Once user grants these permissions, user is redirected back to index page, where s/he is presented with a form containing a message input box and list of his own Facebook pages. You see, to list user pages, I have used FQL (Facebook Query Language), FQL is Facebook’s own query language and it is very similar to MySQL queries, with FQL it is possible to retrieve more information in a way that we can’t with just Graph API (we will get back to it soon). On form submission the data is sent to process.php.

<?php
include_once("config.php");
if ($fbuser) {
  try {
        //Get user pages details using Facebook Query Language (FQL)
        $fql_query = 'SELECT page_id, name, page_url FROM page WHERE page_id IN (SELECT page_id FROM page_admin WHERE uid='.$fbuser.')';
        $postResults = $facebook->api(array( 'method' => 'fql.query', 'query' => $fql_query ));
    } catch (FacebookApiException $e) {
        echo $e->getMessage();
  }
}else{
        //Show login button for guest users
        $loginUrl = $facebook->getLoginUrl(array('redirect_uri'=>$homeurl,'scope'=>$fbPermissions));
        echo '<a href="'.$loginUrl.'"><img src="images/facebook-login.png" border="0"></a>';
}

if($fbuser && empty($postResults))
{
        /*
        if user is logged in but FQL is not returning any pages, we need to make sure user does have a page
        OR "manage_pages" permissions isn't granted yet by the user.
        Let's give user an option to grant application permission again.
        */
        $loginUrl = $facebook->getLoginUrl(array('redirect_uri'=>$homeurl,'scope'=>$fbPermissions));
        echo 'Could not get your page details, make sure you have created one!';
        echo '<a href="'.$loginUrl.'">Click here to try again!</a>';
}elseif($fbuser && !empty($postResults)){

//Everything looks good, show message form.
?>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Post to Facebook Page Wall Demo</title>
<link href="style.css" rel="stylesheet" type="text/css" />
</head>
<body>

<div class="fbpagewrapper">
<div id="fbpageform" class="pageform">
<form id="form" name="form" method="post" action="process.php">
<h1>Post to Facebook Page Wall</h1>
<p>Choose a page to post!</p>
<label>Pages
<span class="small">Select a Page</span>
</label>
<select name="userpages" id="upages">
    <?php
    foreach ($postResults as $postResult) {
            echo '<option value="'.$postResult["page_id"].'">'.$postResult["name"].'</option>';
        }
    ?>
</select>
<label>Message
<span class="small">Write something to post!</span>
</label>
<textarea name="message"></textarea>
<button type="submit" class="button" id="submit_button">Send Message</button>
<div class="spacer"></div>
</form>
</div>
</div>

</body>
</html>
<?php
}
?>
</body>
</html>

Posting to Facebook Page Wall

After receiving page id and message variables from index page, all we need to do is use page id to select a page and send a POST request to PAGE_ID/feed with the publish_stream permission. This script tries to post message to selected user Facebook page wall, and displays a success message.

Main thing to note here in process.php is $post_url and $msg_body array variable, these two things define what you are going to post on Facebook page wall, for example you may want to automatically post notes, events, questions, status message, photos or videos.

The following snippet creates a status message :

 


 
$msg_body = array(
'message' => 'message for my wall'
);

To post a link on Facebook page wall :

 



 
$msg_body = array(
'link' => 'http://www.saaraan.com',
'message' => 'message for my wall'
);

Creates a note, but the $post_url must be PAGE_ID/notes.

 



 
$msg_body = array(
'subject' => 'Subject of Note',
'message' => 'message for my wall'
);

To create a poll question on behalf of the Page, $post_url to PAGE_ID/questions.





 
$msg_body = array(
'question' => 'Do you like saaraan.com?', //Question
'options' => array('Yes I do','No I do Not','Can not Say'), //Answers
'allow_new_options' => 'true' //Allow other users to add more options
);

To post a photo, change $post_url to PAGE_ID/photos.




 
$msg_body = array(
'source' => '@'.realpath('myphoto/somephot.gif'),
'message' => 'message for my wall');

You can also save your photos, notes, status messages as unpublished by issuing ‘published’=>’false’.

Or set scheduled_publish_time for the post : ‘scheduled_publish_time’=>’1333699439’ (UNIX timestamp). 

$msg_body = array(
'source' => '@'.realpath('myphoto/somephot.gif'),
'message' => 'message for my wall',
'published' => 'false', //Keep photo unpublished
'scheduled_publish_time' => '1333699439' //Or time when post should be published
);

Here’s complete code of “process.php“:

<?php
include_once("config.php");

if($_POST)
{
    //Post variables we received from user
    $userPageId     = $_POST["userpages"];
    $userMessage    = $_POST["message"];

    if(strlen($userMessage)<1)
    {
        //message is empty
        $userMessage = 'No message was entered!';
    }

        //HTTP POST request to PAGE_ID/feed with the publish_stream
        $post_url = '/'.$userPageId.'/feed';

        /*
        // posts message on page feed
        $msg_body = array(
            'message' => $userMessage,
            'name' => 'Message Posted from Saaraan.com!',
            'caption' => "Nice stuff",
            'link' => 'http://www.sanwebe.com/assets/ajax-post-on-page-wall',
            'description' => 'Demo php script posting message on this facebook page.',
            'picture' => 'http://www.sanwebe.com/templates/saaraan/images/logo.png'
            'actions' => array(
                                array(
                                    'name' => 'Saaraan',
                                    'link' => 'http://www.saaraan.com'
                                )
                            )
        );
        */

        //posts message on page statues
        $msg_body = array(
        'message' => $userMessage,
        );

    if ($fbuser) {
      try {
            $postResult = $facebook->api($post_url, 'post', $msg_body );
        } catch (FacebookApiException $e) {
        echo $e->getMessage();
      }
    }else{
     $loginUrl = $facebook->getLoginUrl(array('redirect_uri'=>$homeurl,'scope'=>$fbPermissions));
     header('Location: ' . $loginUrl);
    }

    //Show sucess message
    if($postResult)
     {
         echo '<html><head><title>Message Posted</title><link href="style.css" rel="stylesheet" type="text/css" /></head><body>';
         echo '<div id="fbpageform" class="pageform" align="center">';
         echo '<h1>Your message is posted on your facebook wall.</h1>';
         echo '<a class="button" href="'.$homeurl.'">Back to Main Page</a> <a target="_blank" class="button" href="http://www.facebook.com/'.$userPageId.'">Visit Your Page</a>';
         echo '</div>';
         echo '</body></html>';
     }
}

?>

 

  • answered 2 years ago
  • Sandy Hook

Your Answer

    Facebook Share