Hi I'm using facebook php sdk to make posts to my fanpage. I am attempting to schedule these posts to the future. I am running into some problems though. Here is my code
<?php
// This code is just a snippet of the example.php script
// from the PHP-SDK <https://github.com/facebook/facebook-php-sdk/blob/master/examples/example.php>
require_once('facebookphp/src/facebook.php');
$app_id = "xxxxx";
$app_secret = "xxxxxx";
// Create our Application instance (replace this with your appId and secret).
$facebook = new Facebook(array(
'appId' => $app_id,
'secret' => $app_secret,
'fileUpload' => true,
));
// Get User ID
$user = $facebook->getUser();
var_dump($user);
if ($user) {
try {
$page_id = 'xxxx';
$album_id = 'xxxxx';
$page_info = $facebook->api("/$page_id?fields=access_token");
if( !empty($page_info['access_token']) ) {
$args = array(
'access_token' => $page_info['access_token'],
'scheduled_publish_time' => "1361642425", #an example timestamp
'message' => "test post",
'source' => "#" . "/path/to/photo.jpg",
'published' => "0",
);
$post_id = $facebook->api("/$album_id/photos","post",$args);
#echo $post_id;
} else {
$permissions = $facebook->api("/me/permissions");
if( !array_key_exists('publish_stream', $permissions['data'][0]) ||
!array_key_exists('manage_pages', $permissions['data'][0])) {
// We don't have one of the permissions
// Alert the admin or ask for the permission!
header( "Location: " . $facebook->getLoginUrl(array("scope" => "publish_stream, manage_pages")) );
}
}
} catch (FacebookApiException $e) {
var_dump($e);
$user = null;
}
}
// Login or logout url will be needed depending on current user state.
if ($user) {
$logoutUrl = $facebook->getLogoutUrl();
echo 'logout';
} else {
$loginUrl = $facebook->getLoginUrl(array('scope'=>'manage_pages,publish_stream'));
echo 'login';
}
// ... rest of your code
?>
This code posts a photo to my facebook page scheduled into the future perfectly, except when the schedule time comes to pass the photo is not published. In the activity log the photo remains in the 'scheduled posts' section with the error 'Sorry, something went wrong publishing this scheduled post'
I suspected this was because of the parameter: 'published' => "0",
If I remove this parameter or set it to 1 then the post is not made at all and I get the error 'You cannot specify a scheduled publish time on a published post'
Scheduling the post with the above code, works perfect work me. I just tried and scheduled the post with 11 minutes later and I got the notification after 11 minutes and photo was published on the said album.
Actually its some kinda facebook bug.
Just go to each post, click on 'Reschedule' and adjust the time by a 15 minutes (or however much you want). For some reason this resets them individually and everything goes back to normal, the posts will once again post themselves according to schedule.
I know this is a tedious way to fix something which Facebook should fix on their own, but it works.
Related
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'm sending notifications to my application users like this :
require_once('php-sdk/facebook.php');
$config = array
(
'appId' => 'blabla',
'secret' => 'blablablabla',
);
$facebook = new Facebook($config);
$user_id = $facebook->getUser();
$post = $facebook->api('/'.$user_id.'/notifications/', 'post', array
(
'access_token' => 'blabla|blablablabla',
'href' => 'https://www.my_app_url.net/',
'template' => "You have X new updates waiting on MyAppName !",
'ref' => 'MyApp_notification'
));
Now, if the user have a new update on my app but haven't visited since last notification, I send him a new notification with the new number of updates waiting for him, which could be very annoying if he doesn't connect for a while and has 50 new facebook notifications...
So my question is : Is it possible to remove previous notification(s) on user's Facebook when I send a new one using the PHP API ?
I've searched but couldn't find the answer...
I have found how to mark notifications as read.
require_once('php-sdk/facebook.php');
$config = array
(
'appId' => 'blabla',
'secret' => 'blablablabla',
);
$facebook = new Facebook($config);
$user_id = $facebook->getUser();
if ($user_id) // Only if the user is connected
{
$permissions = $facebook->api("/me/permissions");
if (array_key_exists('manage_notifications', $permissions['data'][0])) // Check if we have the permission to manage the notifications
{
$access_token = $facebook->getAccessToken();
$get = $facebook->api('/me/notifications?include_read=0&access_token='.$access_token, 'get'); // We get all the unread notifications from the app
for ($i=0; $i<count($get['data']); $i++) // Now let's mark each of them as read
{
$notification_id = $get['data'][$i]['id'];
$facebook->api('/'.$notification_id.'?unread=0&access_token='.$access_token, 'post');
echo 'Mark '.$notification_id.' as read : OK<br>';
}
}
else
{
echo 'err0r: user have not allowed the app to manage his notifications';
}
}
else
{
echo 'err0r: no user connected to the app';
}
It seems that there is no way to DELETE some notifications, so this is the best solution I have found... hope this will help anyone who have the same problem !
Here's a link to the full code on my PasteBin : http://pastebin.com/2J0c5L18
I am trying to post a status update on the wall of a group which I am a member of. Here is the code I am using
<?php
require 'facebook-php-sdk/src/facebook.php';
$appId = 'xxxxxxxxxxxxxxxx';
$appSecret = 'xxxxxxxxxxxxxxxx';
$extended_access_token = 'xxxxxxxxxxxxxxxxxxxxx';
$facebook = new Facebook(array('appId' => $appId, 'secret' => $appSecret));
$msg_body = array(
'message' => 'Good evening',
'type' => 'status',
'access_token' => $extended_access_token,
);
$groups = array(
'Group name' => '1234567',
);
foreach($groups as $group_name => $group_id){
try {
$post_url = "/$id/feed";
$postResult = $facebook->api($post_url, 'post', $msg_body );
print_r($postResult);
} catch (FacebookApiException $e) {
echo $e;
}
}
?>
If I login to fb via browser and hit this page in a new tab, the message is getting posted to the group wall. But If I am not logged into facebook, then if I hit this page, no message is getting posted and I am getting an error message
OAuthException: (#200) The user hasn't authorized the application to perform this action
How can I post to this group via offline mode? Searched a lot for this, could not find any useful info.
you need to have the permissions from the group owner
Change $id to $group_id and you'll be fine.
you ned to get apps this permession : publish_actions,publish_stream,user_groups,
I am on the verge of going crazy I think!
I am logged into my Personal Facebook account on my work machine and the app I am using works fine but on any other machine logged in as me, the app admin or anyone else the page just seems to keep on constantly refreshing with the state parameter in the url just whirring away and changing between page loads. (I have a laptop sitting on my desk, both using Firefox aswell)
I'm sure it was working on all machines that tested it the other day. Today it started with an error but I can't remember the error code but it was to do with the re-direct url not being owned by the domain but this doesn't seem to crop up now.
I am not the admin of the app either.
Here is the relevant code:
<?
error_reporting(0);
// Facebook PHP SDK
include_once "src/facebook.php";
// app id and seret from the facebook app
$appId = 'xxxxxxxxxxxxxx';
$secret = 'xxxxxxxxxxxxxxxxxxxxxxxxxxx';
$facebook = new Facebook(array(
'appId' => $appId,
'secret' => $secret,
'cookie' => true,
));
//Facebook Authentication part
$user = $facebook->getUser();
$loginUrl = $facebook->getLoginUrl(
array(
'canvas' => 1,
'fbconnect' => 0,
'scope' => 'user_status,publish_stream,user_photos'
)
);
if ($user)
{
try
{
// page id and the feed we want
$user_feed = $facebook->api('PAGENUMBER/feed');
echo "<div id=\"graph\">";
$count = 0;
for ($i=0; $i<25; $i++)
{
// only want statuses - no videos, events, links etc.
if ($user_feed['data'][$i]['type'] == "status")
// just grabbing stuff and echoing it out
// blah blah blah
}
}
catch (FacebookApiException $e)
{
$user = null;
}
// close graph div
echo "</div>";
}
// if the user is not logged in then redirect to login page
if (!$user)
{
echo "<script type='text/javascript'>top.location.href = '$loginUrl';</script>";
exit;
}
?>
This was a pain but took out the if ($user) and the try catch and the login redirect and all that seemed to work.
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