Batch upload multiple photos to multiple user accounts - facebook-graph-api

I have an array that looks as follows:
$userImages = array(
'100000000000001' => array(
'..../image01.jpg',
'..../image02.jpg',
'..../image03.jpg',
),
'100000000000002' => array(
'..../image04.jpg',
'..../image05.jpg',
'..../image06.jpg',
),
);
which contains FB user ids as keys, and then an array of images to upload to each users account.
My upload code looks as follows:
/** #var FacebookSessionPersistence $facebook */
$facebook = $this->container->get('fos_facebook.api');
$facebook->setFileUploadSupport(true);
$count = 1;
foreach ($userImages as $userId => $images) {
$batch = array();
$params = array();
foreach ($images as $image) {
$request = array(
'method' => 'post',
'relative_url' => "{$userId}/photos",
'attached_files' => "file{$count}",
'access_token' => $this->getUserAccessToken($userId)
);
$batch[] = json_encode($request);
$params["file{$count}"] = '#' . realpath($image);
$count++;
}
}
$params['batch'] = '[' . implode(',', $batch) . ']';
$result = $facebook->api('/', 'post', $params);
return $result;
I've added user access tokens to each image, under access_token, but when $facebook-api() is called, I get the following back from Facebook:
Does anyone know why, I'm getting these errors? Am I adding the user access token in the wrong place?

The access_token had to be added to the $params associative array, in the root, not to each image item!

Your logic is good, but you need to put the access token inside the body for every individual request.
For example:
...
$request = array(
'method' => 'post',
'relative_url' => "{$userId}/photos",
'attached_files' => "file{$count}",
'body' => "access_token={$this->getUserAccessToken($userId)}",
);
...

Does anyone know why, I'm getting these errors? Am I adding the user access token in the wrong place?
Have you made sure, you’ve actually added access tokens at all, and not perhaps just a null value?
The error message does not say that you used a wrong or expired user access token, but it says that a user access token is required.
So I’m guessing, because you did not really put actual tokens into your separate batch request parts in the first place, then the fallback to your app access token occurs, and hence that particular error message.

Related

OAuthException when trying to upload/post photos to group

I am currently trying to upload photos to pages and groups through an app. I have these codes:
try
{
$facebook->setFileUploadSupport(true);
$args = array('message' => 'This is my image caption',);
$args['image'] = '#'.realpath('./uploads/terragarden1.png');
$response = $facebook->api('/GROUP_ID/photos/','POST',$args);
}
catch(FacebookApiException $e)
{
echo "Error: ".$e;
}
The value of $args['image'] would be something like this:
#/home/publica/public_html/AutoPost/uploads/terragarden1.png
The problem is that it throws an OAuthException: An unknown error has occurred. I don't quite know what to do with this kind of error.
Additional:
When I try to post image using the same code and just changing
$response = $facebook->api('/GROUP_ID/photos/','POST',$args);
into $response = $facebook->api('/me/photos/','POST',$args);, the image would successfully be posted on the user's wall. What might be the problem here?
This works fine for me on pages:
$attachements = array(
'access_token' => $page->getToken(),
'message' => $post_pub['title'],
'url' => 'http://site.com/images/your_image.png' );
try{
$result = $facebook->api('/'.$page->getIdFacebook().'/photos', 'POST', $attachements, function(){
});
}
catch(Exception $e){ }
Might want to try switching from 'image' to 'url'
I got the same issue.
There is a topic about it here: https://developers.facebook.com/bugs/1430985030446221?browse=external_tasks_search_results_527428908614f7c36099745
I've been tried to do this with js sdk, with the same error response.

adding like comment issue using graph api

i have put last 3 posts in web page , if user loged in he can add comment / like , problem is if user loged in and try add like or comment he is getting an permission error #200 , if i loged in i can add like or comment (application is for me) , am getting the all permission nedded from the user , so how can i give him permission to add like / comment.
CODE :
$facebook = new Facebook(array(
'appId' => '',
'secret' => '',
'cookie' => true,
));
$user = $facebook->getUser();
if ($user) {
if (session_id()) {
} else {
session_start();
}
$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', '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,manage_pages',
'fbconnect' => 1,
'display' => "page",
'redirect_uri' => 'http://localhost/fb/index.php',
);
$login_url = $facebook->getLoginUrl($login_url_params);
header("Location: {$login_url}");
exit();
}
}
}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,manage_pages',
'fbconnect' => 1,
'display' => "page",
'redirect_uri'=>'http://localhost/fb/index.php',
);
$login_url = $facebook->getLoginUrl($login_url_params);
//redirect to the login URL on facebook
header("Location: {$login_url}");
exit();
}
$logoutUrl = $facebook->getLogoutUrl();
and if the user click on like button :
jQuery('ul.fb_list a').click(function(){
var comm_id = jQuery(this).attr("class");
jQuery.post('https://graph.facebook.com/'+comm_id+'/likes/',{
access_token : "<?php echo $access_token ?>"
});
});
Double check and make sure your variable comm_id is formated with both the user id of the person who posted the post, and then the id of the post itself, with an underscore in between, like this - USERID_POSTID. This is how facebook gives it you if you call to the graph api
$post_url = "https://graph.facebook.com/" . $user_id . "/posts?access_token=". urlencode($access_token);
Not sure if you're getting comm_id from another source or not. Also noticed in your code
access_token : "<?php echo $access_token ?>"
You forgot a semi-colon after the echo call. Should be this
access_token : "<?php echo $access_token; ?>"
Hope this helps. I see you're using a lot of jquery to do the like functionality. I like to stick w/ server side code for stuff like this, I feel that it's more stable for some reason.
This is how I did it. I have a like button like this -
echo '<div id="like_container-'.$i.'">
<div id="like_count">'.$num_likes.'</div>'
<div class="unliked"></div>
</div>';
and fb_Like() is an ajax call, something like this -
function fb_Like(post_id, token, num_likes, id){
$.ajax({
type: "GET",
url: "likepost.php",
data: 'id='+post_id+'&token='+token+'&likes='+num_likes,
success: function(html)
{
$("#like_container-"+id).empty().html(html);
}
});
}
And the likepost.php page is a script similar to the one on this page
Like a Facebook Post externally using Graph Api - example
This worked really well for me. It also let's me update the number of likes that the post has on the front end right above the like button if a like has been made. Good luck!
UPDATE
If you want to check if the user already likes a post, it's pretty simple w/ the facebook graph api
//Create Post Url
$post_url = "https://graph.facebook.com/" . $Page/User_id . "/posts?access_token=". urlencode($access_token);
//Get Json Contents
$resp = file_get_contents($post_url,0,null,null);
//Store Post Entries as Array
$the_posts = json_decode($resp, true);
foreach ($the_posts['data'] as $postdata) {
foreach ($postdata['likes']['data'] as $like){
if($like['id']==$user){
$liked=1;
}else{continue;}
}
if($liked==1){
//do something
}
}
This assumes that you already have a facebook user id for the logged in user, in this example, stored in the variable $user.

Limitation of number posts on API

I want to build a FB app which posts messages to the walls of those registered for the app.
There are two setups:
One message to many people (1-many, could occur few times a day)
Many user-specific massages (1-1, but many of them, could occur few times a day for each user)
All in all; one user could get a few different updates on his wall per day, but it could affect many users (that's pretty much the whole point of my idea)
Into what extend is Facebook going to allow me to do this, and won't think I'll be spamming.
PS:
I've come along this post, which seems to have remained unsolved...:
Post on Multiple Friend's Wall
And this post, which doesn't make it clear for me whether my idea is something I should start or not ;)
Graph API post to wall limitation
You can use Facebook batch API to do what you intent.
You can get more information on Facebook batch request at: http://25labs.com/tutorial-post-to-multiple-facebook-wall-or-timeline-in-one-go-using-graph-api-batch-request/
$batchPost[] = array(
'method' => 'POST',
'relative_url' => "/{ID1}/feed?access_token={ACCESS_TOKEN_FOR_ID1}",
'body' => http_build_query($body) );
$batchPost[] = array(
'method' => 'POST',
'relative_url' => "/{ID2}/feed?access_token={ACCESS_TOKEN_FOR_ID2}",
'body' => http_build_query($body) );
$batchPost[] = array(
'method' => 'POST',
'relative_url' => "/{ID3}/feed?access_token={ACCESS_TOKEN_FOR_ID3}",
'body' => http_build_query($body) );
$multiPostResponse = $facebook->api('?batch='.urlencode(json_encode($batchPost)), 'POST');
I developed an app in my website http://www.cefozyt.com which can post links, message etc. to multiple facebook users wall & groups. I used :-
if($user){
// Proceed knowing you have a logged in user who has a valid session.
//========= Batch requests over the Facebook Graph API using the PHP-SDK ========
// Save your method calls into an array
$queries = array(
array('method' => 'GET', 'relative_url' => '/'.$user),
array('method' => 'GET', 'relative_url' => '/'.$user.'/friends'),
array('method' => 'GET', 'relative_url' => '/'.$user.'/groups'),
array('method' => 'GET', 'relative_url' => '/'.$user.'/likes'),
);
// POST your queries to the batch endpoint on the graph.
try{
$batchResponse = $facebook->api('?batch='.json_encode($queries), 'POST');
}catch(Exception $o){
error_log($o);
}
//Return values are indexed in order of the original array, content is in ['body'] as a JSON
//string. Decode for use as a PHP array.
$user_info = json_decode($batchResponse[0]['body'], TRUE);
$friends_list = json_decode($batchResponse[1]['body'], TRUE);
$groups = json_decode($batchResponse[2]['body'], TRUE);
$pages = json_decode($batchResponse[3]['body'], TRUE);
//========= Batch requests over the Facebook Graph API using the PHP-SDK ends =====
if(isset($_POST['submit_x'])){
if($_POST['message'] || $_POST['link'] || $_POST['picture']) {
$body = array(
'message' => $_POST['message'],
'link' => $_POST['link'],
'picture' => $_POST['picture'],
'name' => $_POST['name'],
'caption' => $_POST['caption'],
'description' => $_POST['description'],
);
$batchPost=array();
$i=1;
$flag=1;
foreach($_POST as $key => $value) {
if(strpos($key,"id_") === 0) {
$batchPost[] = array('method' => 'POST', 'relative_url' => "/$value/feed", 'body' => http_build_query($body));
if($i++ == 50) {
try{
$multiPostResponse = $facebook->api('?batch='.urlencode(json_encode($batchPost)), 'POST');
}catch(FacebookApiException $e){
error_log($e);
echo("Batch Post Failed");
}
$flag=0;
unset($batchPost);
$i=1;
}
}
}
if(isset($batchPost) && count($batchPost) > 0 ) {
try{
$multiPostResponse = $facebook->api('?batch='.urlencode(json_encode($batchPost)), 'POST');
}catch(FacebookApiException $e){
error_log($e);
echo("Batch Post Failed");
}
$flag=0;
}
}
else {
$flag=2;
}
}
}
?>

I want to post from my site on my fanpage

I have create an app in facebook and, between php sdk, i can post the article of my site on my profile.
Now, i want to post my article in my fanpage and not in my prfile. how i can do this?
This is the code that i use, not much different from the example in facebook developers:
// 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('facebook.php');
$config = array(
'appId' => 'xxxxxxxxxxxxx',
'secret' => 'xxxxxxxxxxxxxxxxx',
);
$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 {
$access_token = $facebook->getAccessToken();
$page_id='xxxxxxxxxxxxxx';
$ret_obj = $facebook->api('/me/feed', 'POST',
array(
'link' => $link,
'message' => $titolo,
'picture' => 'http://xxxxxxxxxxxxxxxxxx',
'name' => 'Ecosport',
'access_token' => $access_token
));
echo '<pre>Post ID: ' . $ret_obj['id'] . '</pre>';
} 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'
));
header("location:$login_url");
error_log($e->getType());
error_log($e->getMessage());
}
// Give the user a logout link
$id_articolo=$_GET['id_articolo'];
header("location:xxxxxxxxxx");
/*echo '<br />logout';*/
} 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' ) );
header("location:$login_url");
/*echo 'Please login.';*/
}
?>
Oviusly the "xxxx" are used for privacy. I tied to change this " $facebook->api('/me/feed',...... " into this " $facebook->api('/$page_id/feed',....... " but nothing. I can't to post my article in my fanpage.
Can you help me?
Thank you very much.
You need to ask for the manage_pages and publish_stream permissions. Then call to /me/accounts to get a list of accounts (aka pages) that the user administers. Each account in that list of accounts will have an access token associated with it. That access token is special and will need to be used to new up an instance of the facebook api. Once you do that, posting to the page wall is the same as posting to a user's wall (i.e. /me/feed)

What is wrong with Facebook and Twitter APIs?

Is anyone else noticing that facebook and twitters APIs aren't working?
For facebook even if I allow my application to have access to my wall
$facebook->getUser()
Is always 0... When I try to open getLoginUrl it just open pop-up and redirect it instantly to success return link...
Here is code:
require_once 'src/base_facebook.php';
require_once 'src/facebook.php';
$app_id = 'xxx';
$app_secret = 'xxx';
$facebook = new Facebook(array(
'appId' => $app_id,
'secret' => $app_secret,
'oauth' => true,
'cookie' => true
));
$req_perms = "publish_stream";
$user = $facebook->getUser();
if (!$user)
{
$loginUrl = $facebook->getLoginUrl(array('display' => 'popup', 'redirect_uri' => 'http://xxxx.com/return_close.php?success=1', 'cancel_url' => 'http://xxxx.com/return_close.php?success=0','req_perms' => $req_perms, 'scope' => $req_perms));
}
And for twitter it's like someone mistyped return link...
When I open getAuthorizeURL and when I log in it redirects me to this URL:
https://twitter.comoauth_callback/?oauth_token=yA2xjLsVRm9tIuVEysXnCV8R7TISW8tF94uznn7zlw&oauth_verifier=Io1N2I8zOEzJeBWI77WXFMqmMRNDfCrXZGQxXmxJLbI
Yes, https://twitter.comoauth_callback/ is right, there is no / after .com, it's together, so I get not found page...
It's like both APIs have serious problems... Facebook sometimes work and sometimes doesn't, it's buggy a lot...
Facebook library downloaded from OFFICIAL GitHub page. Tried versions:
v3.1.1
v3.1.0
v3.0.1
And none of those work...
Update
Return URL ( redirect_uri ) MUST have facebook class included in file...
There is so many examples/documentations and none of those had this explained...
So, Facebook fixed... Twitter still not working...
Well, nothing is broken in the API. Where did you get the above code? and if you come up with it then based on what resource?
First of all, take a look at the example of the OFFICIAL PHP-SDK, you'll notice the following:
Only the facebook.php file has been included, why not base_facebook.php? well because it's included in the facebook.php file!
Developers used to use req_perms but now to request permissions you just need to use scope
Take a look inside base_facebook.php for the params the Facebook() class expect: appId, secret and fileUpload ONLY
Only use the display parameter if you know what you are doing!
Use proper indentation with your code, it makes your life (and others!) much easier!
This been said, this is a rewrite of your code:
require 'src/facebook.php';
$app_id = 'xxx';
$app_secret = 'xxx';
$facebook = new Facebook(array(
'appId' => $app_id,
'secret' => $app_secret
));
$req_perms = "publish_stream";
$user = $facebook->getUser();
if (!$user) {
$loginUrl = $facebook->getLoginUrl(array('display' => 'popup', 'redirect_uri' => 'http://xxxx.com/return_close.php?success=1', 'cancel_url' => 'http://xxxx.com/return_close.php?success=0', 'scope' => $req_perms));
}