Batch wall post to multiple Facebook accounts using php - php

I am trying to post status messages to multiple FB users but not while they are on my site. I have publish_stream perms and a 60 day access token for each user I am posting to, but I can't figure out how to batch this correctly.
Is this the correct way to put in the access token?
$body = array(
'message' => $message,
'link' => $link,
'picture' => $picture,
'name' => $name,
'description'=> $description
);
$batchPost=array();
$i=1;
foreach ($user_fb_id_array as $fb_id) {
$batchPost[] = array(
'method' => 'POST',
'relative_url' => "/" . $fb_id['user_fb_id'] . "/feed?access_token=" . $fb_id['user_fb_auth_code'], // Will this work???
'body' => http_build_query($body) );
if($i++ == 50) {
try {
$multiPostResponse = $this->facebook->api('?batch='.urlencode(json_encode($batchPost)), 'POST');
} catch(FacebookApiException $e) {
error_log($e);
echo("Batch Post Failed");
}
unset($batchPost);
$i=1;
}
}
if(isset($batchPost) && count($batchPost) > 0 ) {
try{
$multiPostResponse = $this->facebook->api('?batch='.urlencode(json_encode($batchPost)), 'POST');
} catch(FacebookApiException $e){
error_log($e);
echo("Batch Post Failed");
}
}
To give credit where credit is due, this code was modified from the 25labs.com original code.

The access token should be defined for each call at the same level as 'method' and 'relative_url' but your method there might work too.
Are you actually getting an error message or are you just asking how to implement this?

Related

Facebook Php SDK - Posting a feed using batch is not showing the picture

Using the script originally from 25labs.com to post in multiple pages and groups.
It is posting the feed but the pictures are not showing. I'm pretty sure that something is blocking the pictures to show up in the feed, because when i share it in my time line, everything shows up.
I couldn't find anything wrong with the script. Facebook is blocking the images from the feeds. Any idea how to make the pictures to show up?
The form with the information being posted:
Message : A Technology Laboratory..
Link: http://25labs.com
Picture: http://25labs.com/25-labs.jpg
Name: 25 labs
Caption: 25labs.com
Description: Blablabla
Parts of the code:
if (!$user) {
// Get login URL
$loginUrl = $facebook->getLoginUrl(array(
'scope' => 'publish_stream,user_groups,read_stream,publish_actions,photo_upload,share_item',
'redirect_uri' => $site_url,
));
}
if ($user) {
// Proceed knowing you have a logged in user who has a valid session.
$token = $facebook->getAccessToken();
//========= 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.'/groups?limit=5000'),
array('method' => 'GET', 'relative_url' => '/'.$user.'/likes?limit=5000'),
);
// 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);
foreach ($_POST['ids'] as $id) {
$batchPost[] = array('method' => 'POST', 'relative_url' => "/$id/feed",'body' => http_build_query($body));
if ($i++ == 50) {
try{
$multiPostResponse = $facebook->api('?batch='.urlencode(json_encode($batchPost)), 'POST');
if (is_array($multiPostResponse)) {
foreach ($multiPostResponse as $singleResponse) {
$temp = json_decode($singleResponse['body'], true);
if (isset($temp['id'])) {
$splitId = explode("_", $temp['id']);
if (!empty($splitId[1])) $list_ids[] = $splitId[0];
}elseif (isset($temp['error'])) {
error_log(print_r($temp['error'], true));
}
}
}
}catch(FacebookApiException $e) {
error_log($e);
}
$flag=0;
unset($batchPost);
$i=1;
}
}

How to post on group wall of facebook

I want to post on group wall. I have permission of "user_groups" and "publish_stream". and also access_token.
and here is my code:
try{
$statusUpdate = $this->facebook->api('/'.$group_id.'/feed', 'post',
array(
'name' => stripslashes($productname),
//'caption'=>$caption,
'message' => $message,
'description' => $description,
'picture' => $picture,
'link'=>$link));
$postid = $statusUpdate['id']; // return id
} catch (Exception $e){
$postid = 0;
}
return $postid; // return id
}
When I run this code I get a return id which was the page id. but nothing post on my group wall. how to solve this?
This code works for me to post to a facebook page.
Get FB page access token ($value['access_token']) and its page id ($value['id'])
Populate the $params array
use the FB API to post your message 3.
This is a snippet
foreach ($pages as $key => $value) {
$params = array(
'access_token' => $value['access_token'],
'message' => $message
);
// ask facebook api to post the message to the selected page
$facebook->api()->api( "/" . $value['id'] . "/feed", 'POST', $params );
}

Facebook app that posts to all its users in a specific time (php)

It's my first question on stackoverflow. I made this application and it works fine for posting a photo to a user's wall once he visit the app page, But what I really want is to post many photos in a scheduled way (at a specific time like 12 Feb 2013 10:00 pm) to his wall and all users wall
I made a MySQL database that contains a table for users' ID, and a table for posts' info and time.
What can I do next?
include ("../facebook/facebook.php") ;
$facebook = new Facebook(array(
'appId' => APP_ID ,
'secret' => APP_SECRET ,
'fileUpload' => true,
));
$user = $facebook->getUser();
if ($user) {
try {
$user_profile = $facebook->api('/me');
} catch (FacebookApiException $e) {
error_log($e);
$user = null;
}
}
if ($user) {
$facebook->setFileUploadSupport(true);
$photo ="images/image1.jpg" ;
$message= "My message ";
$ret_obj = $facebook->api('/me/photos', 'post', array(
'source' => '#' . $photo,
'message' => $message,
)
);
$logoutUrl = $facebook->getLogoutUrl();
} else {
$loginUrl = $facebook->getLoginUrl(array(
'scope' => 'read_stream, publish_stream, photo_upload')
);
}
#kareem : In simple words you can have a loop statement for the same.
for($i=0;$i<$upperLimit;$i++)
{
$photo ="images/image".$i."jpg" ;
$message= "My message ";
$ret_obj = $facebook->api('/me/photos', 'post', array(
'source' => '#' . $photo,
'message' => $message,
)
);
}
$upperLimit is the limit , till which you are planning to post the image on users wall.
Note: you can have a set of Images in a location as image1...imagen,so that you can loop around the images while posting on user wall
if required you can add a timer inside the for loop for some delay

Posting on user's facebook wall using php 2011

Nothing gets posted to the wall, execution gets out of try after $result = $facebook->api('/me/feed/','post',$attachment); statement, any idea whats broken.
$facebook = new Facebook(array(
'appId' => 'xxxxxxxxxxxx',
'secret' => 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
));
// Get User ID
$user = $facebook->getUser();
if ($user) {
try {
// Get the user profile data you have permission to view
$user_profile = $facebook->api('/me');
$uid = $facebook->getUser();
$url = $facebook->getLoginUrl(array(
'canvas' => 1,
'fbconnect' => 0,
'req_perms' => 'email,publish_stream,status_update,user_birthday,user_location,user_work_history'));
$attachment = array
(
'access_token'=>$facebook->getAccessToken(),
'message' => 'I had a question: should I write a PHP facebook app that actually worked?',
'name' => 'I Asked Bert',
'caption' => 'Bert replied:',
'link' => 'http://apps.facebook.com/askbert/',
'description' => 'NO',
'picture' => 'http://www.facebookanswers.co.uk/img/misc/question.jpg'
);
echo "Test 1";
$result = $facebook->api('/me/feed/','post',$attachment);
echo "Test 2";
$_SESSION['userID'] = $uid;
} catch (FacebookApiException $e) {
$user = null;
}
} else {
die('Somethign Strange just happened <script>top.location.href="'.$facebook->getLoginUrl().'";</script>');
}
Test 1 is printed but not Test 2.
You said you were looking for updated documentation, did you check Facebook PHP-SDK FAQ?
Specifically,
How to authorize and have any of the following permissions?
How to post on a wall?
After you create an Application instance get your $user first
$user = $facebook->getUser();
From here, following the instructions from "How to authorize and have any of the following permissions?" using the scope
$par = array();
$par['scope'] = "publish_stream";
Check the user state to see which login/logout method is required passing the publish_stream permission
if ($user) {
$logoutUrl = $facebook->getLogoutUrl();
} else {
$loginUrl = $facebook->getLoginUrl($par);
}
Then place the attachment as explained in "How to post on a wall?"
if ($user) {
$attachment = 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/ '))
);
try {
// Proceed knowing you have a user who is logged in and authenticated
$result = $facebook->api('/me/feed/','post',$attachment);
} catch (FacebookApiException $e) {
error_log($e);
$user = null;
}
}
As explained in the example app, put in a try/catch block to see what data is available depending on whether the user is logged in or not when making API calls.
A call such as
$cocacola = $facebook->api('/cocacola');
Will always work since it is publicly available.
Here are a couple of notes:
You are using the new PHP-SDK so don't use req_perms use scope instead
Put your /me/feed post call inside the try
You don't need to call getUser() twice, the user id is already in the $user
The user id will be already in the session, with key that looks like: fb_XXXXXXX_user_id where XXXXXXX is your app id
session already started..
below code surely works: even if you dont have permission it will try to get them
$facebook = new Facebook(array(
'appId' => 'xxxxxxxxxxxxxxxxxx',
'secret' => 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
));
$user = $facebook->getUser();
$user_profile = $facebook->api('/me');
if( array_key_exists('publish_stream', $permissions['data'][0]) ) {
// Permission is granted!
// Do the related task
//$post_id = $facebook->api('/me/feed', 'post', array('message'=>'Hello World!'));
$post_id = $facebook->api('/me/feed', 'post', $attachment);
} else {
// We don't have the permission
// Alert the user or ask for the permission!
echo "Click Below to Enter!";
header( "Location: " . $facebook->getLoginUrl(array("scope" => "publish_stream")) );
}
*Warning
as of sept 5 2011 this is working, but i saw on fb documentation they are changing method to poste on users wall and are discouraging use of publish stream. but its working for now

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