Monday, October 3, 2016

macOS Sierra: Facebook: Post Using PHP

Command:

$ cat /Library/WebServer/Documents/fb-tokens/index.php


Result:

<?php
print_r($_GET);

?>


URL (Get code):

https://graph.facebook.com/oauth/authorize?client_id=MY_APP_ID&scope=publish_actions&redirect_uri=http://localhost/fb-tokens/


Result:

Array ( [code] => MY_CODE )


URL (GET access token):

https://graph.facebook.com/oauth/access_token?client_id=MY_APP_ID&redirect_uri=http://localhost/fb-tokens/&client_secret=MY_APP_SECRET&code=MY_CODE


Result:

access_token=MY_ACCESS_TOKEN&expires=5176951


Command:

$ cat posttest.php


Result:

<?php
require_once __DIR__ . '/vendor/autoload.php';
require_once("vendor/facebook/php-sdk/src/Facebook/Facebook.php");
use Facebook\Facebook;

$config = array();
$config['app_id'] = 'MY_APP_ID';
$config['app_secret'] = 'MY_APP_SECRET';
$config['fileUpload'] = false; // optional

$fb = new Facebook($config);
 
$params = array(
"access_token" => "MY_ACCESS_TOKEN",
"message" => "My first post using php",
"link" => "http://nautil.us/issue/40/learning/is-artificial-intelligence-permanently-inscrutable",
"picture" => "http://static.nautil.us/10275_3ac01363eb96084101c0e5ed8be7374a.png",
"name" => "Is Artificial Intelligence Permanently Inscrutable?",
"caption" => "nautil.us",
"description" => "Despite new biology-like tools, some insist interpretation is impossible."
);
               
// post to Facebook
try {
$ret = $fb->post('/me/feed', $params);
echo 'Successfully posted to Facebook';
} catch(Exception $e) {
echo $e->getMessage();
}
?>