I want to post a message to the wall of a Facebook Page. I am the admin of the app and the page used in this code, I already gave permissions needed for my app to be able to post on my page, it works when I use only the field "message", like this:
$message = array(
'message' => "Test2",<br>
);
$result = $fb->api('/411895472189524/feed','POST',$message);
The code above posts to my page wall and the post is made "from" the page itself, just like if I would do it manually from facebook. This is working great.
But when I try to add more fields like "link" or "picture" or "description" the post goes in the "Recent Posts by Others on TEST Jojo Page" and the post is now made from my personnal account (Joelle Landrie) instead of from the page itself. See code below.
$message = array(
'message' => "Test2",
'picture' => "http://www.cleanpopo.com/uploads/1/3/1/5/13154615/245431315.jpg",
'description' => "This is a test description",
'link' => "google.com"
);
$result = $fb->api('/411895472189524/feed','POST',$message);
See: https://www.facebook.com/pages/TEST-Jojo-Page/411895472189524
The link field seems to be causing problem, I can get a successful post on my page using the message, picture and description field. Only this is useless to me, I need my post to have a link.
SOLUTION
Thanks to Shadowfax who asked if I was using the "page_access_token". I was not. I started looking on the web how to get this token, added it to my code and now it works great!!
The Final Code
$appId = 'YOUR APP ID';
$secret = 'YOUR SECRET';
$returnurl = 'http://www.yoursite.com';
$permissions = 'manage_pages, publish_stream, offline_access';
$fb = new Facebook(array('appId'=>$appId, 'secret'=>$secret));
$fbuser = $fb->getUser();
if($fbuser){
$page_id = "YOUR PAGE ID";
$page_access_token = "";
$result = $fb->api("/me/accounts");
// loop trough all your pages and find the right one
if( !empty($result['data']) )
{
foreach($result["data"] as $page)
{
if($page["id"] == $page_id)
{
$page_access_token = $page["access_token"];
break;
}
}
}
else
{
echo "AN ERROR OCCURED: could not get the access_token. Please verify the page ID ".$page_id." exists.";
}
// set the facebook active facebook access token as the one we just fetch
$fb->setAccessToken($page_access_token);
// Now try to post on page's wall
try{
$message = array(
'message' => "YOUR MESSAGE",
'picture' => "YOUR PICTURE",
'description' => "YOUR DESCRIPTION",
'link' => "YOUR LINK"
);
$result = $fb->api('/'.$page_id.'/feed','POST',$message);
if($result){
echo 'Successfully posted to Facebook Wall...';
}
}catch(FacebookApiException $e){
echo $e->getMessage();
}
}else{
$fbloginurl = $fb->getLoginUrl(array('redirect-uri'=>$returnurl, 'scope'=>$permissions));
echo 'Login with Facebook';
}
Just posting the answer as answer.
When posting as a page, you need to get manage_pages permission, then get the desired page's access_token via /me/accounts API call and use that token to make the /{page_id}/feed POST call.
Flames, the original poster, managed to do this and posted his solution edited in the question itself. I just pasting it here and making it Community Wiki
$appId = 'YOUR APP ID';
$secret = 'YOUR SECRET';
$returnurl = 'http://www.yoursite.com';
$permissions = 'manage_pages, publish_stream, offline_access';
$fb = new Facebook(array('appId'=>$appId, 'secret'=>$secret));
$fbuser = $fb->getUser();
if($fbuser){
$page_id = "YOUR PAGE ID";
$page_access_token = "";
$result = $fb->api("/me/accounts");
// loop trough all your pages and find the right one
if( !empty($result['data']) )
{
foreach($result["data"] as $page)
{
if($page["id"] == $page_id)
{
$page_access_token = $page["access_token"];
break;
}
}
}
else
{
echo "AN ERROR OCCURED: could not get the access_token. Please verify the page ID ".$page_id." exists.";
}
// set the facebook active facebook access token as the one we just fetch
$fb->setAccessToken($page_access_token);
// Now try to post on page's wall
try{
$message = array(
'message' => "YOUR MESSAGE",
'picture' => "YOUR PICTURE",
'description' => "YOUR DESCRIPTION",
'link' => "YOUR LINK"
);
$result = $fb->api('/'.$page_id.'/feed','POST',$message);
if($result){
echo 'Successfully posted to Facebook Wall...';
}
}catch(FacebookApiException $e){
echo $e->getMessage();
}
}else{
$fbloginurl = $fb->getLoginUrl(array('redirect-uri'=>$returnurl, 'scope'=>$permissions));
echo 'Login with Facebook';
}
Related
I have problem with Facebook SDK auto post to my Facebook business Page.
It is working code but now it's showing me error
"(#100) Only owners of the URL have the ability to specify the picture, name, thumbnail or description params. FacebookApiException"
I create cakePHP script to auto post Facebook to my Page. I create new App -> I took App Id and Secret ID. I created Access Token with long time expired. Of course I verifed domain for my Page with bussiness acount on FB.
What is wrong...? I don't have any idea!
please find my code
$config = array();
$config['appId'] = '16xxxxxxxxxxxx';
$config['secret'] = 'a24faxxxxxxxxxxxxxxxxxxxxx';
$config['fileUpload'] = false; // optional
$link = SITE_URL.'/PostAds/details/'.base64_encode($post_id);
$name = $this->request->data['title'];
$price = $this->request->data['price'];
$city = $this->request->data['city'];
$fb = new \Facebook($config);
$img_link = webroot.'/uploads/postAd/'.$image_name;
$params = array(
"access_token" => 'EAACZA18CF5TcBAL0E4XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX',
"message" => $name.' - '.$city.' Price:'.$price,
"link" => $link,
"picture" => $img_link,
"name" => $name,
"description" => $name.' '.$price,
"published" => true
);
try {
$ret = $fb->api('/page-id/feed', 'POST', $params);
echo 'Successfully posted to Facebook';
} catch(Exception $e) {
echo $e->getMessage();
}
I've read what seems to be every post on stack related to this topic but nothing seems to work.
I've gone to the Graph explorer on the fb developers page used the Get Access Token button, (making sure to select the parameters needed - user_likes,publish_actions,email,offline_access,publish_stream,manage_pages)then used that to create a long term access token with the following link: inserting/replacing
<MYAPPID>,<MYSECRETID>,<SHORT_TERM_TOKEN>
with the real stuff in:
https://graph.facebook.com/oauth/access_token?grant_type=fb_exchange_token&client_id=<MYAPPID>&client_secret=<MYSECRETID>&fb_exchange_token=<SHORT_TERM_TOKEN>
Got my <TWO_MONTH_TOKEN>
Tried now to implement into code:
require "fb_src/facebook.php";
$config = array('appId' => '<MYAPPID>','secret' => '<MYSECRETID>');
$params = array('scope'=>'user_likes,publish_actions,email,offline_access,publish_stream,manage_pages');
$facebook = new Facebook($config);
$user = $facebook->getUser();
if($facebook->getUser()) {
try {
$user_profile = $facebook->api('/me');
$access_token = $facebook->getAccessToken();
} catch(FacebookApiException $e) {
$login_url = $facebook->getLoginUrl($params);
error_log($e->getType());
error_log($e->getMessage());
}
} else {
$login_url = $facebook->getLoginUrl($params);
}
$page_id = "<MY_FANPAGE_ID>";
$page_access_token = "";
$result = $facebook->api("/me/accounts");
foreach($result["data"] as $page) {
if($page["id"] == $page_id) {
$page_access_token = $page["access_token"];
//echo '<br>';
//echo "2. ".$page_access_token;
break;
}
}
$args = array(
'access_token' => '<TWO_MONTH_TOKEN>',
'message' => "my short message",
'name' => "name of post",
'link' => "http://example.com/",
'picture' => "http://example.com/images/fbobimgSV403.jpg",
'actions' => array(
'name' => 'page name',
'link' => "http://example.com/page_name"
)
);
$post = $facebook->api("/$page_id/feed","post",$args);
What really has me in a twist is that this exact code worked at 2am this morning about 20 times while testing it out.. Then it stopped when I logged out to see if I could get it to work while not logged in. I've since logged in again and repeated the process to no avail. The access token is still good for 2 months. (Yes, i've tried clearing the cache and deleting cookies.)
I get this error:
Fatal error: Uncaught OAuthException: An active access token must be used to query information about the current user. thrown in /public_html/facebook/fb_src/base_facebook.php on line 1249
also I should point out that $user = $facebook->getUser(); returns 0 every time.
I'm hoping that someone has successfully done this and can steer me in the right direction. Thanks!
I want to post Photos on may Facebook Page's Timeline as Page not user using PHP SDK
Here is the sample code that I'm using
<?php
include_once("config.php");
if($_POST)
{
if(strlen($_POST["message"])<1)
{
//message is empty
$userMessage = 'No message!';
}
//Post variables we received from user
$userPageIds = '00000000000000';
$facebook->setFileUploadSupport(true);
$userMessage = $_POST["message"];
//HTTP POST request to PAGE_ID/feed with the publish_stream
$post_url = '/'.$userPageId.'/albums';
//*
// posts message on page feed
$page_info = $facebook->api("/$userPageId?fields=access_token");
$access_token = $facebook->getAccessToken();
// Get the new album ID
$albums = $facebook->api($userPageId.'/albums','GET',array('access_token'=>$access_token));
foreach($albums['data'] as $album)
{
echo $album['name'];
if($album['name'] == 'Timeline Photos')
{
$album_id = $album['id'];
}
}
$args = array(
'message' => $userMessage,
'image' => '#' . $_FILES['img']['tmp_name'],
'aid' => $album_id,
'no_story' => 0,
'access_token' => $page_info['access_token']
);
if ($fbuser) {
try {
$postResult = $facebook->api('/'.$album_id.'/photos', 'post', $args);
} catch (FacebookApiException $e) {
echo $e->getMessage();
}
}else{
$loginUrl = $facebook->getLoginUrl(array('redirect_uri'=>$homeurl,'scope'=>$fbPermissions));
header('Location: ' . $loginUrl);
}
//Show sucess message
}
?>
this code add the photo to the Page's Timeline album , but it doesnt appear in the page's wall
Any help is greatly appreciated.
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."
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"/>';
}
?>