can't post photos Facebook Page's Timeline as Page (PHP) - php

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.

Related

Facebook PHP API post to wall falls under "Recent Posts by Others"

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';
}

Facebook post image on fan page with app

I need to post on facebook fan page with app.
My post type is text+image.
When i post only text, i have no problem, but when i try to add a jpg it doesn't works.
Here's my code:
<pre>
<?php
require_once 'facebook.php';
// configuration
$appid = 'XXX';
$appsecret = 'YYY';
$pageId = 'ZZZ';
$msg = 'MSG MSG MSG';
$title = 'TITOLO TITOLO TITOLO';
$uri = 'http://www.google.it/';
$desc = 'Description';
$pic = 'http://sharefavoritebibleverses.com/images/bible_verses.png';
$action_name = 'AZIONE NOME';
$action_link = 'http://www.yahoo.it';
$facebook = new Facebook(array(
'appId' => $appid,
'secret' => $appsecret,
'cookie' => false,
));
$user = $facebook->getUser();
// Contact Facebook and get token
if ($user)
{
// you're logged in, and we'll get user acces token for posting on the wall
try
{
$facebook->setFileUploadSupport(true);
$page_info = $facebook->api("/$pageId?fields=access_token");
if (!empty($page_info['access_token'])) {
/*$attachment = array(
'access_token' => $page_info['access_token'],
'message' => $msg,
'name' => $title,
'picture'=>$pic
);*/
$photo_details = array(
'message' => 'message',
'access_token' => 'XYZ'
);
$photo_details['picture'] = '#'.realpath('aaa.jpg');
echo realpath('aaa.jpg');
$status = $facebook->api("/$pageId/feed", "post", $photo_details);
}
else
{
$status = 'No access token recieved';
}
}
catch (FacebookApiException $e)
{
error_log($e);
$user = null;
}
}
else
{
// you're not logged in, the application will try to log in to get a access token
header("Location:{$facebook->getLoginUrl(array('scope' => 'photo_upload,user_status,publish_stream,user_photos,manage_pages'))}");
}
echo $status;
echo "<br>CONT=".count($status);
?>
Also i need a format like second one, and not like first:
What's wrong in my code?
Thanks!
Try this:
//At the time of writing it is necessary to enable upload support in the Facebook SDK, you do this with the line:
$facebook->setFileUploadSupport(true);
//Create an album
$album_details = array(
'message'=> 'Album desc',
'name'=> 'Album name'
);
$create_album = $facebook->api('/me/albums', 'post', $album_details);
//Get album ID of the album you've just created
$album_uid = $create_album['id'];
//Upload a photo to album of ID...
$photo_details = array(
'message'=> 'Photo message'
);
$file='app.jpg'; //Example image file
$photo_details['image'] = '#' . realpath($file);
$upload_photo = $facebook->api('/'.$album_uid.'/photos', 'post', $photo_details);
Please try to make sure that $pic is the relative image location on your server and not a generic web url of the image.

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."

facebook graph api - post large image

I finally got facebooks graph api to post messages on my fan PAGE as page
How do i get it to post large images as a post, not as a link?
'source' => $photo seems to create a thumbnail
this is what i have so far
<?php
$page_id = 'YOUR-PAGE-ID';
$message = "I'm a Page!";
$photo = "http://www.urlToMyImage.com/pic.jpg";
require '../src/facebook.php';
// Create our Application instance (replace this with your appId and secret).
$facebook = new Facebook(array(
'appId' => 'YOUR-APP-ID',
'secret' => 'YOUR-SECRET-ID',
));
$user = $facebook->getUser();
if ($user) {
try {
$page_info = $facebook->api("/$page_id/?fields=access_token");
if( !empty($page_info['access_token']) ) {
$facebook->setFileUploadSupport(true); // very important
$args = array(
'access_token' => $page_info['access_token'],
'message' => $message,
'source' => $photo
);
$post_id = $facebook->api("/$page_id/feed","post",$args);
}
} catch (FacebookApiException $e) {
error_log($e);
$user = null;
}
}
// Login or logout url will be needed depending on current user state.
if ($user) {
$logoutUrl = $facebook->getLogoutUrl(array( 'next' => 'http://mydomain.com/logout_page.php' ));
} else {
$loginUrl = $facebook->getLoginUrl(array('scope'=>'manage_pages,publish_stream'));
}
?>
The problem here is that you are in actual fact not posting a photo. What you are doing is posting a link to that photo so what you see is indeed a thumbnail preview image that Facebook retrieved from that URL.
What you'll want to do is provide a full path to a file on your server prefixed with the # symbol. The topic has been discussed on the site quite a bit so I'll just point you in the direction of a canonical post dealing with uploading of images to Facebook with the PHP SDK
Upload Photo To Album with Facebook's Graph API
The code looks like this -
$facebook->setFileUploadSupport(true);
$params = array('message' => 'Photo Message');
$params['image'] = '#' . realpath($FILE_PATH);
$data = $facebook->api('/me/photos', 'post', $params);

Facebook post on page with PHP SDK

I'd like to post on page - throught my site. . I didn't find anything that could help me in documentation. Also none of google results gave mi answer.
function post_facebook($data=null){
$result = "";
require_once (ROOT. "/apps/configuration/models/ConfigurationItem.php");
require_once (ROOT . "/components/facebook/facebook.php");
$this->ConfigurationItem = new ConfigurationItem($this->getContext());
$row=$this->ConfigurationItem->findByCatKeyItemKey('system','facebook_login');
$apiid=$row['value'];
$row=$this->ConfigurationItem->findByCatKeyItemKey('system','facebook_pass');
$secret=$row['value'];
$facebook = new Facebook(array(
'appId' => $apiid,
'secret' => $secret,
'cookie' => true,
));
$session = $facebook->getSession();
print_r($session);
$me = null;
if ($session) {
try {
$uid = $facebook->getUser();
$me = $facebook->api('/me');
} catch (FacebookApiException $e) {
error_log($e);
}
$message=$data['facebook_text'];
$attachment = array(
'message' => $data['facebook_text'],
'name' => $data['name'],
'link' => $this->getLinkToLatestNews(),
'description' => '',
);
if($data['thumb_file_tree_id'] !== NULL) $attachment = $_SERVER['HTTP_HOST']."media/file/image_by_id/".$data['thumb_file_tree_id']."/?w=400&h=500";
try {
$facebook->api('/162618213751448/feed/', 'post', $attachment);
$result = "Facebook: Sent";
} catch (FacebookApiException $e) {
$result = "Facebook: Failed";
error_log($e);
}
} else {
$login_url = $facebook->getLoginUrl();
header("Location: ".$login_url);
exit;
}
return $result;
}
The wrong part is:
$session = $facebook->getSession();
$me = null;
if ($session) {
(...)
} else {
$login_url = $facebook->getLoginUrl();
header("Location: ".$login_url);
exit;
}
I want to allow user to login on specified FB account (this with page), and then send. App settings allow only this account to post, so it should be ok... But isn't. When I log out FB account, session still exists, but returns exception. What's wrong?
if you want to post on a fan page where you are adminstrator.. do the next
Your application needs to have this permission minimum:
$this->loginUrl = $this->facebook->getLoginUrl(
array(
'scope' => 'manage_pages,offline_access,publish_stream',
'redirect_uri' => $url,
)
);
After you are logged into:
//get pages or applications where you are administrator
$accounts = $this->facebook->api('/me/accounts');
//page where i want to post
$page_id = '227870047252297';
foreach($accounts['data'] as $account)
{
if($account['id'] == $page_id)
{
$token = $account['access_token'];
}
}
$attachment = array(
'access_token' => $token,
'message' => 'mensaje',
'name' => 'titulo',
'link' => 'http://...',
'description' => 'xxxxx',
'picture'=> 'http://...',
);
try{
$res = $this->facebook->api('/'.$page_id.'/feed','POST',$attachment);
} catch (Exception $e){
echo $e->getMessage();
}
If I understand this correctly, you want to send a message to the user's wall who's connected to your application via your website the moment they log in? If so, try this. Rework the script to prevent constant posting, but this model, in theory, should work.
if ($session) {
try {
$uid = $facebook->getUser();
$me = $facebook->api('/me');
// Place messaging portion here instead.
$message = $facebook->api('/me/feed', 'post', array(
'message'=> '<Message>',
'picture' => '<Picture URL>',
'link'=> '<URL>',
'description'=>'Description',
'name'=> '<Name of Post>',
'privacy'=> '<ALL_FRIENDS (Default)>',
'caption'=> '<Caption>',
)
);
} catch (FacebookApiException $e) {
error_log($e);
}
So if the user is connected with your application and the session is valid, it will automatically send the post to their news feed (Wall).

Categories