PHP API FACEBOOK - Users post to facebook page and personal wall - php

I created a contest where a submitted form will:
write a comment on the wall of Facebook staff and
write a comment on the wall of my page
I had no problems with step 1, but step 2 does not work. My code is as follows:
connect.php
<?php
//include the Facebook PHP SDK
include_once 'facebook.php';
//instantiate the Facebook library with the APP ID and APP SECRET
$facebook = new Facebook(array(
'appId' => 'CRYPT FOR THIS FORUM',
'secret' => 'CRYPT FOR THIS FORUM',
'cookie' => true
));
//Get the FB UID of the currently logged in user
$user = $facebook->getUser();
//if the user has already allowed the application, you'll be able to get his/her FB UID
if($user) {
//start the session if needed
if( session_id() ) {
} else {
session_start();
}
//do stuff when already logged in
//get the user's access token
$access_token = $facebook->getAccessToken();
//check permissions list
$permissions_list = $facebook->api(
'/me/permissions',
'GET',
array(
'access_token' => $access_token
)
);
//check if the permissions we need have been allowed by the user
//if not then redirect them again to facebook's permissions page
$permissions_needed = array('publish_stream', 'read_stream');
foreach($permissions_needed as $perm) {
if( !isset($permissions_list['data'][0][$perm]) || $permissions_list['data'][0][$perm] != 1 ) {
$login_url_params = array(
'scope' => 'publish_stream,read_stream',
'fbconnect' => 1,
'display' => "page",
'next' => 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']
);
$login_url = $facebook->getLoginUrl($login_url_params);
header("Location: {$login_url}");
exit();
}
}
//if the user has allowed all the permissions we need,
//get the information about the pages that he or she managers
//id pag sposiamo è 494659577226200
$accounts = $facebook->api(
'/me/accounts',
'GET',
array(
'access_token' => $access_token
)
);
//save the information inside the session
$_SESSION['access_token'] = $access_token;
$_SESSION['accounts'] = $accounts['data'];
//save the first page as the default active page
//$_SESSION['active'] = $accounts['data'][0];*/
//redirect to manage.php
header('Location: manage.php');
} else {
//if not, let's redirect to the ALLOW page so we can get access
//Create a login URL using the Facebook library's getLoginUrl() method
$login_url_params = array(
'scope' => 'publish_stream,read_stream',
'fbconnect' => 1,
'display' => "page",
'next' => 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']
);
$login_url = $facebook->getLoginUrl($login_url_params);
//redirect to the login URL on facebook
header("Location: {$login_url}");
exit();
}
?>
newpost.php
<?php
//include the Facebook PHP SDK
include_once 'facebook.php';
//start the session if necessary
if( session_id() ) {
} else {
session_start();
}
//instantiate the Facebook library with the APP ID and APP SECRET
$facebook = new Facebook(array(
'appId' => 'CRYPT',
'secret' => 'CRYPT',
'cookie' => true
));
//get the info from the form
$parameters = array(
'message' => $_POST['message'],
'picture' => $_POST['picture'],
'link' => $_POST['link'],
'name' => $_POST['name'],
'caption' => $_POST['caption'],
'description' => $_POST['description']
);
//add the access token to it
$parameters['access_token'] = $_SESSION['active']['access_token'];
//build and call our Graph API request
$newpost = $facebook->api(
'/494659577226200/feed',
'/me/feed',
'POST',
$parameters
);
//redirect back to the manage page
header('Location: manage.php');
exit();
494659577226200 = FBPAGEID
PROBLEM IS '/494659577226200/feed', and error AuthCode 200...

You need to ask your user's to give your app manage_pages permission to post to their pages they manage on behalf of them. Check out their permissions doc here, See Page Permissions section.
Quoted from docs:
manage_pages
Enables your application to retrieve access_tokens for Pages and Applications that the user administrates. The access tokens can be queried by calling //accounts via the Graph API. This permission is only compatible with the Graph API, not the deprecated REST API.
See here for generating long-lived Page access tokens that do not expire after 60 days.
Once you get this permission, you can then make a wall post using page access token

Related

Facebook 0Auth Client login not working. PHP APP

I have created a facebook app using PHP-SDK which posts a message on user's feed and it will print app access token on the canvas page. It does not opens any Dialog box for permissions access to app, also after opening the app it does not do anything. It just show "Please Login" where login isa button having some link which too isnot working. Help me!
<?php
// Remember to copy files from the SDK's src/ directory to a
// directory in your application on the server, such as php-sdk/
require_once('src/facebook.php');
$config = array(
'appId' => 'myappidhere',
'secret' => 'mysecrete,
'allowSignedRequest' => false // optional but should be set to false for non-canvas apps
);
$facebook = new Facebook($config);
$user_id = $facebook->getUser();
?>
<html>
<head></head>
<body>
<?php
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 {
$ret_obj = $facebook->api('/me/feed', 'POST',
array(
'link' => 'www.facebook.com',
'message' => 'Posting with the PHP SDK!Learning PHP and Facebook API :D :D'
));
echo '<pre>Post ID: ' . $ret_obj['id'] . '</pre>';
$token = $facebook->getAccessToken();
echo 'test';
echo $token;
// Give the user a logout link
echo '<br />logout';
} catch(FacebookApiException $e) {
// If the user is logged out, you can have a
// user ID even though the access token is invalid.
// In this case, we'll get an exception, so we'll
// just ask the user to login again here.
$login_url = $facebook->getLoginUrl( array(
'scope' => 'publish_stream'
));
echo 'Please login.';
error_log($e->getType());
error_log($e->getMessage());
}
} else {
// No user, so print a link for the user to login
// To post to a user's wall, we need publish_stream permission
// We'll use the current URL as the redirect_uri, so we don't
// need to specify it here.
$login_url = $facebook->getLoginUrl( array( 'scope' => 'publish_stream' ) );
echo 'Please login.';
}
?>
Is there any special settings which i have to do in my APP dashboard on facebook?
You missing single quotes at:
'secret' => 'mysecrete',
Is this a typo only in this post, not in your code? And is any arrors displayed? Use var_dump for dumping url:
$login_url = $facebook->getLoginUrl( array(
'scope' => 'publish_stream'
));
var_dump($login_url);

PHP sdk redirect after he have granted permission

I don't have very good skills in coding what i want to do is when i user visit my site and after he grant access to my app message will be posted to his wall and i want him to be redirected to some other url the wall post is working fine but after he grant permissions nothing happens only white page is shown this is the code what i have:
<?php
require_once "./src/facebook.php";
$app_id = "xxxxxx";
$app_secret = "xxxxx";
// Init facebook api.
$facebook = new Facebook(array(
'appId' => $app_id,
'secret' => $app_secret,
'cookie' => true
));
// Get the url to redirect for login to facebook
// and request permission to write on the user's wall.
$login_url = $facebook->getLoginUrl(
array('scope' => 'publish_stream')
);
$loginUrl = $facebook->getLoginUrl($params);
// If not authenticated, redirect to the facebook login dialog.
// The $login_url will take care of redirecting back to us
// after successful login.
if (! $facebook->getUser()) {
echo <<< EOT
<script type="text/javascript">
top.location.href = "$login_url";
</script>;
EOT;
exit;
}
// Do the wall post.
$facebook->api("/me/feed", "post", array(
message => "test",
picture => "http://s.ytimg.com/yt/img/doodles/teachers_day_yoodle-vflBKh2mG.png",
link => "http://www.youtube.com/",
name => "test",
caption => "test"
));
?>
to redirect a user after granting permissions use this:
$user = $facebook->getUser();
if($user){
// Get logout URL
$logoutUrl = $facebook->getLogoutUrl();
}else{
// Get login URL
$loginUrl = $facebook->getLoginUrl(array(
'scope' => 'publish_actions',
'redirect_uri' => 'http://mysite.com/success.html', //redirect user to this url
));
}

How can i post stories to facebook page without login to the account in php?

<?php
session_start();
$appid = 'xxxxxxxx'; //Application ID
$appsec = 'xxxxx'; // Application secret
$redirectUrl = 'http://test/tester/'; //Facebook redirects back to this page
$permissions = 'publish_stream,offline_access,read_stream,manage_pages'; // Permissions we will need
$access_token = '';
if(isset($_POST['FacebookPageID']) && strlen($_POST['FacebookPageID'])>10)
{
$_SESSION['FacebookPageID']=$_POST['FacebookPageID'];
$_SESSION['FacebookMessage']=$_POST['FacebookMessage'];
$_SESSION['Facebooktitle']=$_POST['Facebooktitle'];
// $_SESSION['image']=$_POST['image'];
}
if(!is_numeric($_SESSION['FacebookPageID']) || strlen($_SESSION['FacebookPageID'])<5)
{
session_destroy();
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.'process.php');
$RedirectToFacebook .="&state=".$_SESSION['state'];
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'];
//$target_path = $_SESSION['image'];
############## Wall Message ############
$facebookMessage = (empty($_SESSION['FacebookMessage']) || strlen($_SESSION['FacebookMessage'])<5)?"Nice Facebook Wall Posting Script!":$_SESSION['FacebookMessage'];
if($_GET['state'] == $_SESSION['state'])
{
$AccessTokenUrl = "https://graph.facebook.com/oauth/access_token?client_id=".$appid;
$AccessTokenUrl .="&redirect_uri=".urlencode($redirectUrl.'process.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' => 'uffcaffnews.com',
'name' => $Facebooktitle,
'caption' => "test.fff.com",
'link' => 'http://www.fff.com/assets/ajax-post-on-page-wall',
'description' => $facebookMessage,
'picture' => "http://test.c/images/desc.jpg",
'access_token' =>$OurAccessToken,
'actions' => array(
array(
'name' => 'Saaraan',
'link' => 'http://www.saaraan.com'
)
)
);
try {
$pageID = '3xxx';
$result = $facebook->api($post_url, 'post', $PostData);
if($result)
{
session_destroy();
echo 'Done..';
die("<meta http-equiv=\"refresh\" content=\"2;URL=".$redirectUrl."?");
}
}
i want to post stories to facebook page from my website admin without logging in to the facebook account.please help mei want to post stories to facebook page from my website admin without logging in to the facebook account.please help me
You don't need the offline_access permission to post content to Facebook. Only the publish_stream permission is needed.
Even if no user login is required. Once the user authorize your app with the publish_stream permission, you can start posting content on his behalf without the need of him to login!
You may refer here.

facebook Sdk 3.1.1 Access_token Issue

i am using the following code to get the access_token
<?php
//include the Facebook PHP SDK
include_once 'facebook.php';
//instantiate the Facebook library with the APP ID and APP SECRET
$facebook = new Facebook(array(
'appId' => 'REPLACE WITH APP ID',
'secret' => 'REPLACE WITH APP SECRET',
'cookie' => true
));
//Get the FB UID of the currently logged in user
$user = $facebook->getUser();
//if the user has already allowed the application, you'll be able to get his/her FB UID
if($user) {
//start the session if needed
if( session_id() ) {
} else {
session_start();
}
//do stuff when already logged in
//get the user's access token
$access_token = $facebook->getAccessToken();
//check permissions list
$permissions_list = $facebook->api(
'/me/permissions',
'GET',
array(
'access_token' => $access_token
)
);
//check if the permissions we need have been allowed by the user
//if not then redirect them again to facebook's permissions page
$permissions_needed = array('publish_stream', 'read_stream', 'offline_access', 'manage_pages');
foreach($permissions_needed as $perm) {
if( !isset($permissions_list['data'][0][$perm]) || $permissions_list['data'][0][$perm] != 1 ) {
$login_url_params = array(
'scope' => 'publish_stream,read_stream,offline_access,manage_pages',
'fbconnect' => 1,
'display' => "page",
'next' => 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']
);
$login_url = $facebook->getLoginUrl($login_url_params);
header("Location: {$login_url}");
exit();
}
}
//if the user has allowed all the permissions we need,
//get the information about the pages that he or she managers
$accounts = $facebook->api(
'/me/accounts',
'GET',
array(
'access_token' => $access_token
)
);
//save the information inside the session
$_SESSION['access_token'] = $access_token;
$_SESSION['accounts'] = $accounts['data'];
//save the first page as the default active page
$_SESSION['active'] = $accounts['data'][0];
//redirect to manage.php
header('Location: manage.php');
} else {
//if not, let's redirect to the ALLOW page so we can get access
//Create a login URL using the Facebook library's getLoginUrl() method
$login_url_params = array(
'scope' => 'publish_stream,read_stream,offline_access,manage_pages',
'fbconnect' => 1,
'display' => "page",
'next' => 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']
);
$login_url = $facebook->getLoginUrl($login_url_params);
//redirect to the login URL on facebook
header("Location: {$login_url}");
exit();
}
?>
But it is not getting back to my redirect URL, Firefox shows the following error
Firefox has detected that the server is redirecting the request for this address in a way that will never complete.
This problem can sometimes be caused by disabling or refusing to accept
cookies.
You can put login and auth process in another file like login.php
And then when you need to authenticate, then use include_once "login.php"; from your app.
Replace your-app-namespace.
<?php
//login.php
require 'lib/facebook.php';
require 'lib/fbconfig.php';
if (isset($_GET['code'])){
header("Location:http://apps.facebook.com/your-app-namespace");
exit;
}
$user=null;
//Facebook Authentication part
$user = $facebook->getUser();
// We may or may not have this data based
// on whether the user is logged in.
// If we have a $user id here, it means we know
// the user is logged into
// Facebook, but we don’t know if the access token is valid. An access
// token is invalid if the user logged out of Facebook.
$loginUrl = $facebook->getLoginUrl(
array(
'scope' => 'email,read_mailbox,publish_stream,user_birthday,user_location,read_stream,user_work_history,user_about_me,user_hometown'
)
);
if ($user) {
try {
// Proceed knowing you have a logged in user who's authenticated.
$user_profile = $facebook->api('/me');
} catch (FacebookApiException $e) {
//you should use error_log($e); instead of printing the info on browser
d($e); // d is a debug function defined at the end of this file
$user = null;
}
}
if (!$user) {
echo "<script type='text/javascript'>top.location.href = '$loginUrl';</script>";
exit;
}
//get user basic description
$userInfo = $facebook->api("/$user");
function d($d){
echo '<pre>';
print_r($d);
echo '</pre>';
}
?>
Instead of using
//redirect to the login URL on facebook
header("Location: {$login_url}");
Try using :
echo "<script type='text/javascript'>top.location.href = '$loginUrl';</script>";

access_token - Script to upload photo in fan page album

I am developing an app to include in my page tab. In this app, the user will go take a picture with your webcam and the picture will sent to an especific album in my fan page.
I found an script here: and he is working very well, but I've a problem, the script use an user access_token to upload the picture, dont's necessary ask permission of all users to upload the picture because the script use my administrator user to send to the page.
The big problem is: The user access token expire after 2 hours or when my admin user not logged in, the permission offline_access was discontinued and I don't know how my script will work.
I need that all user can upload photo using the system, anyone know how I can work?
Here is the script in PHP:
`
require_once 'library/facebook.php';
$facebook = new Facebook(array(
'appId' => '<appid>',
'secret' => '<appsecret>',
'fileUpload' => true
));
$access_token = 'access_token';
$params = array('access_token' => $access_token);
$fanpage = 'page_id';
$album_id ='album_id';
$accounts = $facebook->api('/ADMIN_ACCOUNT/accounts', 'GET', $params);
foreach($accounts['data'] as $account) {
if( $account['id'] == $fanpage || $account['name'] == $fanpage ){
$fanpage_token = $account['access_token'];
}
}
$valid_files = array('image/jpeg', 'image/png', 'image/gif');
$img = realpath("image_path");
$args = array(
'message' => 'message to write in legend',
'image' => '#' . $img,
'aid' => $album_id,
'no_story' => 1,
'access_token' => $fanpage_token
);
$photo = $facebook->api($album_id . '/photos', 'post', $args);
if( is_array( $photo ) && !empty( $photo['id'] ) ){
echo '<p><a target="_blank" href="http://www.facebook.com/photo.php?fbid='.$photo['id'].'">Click here to watch this photo on Facebook.</a></p>';
}`
You will need to request a long-lived access token by hitting the endpoint:
https://graph.facebook.com/oauth/access_token?
client_id=APP_ID&
client_secret=APP_SECRET&
grant_type=fb_exchange_token&
fb_exchange_token=EXISTING_ACCESS_TOKEN
Take a look at Scenario 4 on the following document:
http://developers.facebook.com/roadmap/offline-access-removal/
If you’re using that script to post to a fan page’s album, then you should get a page access token – they don’t expire.
Details see here: https://developers.facebook.com/docs/authentication/pages/

Categories