upload photo to page timeline Facebook SDK - facebook

I made this small app that basically asks a user to login and post a photo to a FB page.
the code I have works great for posting on your own wall, but when it comes to posting to a page I am having some difficulties.
require_once('../src/facebook.php');
$config = array(
'appId' => 'XXXXXXXXXXXXX',
'secret' => 'XXXXXXXXXXXXXXX',
'fileUpload' => true,
);
$facebook = new Facebook($config);
$user_id = $facebook->getUser();
$photo = realpath("mypic.png"); // Path to the photo on the local filesystem
$message = 'Photo upload via the PHP SDK!';
if($user_id) {
try {
$ret_obj = $facebook->api('/PAGE_ID_HERE_??/photos', 'POST', array(
'source' => '#' . $photo,
'message' => $message,));
if i use feed instead of photos, like here
$facebook->api('/PAGE_ID_HERE_??/FEED',
it works, but only posts the message.
i have all permissions needed:
user_photos user_videos publish_action
manage_pages publish_stream

To interact with the page you need the access token of the user. The user needs to be the 'manager' or 'content creator' of the page. And those tokens are per user per page.
I have a PHP example where this is handled using a cURL call. I think it gives the idea.
$ch = curl_init();
$url = "https://graph.facebook.com/" . $album_id . "/photos?access_token=" . $access_token;
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $args);
$retdata = curl_exec($ch);
echo($retdata);
In this one the $album_id is the album id of the page and the $access_token is the access token for the user for the page.
Also here's an example by Facebook for a personal album. You can chage the album ID and the token and use that approach.

Related

Access token for a simple FQL retrieving the number of status for a page

I'm doing a really simple PHP app using the latest Facebook PHP SDK which aims to display the number of status a page of mine has.
To do so I created an app to have the app id and the app secret but after I'm kinda lost.
I thought I needed an app secret token so I first tried like this:
<?php
public function getFacebookPosts() {
require __DIR__ . '/libs/facebook-sdk/facebook.php';
$appId = 'myID';
$appSecret = 'mySecret';
$facebook = new Facebook(array(
'appId' => $appId,
'secret' => $appSecret,
));
$token = $this->getFacebookAppToken($appId, $appSecret);
try {
$jinnove = $facebook->api('/my.page');
$fql = '/fql?q=SELECT+status_id+FROM+status+WHERE+uid=' . $jinnove['id'] . '&' . $token;
var_dump($facebook->api($fql));
} catch(FacebookApiException $e) {
var_dump($fql, $e);
}
}
/**
* Function to Get Access Token from Facebook
* #param $appId
* #param $appSecret
* #return string
*/
protected function getFacebookAppToken($appId, $appSecret)
{
$args = array(
'grant_type' => 'client_credentials',
'client_id' => $appId,
'client_secret' => $appSecret
);
$ch = curl_init();
$url = 'https://graph.facebook.com/oauth/access_token';
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $args);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
$data = curl_exec($ch);
return $data;
}
But it returns me an error 102 with the following message: "A user access token is required to request this resource.".
So then I asked on IRC and someone told me I need a user access token to do that.
Of what I've understood a user access token can only be generated when a user explicitly log into facebook to authorize this app and renew the token sometimes.
Is that true? Is there no way to use a token which doesn't imply the user to be logged? Basically anyone can view this number of status, even people who don't have a Facebook account and I want no UI dialog at all.
For some reason, Facebook has decided that querying a status can only be done by a user.
You can get around this by querying the stream table, and only returning posts with type = 46, which are status updates:
SELECT post_id FROM stream WHERE source_id= YOUR_PAGE_ID AND type = 46 LIMIT 100
The stream table has a lot of restrictions on it. Even with a high LIMIT, you may not get all the status updates if the page has been around for a while.
You can also speed up your program by cutting the number of API calls from 3 to 1 with the following changes:
If you want to get a page's ID from its username replace = YOUR_PAGE_ID in the above query with IN (SELECT id FROM profile WHERE username = 'YOUR_PAGE_USERNAME')
You don't need the 'getFacebookAppToken()` function. The PHP SDK will automatically get you an app access token if you don't have an authenticated user.

Facebook API upload photo from URL

I have a website with photo gallery and I'd like to upload each photo (one by one) to my facebook page (not wall). I managed to post a message but now I want to upload a photo to a FB Page Wall by uploading an existing image from the server - specific URL (I don't want to upload again locally). Is this possible?
Yes you can do it
Example
In Graph Api Explorer
Make the call post, set url to https://graph.facebook.com/me/photos,
Add field with key message and value "any custom message"
Add another field with key url and value https://appharbor.com/assets/images/stackoverflow-logo.png
click submit
You need to know the album id and make call POST to:
https://graph.facebook.com/albumid/photos?access_token=$access_token
You will find the album id entering into the album and looking at the URL. Will be something like https://www.facebook.com/media/set/?set=a.XXXXXXXXXXX.YYYY.ZZZZZZZZZZ&type=3
Your album id are the XXXX.
this is what I use:
$facebook = new Facebook(array(
'appId' => FACEBOOK_APP_ID,
'secret' => FACEBOOK_SECRET,
'cookie' => true,
'fileUpload' => true,
));
$user = $facebook->getUser(); // Get the UID of the connected user, or 0 if the Facebook user is not connected.
$facebook->setFileUploadSupport(true);
if($user == 0) {
// If the user is not connected to your application, redirect the user to authentication page
/**
* Get a Login URL for use with redirects. By default, full page redirect is
* assumed. If you are using the generated URL with a window.open() call in
* JavaScript, you can pass in display=popup as part of the $params.
*
* The parameters:
* - redirect_uri: the url to go to after a successful login
* - scope: comma separated list of requested extended perms
*/
$login_url = $facebook->getLoginUrl($params = array('redirect_uri' => REDIRECT_URI,'scope' => PERMISSIONS_REQUIRED));
echo ("<script> top.location.href='".$login_url."'</script>");
} else {
// if the user is already connected, then fetch access_token and user's information or show some content to logged in user.
try
{
$access_token = $facebook->getAccessToken(); // Gives you current user's access_token
$user = $facebook->api('/me'); // Gets User's information based on permissions the user has granted to your application.
} catch(FacebookApiException $e){
$results = $e->getResult();
// Print results if you want to debug.
}
}
$img = './upload/'.$image_path;
$args = array(
'message' => 'Some Message',
'access_token'=>urlencode($access_token),
);
$args[basename($img)] = '#'.realpath($img);
$ch = curl_init();
$url = 'https://graph.facebook.com/me/photos';
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt ($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $args);
$data = curl_exec($ch);
$response = json_decode($data,true);
$config = array('appId' => $config['App_ID'],'secret' => $config['App_Secret']);
$facebook = new Facebook($config);
// sets our access token as the access token when we call
// something using the SDK, which we are going to do now.
$facebook->setAccessToken($access_token);
$page_id = "XXXXXXXXXXXXXXX";
$page_access_token = "";
$result = $facebook->api("/me/accounts");
foreach($result["data"] as $page) {
if($page["id"] == $page_id) {
$page_access_token = $page["access_token"];
break;
}
}
$facebook->setFileUploadSupport(true);
$photo = "http://cdn.sstatic.net/stackexchange/img/logos/so/so-logo.png";
$args = array(
'access_token' => $page_access_token,
'message' => "message here",
'url' => $photo,
);
$post = $facebook->api("/$page_id/photos","post",$args);

How to post to my facebook wall from my own adminpages(CMS)?

How can I post a ordinary post to my facebook wall from my administration pages where I upload content to my webpage?
So I upload content to my webpage from my CMS and next to where I display my uploaded content in my adminpages I would like to have a button that can publish that post to my facebook wall. As an ordinary post and not like a LIKE post or Comment post!
First you need to create an facebook app.
Then you will get an app id and a secret key.
Using this details you can do post into ur wall using facebook php library
or u can use the following function
<?php
function doWallPost($postName='',$postMessage='',$postLink='',$postCaption='',$postDescription='')
{
$FB_APP_ID='xxxxxxxxxxxxxxxxxxxxxxxx';
$FB_APP_SECRET='xxxxxxxxxxxxxxxxxxxxxxxxxxx';
$APP_RETURN_URL=((substr($_SERVER['SERVER_PROTOCOL'],0,4)=="HTTP")?"http://":"https://").$_SERVER['HTTP_HOST'].$_SERVER['SCRIPT_NAME'];
$code = $_REQUEST["code"];
if(empty($code))
{
$dialog_url = "http://www.facebook.com/dialog/oauth?client_id=".$FB_APP_ID."&redirect_uri=".$APP_RETURN_URL."&scope=publish_stream";
header("Location:$dialog_url");
}
$token_url = "https://graph.facebook.com/oauth/access_token?client_id=".$FB_APP_ID."&redirect_uri=".urlencode($APP_RETURN_URL)."&client_secret=".$FB_APP_SECRET."&code=".$code;
$access_token = file_get_contents($token_url);
$param1=explode("&",$access_token);
$param2=explode("=",$param1[0]);
$FB_ACCESS_TOKEN=$param2[1];
$url = "https://graph.facebook.com/me/feed";
$attachment = array( 'access_token' => $FB_ACCESS_TOKEN,
'name' => $postName,
'link' => $postLink,
'description' => $postDescription,
'message' => $postMessage,
'caption' => $postCaption,
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT,2);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $attachment);
$result=curl_exec($ch);
header('Content-type:text/html');
curl_close($ch);
return $result
}
?>
For details
follow How to post wall in facebook using API in PHP?
function postonwall(){
// showLoader(true);
FB.api('/me/feed', 'post',
{
message : "testtext.",
link : 'http://www.mydomain.se',
picture : 'http://www.mydomain.se/image.jpg',
name : 'iOS Apps & Games',
description : 'Checkout iOS apps and games from iThinkdiff.net. I found some of them are just awesome!'
},
function(response) {
// showLoader(false);
if (!response || response.error) {
alert('Error occured');
} else {
//alert('Post ID: ' + response.id);
alert('Success: Content Published');
}
});
}

Posting on Facebook wall from Codeigniter app

I have a CI-based app that allows users to post an update stream similar to Facebook's wall.
Currently, users can authenticate into my app via Facebook using FB connect.
I would like to offer the possibility of a user -- when posting to my app's wall -- also be able to send the same post to his/her Facebook wall.
It seems clear the FB's Graph API support this but I'm having a hard time in finding a roadmap/ code/ library to help with this. The example on the above link is unhelpful and doesn't give me any idea how to implement this.
For example, how would a controller for this function look like?
I've found Elliot's FB CI library here, but am unsure if this is needed to accomplish what I want.
Any advice is greatly appreciated - thanks.
I would suggest you use Facebook PHP SDK
In your controller just include facebook php sdk eg: https://github.com/facebook/php-sdk/blob/master/examples/example.php
To make a wall post the following code should do the trick:
$wall_post = 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'))
);
$result = $facebook->api('/me/feed/', 'post', $wall_post);
I ended up using a codeigniter helper function with curl to post to Facebook. Below is the code.
function facebook($data) {
$CI =& get_instance();
$CI->load->model('fk_model');
$token = $CI->fk_model->fk_cookie();
$attachment = array(
'access_token' => $token['access_token'],
'message' => $data['text'],
'link' => $data['link'],
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,'https://graph.facebook.com/' . $token['id'] . '/feed');
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $attachment);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); //to suppress the curl output
$result = curl_exec($ch);
curl_close($ch);
}

Add a wall post to a page or application wall as page or application with facebook graph API

I wan't to create a new wall post on a appliaction page or a "normal" page with the facebook graph API. Is there a way to "post as page"? With the old REST-API it worked like this:
$facebook->api_client->stream_publish($message, NULL, $links, $targetPageId, $asPageId);
So, if I passed equal IDs for $targetPageId and $asPageId I was able to post a "real" wall post not caused by my own facebook account.
Thanks!
$result = $facebook->api("/me/accounts");
foreach($result["data"] as $page) {
if($page["id"] == $page_id) {
$page_access_token = $page["access_token"];
break;
}
}
$args = array(
'access_token' => $page_access_token,
'message' => "I'm posting as a Page!"
);
$post_id = $facebook->api("/$page_id/feed","post",$args);
To publish as Page you need to add manage_pages permission first of all (and get the tokens).
Next use something like this:
$url = 'https://api.facebook.com/method/stream.publish?message=TEST&target_id=PAGEID&uid=PAGEID&access_token=YOUR_TOKEN';
$ch = curl_init();
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_REFERER, "");
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,0);
curl_setopt($ch, CURLOPT_URL, $url);
$result = curl_exec($ch);
curl_close($ch);
Set the value of targetpageid=null and check the output...