Create Auto-POST by Facebook-SDK - php

I want to enable Facebook Auto Post in my website.
first I created an app, then follow the facebook docs I used the facebook-sdk for PHP, I inserted APP-ID and APP-SECRET, create LOGIN-URL and... to my script (everything like the facebook docs), but I still have problem!!
The problem is:
for first time when user visit my page, he see the login link. when he click on it he will redirect to facebook dialog page for allowing app activities. after this, when facebook redirect user to my canvas page, he see the login link again!! (It seems the getUser() function not worked correctly in my script!).
base on facebook guides the user must see the user profile details... but still the login link is visible.
how can I fix this problem...?
<?php
require_once("libs/facebook.php");
$config = array(
'appId' => 'XXXX',
'secret' => 'XXXX'
);
$fbConnect = new Facebook($config);
$user_id = $fbConnect->getUser();
if($user_id)
{
try {
$userProfile = $fbConnect->api('/me', 'GET');
echo "Name: " . $userProfile['name'];
} catch (FacebookApiException $e) {
$loginUrl = $fbConnect->getLoginUrl();
echo "<a href='" . $loginUrl . "'>LOGIN 2</a>";
}
}
else
{
$loginUrl = $fbConnect->getLoginUrl(array( 'scope' => 'publish_stream' ));
echo "<a href='" . $loginUrl . "'>LOGIN 1</a>";
}
?>
User always see "LOGIN 1"! it means the $user_id is always null (before and after app allowing activities)!! after app allowing (when user for first time click on loginUrl link) I have 'stat' and 'code' in my url query string! but still "LOGIN 1" is visible!

I guess you want to publish a message like "Hey guys, I am now using Aref's superawsome Facebook app now", right?
This can be accomplished with the following lines :
<?php
require_once("/FBAPI/src/facebook.php");
$config = array();
$config['appId'] = 'your_app_id';
$config['secret'] = 'your_app_secret';
$facebook = new Facebook($config);
$user = $facebook->getUser();
if(!$user){
$loginUrl = $facebook->getLoginUrl(array('scope'=>'publish_stream', 'redirect_uri'=>'http://www.example.com'));
}
if($user){
try{
$user_profile = $facebook->api('/me');
$access_token = $facebook->getAccessToken();
$vars = array(
'caption' => 'Aref\'s Facebook Application',
'message' => 'Hey guys, I am now using Aref\'s superawsome Facebook App :D',
'name' => 'Test',
'link' => 'http://www.example.com',
'description' => 'Aref\'s Facebook Canvas App',
'picture' => 'http://fbrell.com/f8.jpg'
);
$result = $facebook->api('/me/feed', 'post', $vars);
if($result){
echo "Post was set";
}
else{
echo "Error!";
}
}
catch(FacebookApiException $e){
error_log($e);
$user = NULL;
}
}
else{
echo '<img src="img/login.png"/>';
}
?>

Related

Facebook: PHP SDK issues

I have some facebook php code that worked flawlessly before the 4/30/15 upgrade. I upgraded my code, it seems to work on certain computers but not on others. On computers that it doesn't work on I've tried multiple browsers with the same result. I am able to log into Facebook using the SDK, but it won't post anything to my page's wall. Same code, different computer, and everything works fine. Here's the code:
<?php
$facebook = new Facebook(array(
'appId' => '##########',
'secret' => '##########',
'fileUpload' => true
));
$user = $facebook->getUser();
if ($user) {
try {
$user_profile = $facebook->api('/me');
}
catch (FacebookApiException $e) {
error_log($e);
$user = null;
}
}
if ($user) {
$logoutUrl = $facebook->getLogoutUrl(array(
'next' => ($user['baseurl'] . 'logout.php')
));
} else {
$loginUrl = $facebook->getLoginUrl(array(
'scope' => 'publish_pages , manage_pages'
));
}
$access_token = $facebook->getAccessToken();
$params = array(
'access_token' => $access_token
);
#The id of the fanpage
$fanpage = '############';
#The id of the album
$album_id = '############';
if ($user) {
$accounts = $facebook->api('/me/accounts', 'GET', $params);
foreach ($accounts['data'] as $account) {
if ($account['id'] == $fanpage || $account['name'] == $fanpage) {
$fanpage_token = $account['access_token'];
}
}
$message = 'Post this to the wall.';
$img = 'path to image.jpg';
$args = array(
'message' => $message,
'image' => '#' . $img,
'aid' => $album_id,
'no_story' => 0,
'access_token' => $fanpage_token
);
$photo = $facebook->api($album_id . '/photos', 'post', $args);
}
?>
Most permissions need to get approved by Facebook before they can be used for any user, else they only work for users with a role in the App. Check out the docs about Login Review.
You can only use publish_pages and manage_pages as App Admin/Developer/Tester without review.
If you only test with those users and it still does not work, debug the Access Token in the Debugger and see if those permissions are really authorized: https://developers.facebook.com/tools/debug/
Edit: After reading your comment, i believe you are trying to use a User Token. Use /me/accounts to get a Page Token and try again with that one. If you debug the Token, make sure the Page shows up too.

is it possible to post stories to facebook page wall from my website without logging in to facebook?

Here is the code i used to post stories to facebook page wall from my website. i have installed facebook sdk like facebook.php and base_facebook.php etc files.My requirement is to post stories without logging into facebook.i have gone through many tutorials yet i couldnt find any solution for this .can you please help me in this.here is the code which i am using.
$appid = 'xxxxx'; //Application ID
$appsec = 'xxxxx'; // Application secret
$redirectUrl = 'http://test.com/admin/'; //Facebook redirects back to this page
$permissions = 'publish_stream'; // Permissions we will need
if(isset($_POST['FacebookPageID']) && strlen($_POST['FacebookPageID'])>10)
{
$_SESSION['FacebookPageID']=$_POST['FacebookPageID'];
$_SESSION['FacebookMessage']=$_POST['FacebookMessage'];
$_SESSION['FacebookTitle']=$_POST['FacebookTitle'];
}
if(!is_numeric($_SESSION['FacebookPageID']) || strlen($_SESSION['FacebookPageID'])<5)
{
die("<meta http-equiv=\"refresh\" content=\"2;URL=".$redirectUrl."\" />");
}
else
{
if(!isset($_GET["code"]))
{
$_SESSION['state'] = md5(uniqid(rand(), TRUE));
$RedirectToFacebook = "https://www.facebook.com/dialog/oauth?client_id=".$appid;
$RedirectToFacebook .="&redirect_uri=".urlencode($redirectUrl.'test.php');
die("<script type=\"text/javascript\">top.location.href='" . $RedirectToFacebook . </script>
<noscript><a href='".$RedirectToFacebook."'>Needs Permissioins</a></noscript>");
}
else
{
############## Facebook Page ID ############
$facebookPageID = $_SESSION['FacebookPageID'];
############## Wall Message ############
$facebookMessage = (empty($_SESSION['FacebookMessage']) || s trlen($_SESSION['FacebookMessage'])<5)?"Nice Facebook Wall Posting Script!":$_SESSION['FacebookMessage'];
$facebookTitle = (empty($_SESSION['FacebookTitle']) || strlen($_SESSION['FacebookTitle'])<5)?"Nice Facebook Wall Posting Script!":$_SESSION['FacebookTitle'];
if($_SESSION['state'] !="")
{
echo $_SESSION['state'];
// $siteurl=$_GET['realurl'];
$AccessTokenUrl = "https://graph.facebook.com/oauth/access_token?client_id=".$appid;
$AccessTokenUrl .="&redirect_uri=".urlencode($redirectUrl.'test.php');
$AccessTokenUrl .="&client_secret=".$appsec;
$AccessTokenUrl .="&code=".$_GET["code"];
$ReturnedString = file_get_contents($AccessTokenUrl);
$params=null;
parse_str($ReturnedString, $params);
$OurAccessToken = $params['access_token']; //access token
//---------------
require_once('src/facebook.php' ); //Include our facebook Php Sdk
$post_url = '/'.$facebookPageID.'/feed';
$facebook = new Facebook(array(
'appId' => $appid,
'secret' => $appsec,
));
//the Posting Parameters
$PostData = array(
'message' =>$facebookMessage,
'name' => $_SESSION['title'],
'caption' => "testcom",
'link' => 'from tranz',
'description' => $facebookMessage,
' picture' => "http://test/uploads/".$_SESSION['imageshare']."",
'access_token' =>$OurAccessToken,
'actions' => array(
array(
'name' => 'Saaraan',
'link' => 'http://www.saaraan.com'
)
)
);
//print_r($PostData); exit;
try {
$result = $facebook->api($post_url, 'post', $PostData);
//$result = $facebook->api('me/feed','post', $PostData);
if($result)
{
// session_destroy();
echo 'Done..';
die("<meta http-equiv=\"refresh\" content=\"2;URL=".$redirectUrl."? success=1&fbp=".$facebookPageID."\" />");
}
}
catch (Exception $e)
{
echo 'Facebook could be experiencing some problem! Try again later <br />Facebook Says: '. $e->getMessage();
}
//--------------
}
}
Facebook requires users to be authenticated to post something. No, it is not possible to post without authentication, if authentication is what you mean by "logging in."

How to authorising my PHP code to publish on Facebook?

I want to publish some test wall post on my Facebook USER account wall (Not any Facebook Page Or Facebook App just normal user account). I tried Facebook SDK like below but nothing happened it just asked me to login. but i want to login programmatically please tell me how to do this and post to my own wall?
require_once "API_Library/Facebook/src/facebook.php";
$config = array(
'userId' => 'USER_ID',
);
$facebook = new Facebook($config);
$user_id = $facebook->getUser();
if($user_id)
{
// We have a user ID, so probably a logged in user.
// If not, we'll get an exception, which we handle below.
try
{
$user = $config['userId'];
$user_profile = $facebook->api('/me', 'GET');
echo "Name: " . $user_profile['name'];
$ret_obj = $facebook->api('/me/feed', 'GET', array(
'link' => "https://www.facebook.com/$user",
'message' => 'Posting with the PHP SDK!'
));
echo '<pre>Post ID: ' . $ret_obj['id'] . '</pre>';
}
catch(FacebookApiException $e)
{
$login_url = $facebook->getLoginUrl();
echo 'Please login.';
error_log($e->getType());
error_log($e->getMessage());
}
}
else
{
// No user, print a link for the user to login
$login_url = $facebook->getLoginUrl();
echo 'Please login.';
}
You are doing an HTTP GET instead of a HTTP POST at
$ret_obj = $facebook->api('/me/feed', 'GET', array(
'link' => "https://www.facebook.com/$user",
'message' => 'Posting with the PHP SDK!'
));
You might want to change the API method to POST instead.

Posting on user's facebook wall using php 2011

Nothing gets posted to the wall, execution gets out of try after $result = $facebook->api('/me/feed/','post',$attachment); statement, any idea whats broken.
$facebook = new Facebook(array(
'appId' => 'xxxxxxxxxxxx',
'secret' => 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
));
// Get User ID
$user = $facebook->getUser();
if ($user) {
try {
// Get the user profile data you have permission to view
$user_profile = $facebook->api('/me');
$uid = $facebook->getUser();
$url = $facebook->getLoginUrl(array(
'canvas' => 1,
'fbconnect' => 0,
'req_perms' => 'email,publish_stream,status_update,user_birthday,user_location,user_work_history'));
$attachment = array
(
'access_token'=>$facebook->getAccessToken(),
'message' => 'I had a question: should I write a PHP facebook app that actually worked?',
'name' => 'I Asked Bert',
'caption' => 'Bert replied:',
'link' => 'http://apps.facebook.com/askbert/',
'description' => 'NO',
'picture' => 'http://www.facebookanswers.co.uk/img/misc/question.jpg'
);
echo "Test 1";
$result = $facebook->api('/me/feed/','post',$attachment);
echo "Test 2";
$_SESSION['userID'] = $uid;
} catch (FacebookApiException $e) {
$user = null;
}
} else {
die('Somethign Strange just happened <script>top.location.href="'.$facebook->getLoginUrl().'";</script>');
}
Test 1 is printed but not Test 2.
You said you were looking for updated documentation, did you check Facebook PHP-SDK FAQ?
Specifically,
How to authorize and have any of the following permissions?
How to post on a wall?
After you create an Application instance get your $user first
$user = $facebook->getUser();
From here, following the instructions from "How to authorize and have any of the following permissions?" using the scope
$par = array();
$par['scope'] = "publish_stream";
Check the user state to see which login/logout method is required passing the publish_stream permission
if ($user) {
$logoutUrl = $facebook->getLogoutUrl();
} else {
$loginUrl = $facebook->getLoginUrl($par);
}
Then place the attachment as explained in "How to post on a wall?"
if ($user) {
$attachment = array('message' => 'this is my message',
'name' => 'This is my demo Facebook application!',
'caption' => "Caption of the Post",
'link' => 'http://mylink.com/ ',
'description' => 'this is a description',
'picture' => 'http://mysite.com/pic.gif ',
'actions' => array(array('name' => 'Get Search',
'link' => 'http://www.google.com/ '))
);
try {
// Proceed knowing you have a user who is logged in and authenticated
$result = $facebook->api('/me/feed/','post',$attachment);
} catch (FacebookApiException $e) {
error_log($e);
$user = null;
}
}
As explained in the example app, put in a try/catch block to see what data is available depending on whether the user is logged in or not when making API calls.
A call such as
$cocacola = $facebook->api('/cocacola');
Will always work since it is publicly available.
Here are a couple of notes:
You are using the new PHP-SDK so don't use req_perms use scope instead
Put your /me/feed post call inside the try
You don't need to call getUser() twice, the user id is already in the $user
The user id will be already in the session, with key that looks like: fb_XXXXXXX_user_id where XXXXXXX is your app id
session already started..
below code surely works: even if you dont have permission it will try to get them
$facebook = new Facebook(array(
'appId' => 'xxxxxxxxxxxxxxxxxx',
'secret' => 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
));
$user = $facebook->getUser();
$user_profile = $facebook->api('/me');
if( array_key_exists('publish_stream', $permissions['data'][0]) ) {
// Permission is granted!
// Do the related task
//$post_id = $facebook->api('/me/feed', 'post', array('message'=>'Hello World!'));
$post_id = $facebook->api('/me/feed', 'post', $attachment);
} else {
// We don't have the permission
// Alert the user or ask for the permission!
echo "Click Below to Enter!";
header( "Location: " . $facebook->getLoginUrl(array("scope" => "publish_stream")) );
}
*Warning
as of sept 5 2011 this is working, but i saw on fb documentation they are changing method to poste on users wall and are discouraging use of publish stream. but its working for now

Facebook Iframe application authentication?

I have developed a Facebook application that runs inside an iframe in the Facebook canvas. For it to work properly I request extended permissions from the user. If the user hasn't authorized the application I send him/her to a login page with the getLoginUrl() method in the PHP SDK.
It works, but it's not pretty. The method sends the user to a landing page before the authentication page. It looks like this:
When I click "Go to Facebook.com" I see the actual page for permission requests (I also get right to the permissions page if I print the url, copy it and enter it into a new browser window). How do I make Facebook skip this step when I do the redirect from an Iframe?
My code looks like this (using CodeIgniter and Facebook PHP SDK):
$this->facebook = new Facebook(array(
'appId' => '{MY_APP_ID}',
'secret' => '{MY_SECRET}',
'cookie' => TRUE,
'domain' => $_SERVER['SERVER_NAME']
));
$this->facebook->getSession();
try {
$this->me = $this->facebook->api('/me');
}
catch (FacebookApiException $e) {
$this->me = NULL;
}
if ( is_null($this->me) ) {
redirect($this->facebook->getLoginUrl(array(
'req_perms' => 'offline_access,read_stream,publish_stream,user_photos,user_videos,read_friendlists',
'next' => $this->config->item('base_url').'fblogin.php?redirect_uri='.$this->uri->uri_string()
)));
}
I think you need to redirect the parent frame (i.e. _top) rather than the iFrame itself?
The way I do it is set up an INDEX.PHP file with the following
//if user is logged in and session is valid.
if ($fbme){
//fql query example using legacy method call and passing
parameter
try{
$fql = "select name, hometown_location, sex,
pic_square from user where uid=" .
$uid;
$param = array(
'method' => 'fql.query',
'query' => $fql,
'callback' => 'http://apps.facebook.com/yoursite/'
);
$fqlResult = $facebook->api($param);
}
catch(Exception $o){
d($o);
}
}
Then point your canvas url to http://yoursite.com/INDEX.php
The callback url in the above code which will be in INDEX.PHP sets where to look after permissions are granted.
FBMain.php looks like this
//set application urls here
$fbconfig['http://www.yoursite.com/iframeapp/YOURMAINPAGE.php/']
= "http://www.tyoursite.com/YOURMAINPAGE.php/";
$fbconfig['http://apps.facebook.com/CANVASBASEURL']
= "http://apps.facebook.com/CANVASBASEURL";
$uid = null; //facebook user id
try{
include_once "facebook.php";
}
catch(Exception $o){
echo '<pre>';
print_r($o);
echo '</pre>';
}
// Create our Application instance.
$facebook = new Facebook(array(
'appId' => $fbconfig['APPID'],
'secret' => $fbconfig['SECRET'],
'cookie' => true,
));
//Facebook Authentication part
$session = $facebook->getSession();
$loginUrl = $facebook->getLoginUrl(
array(
'canvas' => 1,
'fbconnect' => 0,
'req_perms'=>'email,publish_stream,status_update,user_birthday,user_location'
)
);
$fbme = null;
if (!$session) {
echo "<script type='text/javascript'>top.location.href
= '$loginUrl';";
exit;
}
else {
try {
$uid = $facebook->getUser();
$fbme = $facebook->api('/me');
} catch (FacebookApiException $e) {
echo "<script type='text/javascript'>top.location.href
= '$loginUrl';";
exit;
}
}
function d($d){
echo '<pre>';
print_r($d);
echo '</pre>';
} ?>
Hope its a little clearer. It took me a while to figure it out, but I got there, thought I would help.

Categories