Facebook PHP API : delete a notification previously sent by my app - php

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

Related

Create Facebook Event for group page using a SQL database and post using graph api

I have been trying to post to an event that has already been created in a mySQL database and use facebook's graph api to post it to a group page. I am able to post an array created right in the code, but I would like to post an array that I am pulling in from a POST command. Here is what I have.
public function get_event()
{
require_once 'application/php-sdk/facebook.php';
$config = array(
'appId' => '1407968509465242',
'secret' => '***********************',
'cookie' => false,
'fileUpload' => true
);
$id = $_POST['eventsDrp'];
$this->load->model('mdl_facebook_event');
$output = $this->mdl_facebook_event->get_event($id);
print_r ($output);
$facebook = new Facebook($config);
// Set the current access token to be a long-lived token.
$facebook->setExtendedAccessToken();
$access_token = $facebook->getAccessToken();
$page_id = '594922100555123';
$page_access_token = '*******************';
// Declare the variables we'll use to demonstrate
// the new event-management APIs
$event_id = 0;
$event_name = "New Event API Test Event";
$event_start = '2012-04-24T22:01:00+0000';
$event_privacy = "SECRET"; // We'll make it secret so we don't annoy folks.
// We'll create an event in this example.
// We'll need create_event permission for this.
$params = array(
'name' => $event_name,
'start_time' => $event_start,
'privacy_type' => $event_privacy,
'access_token' => $page_access_token,
'page_id' => $page_id //where $page_id is the ID of the page you are managing
);
// Create an event
$ret_obj = $facebook->api("/$page_id/events", 'POST', $output);
if(isset($ret_obj['id'])) {
// Success
$event_id = $ret_obj['id'];
echo ('Event ID: ' . $event_id);
} else {
echo ("Couldn't create event.");
}
// Convenience method to print simple pre-formatted text.
function printMsg($msg) {
echo "<pre>$msg</pre>";
}
I am trying to post the array from $output. I have tried to post from $params and everything works fine. When I try and post from $output I get Fatal error:
Uncaught OAuthException: Invalid token: "594922100555123". An ID has already been specified.

How to post to a facebook group wall in offline mode using graph API? (I am a member of group)

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,

Is Facebook long-lived access token usable on multiple users?

I'm experimenting with Facebook's long-live access token and I found that the long-lived access token is usable in different users. Is this normal?
I'm using the Facebook PHP SDK v3.2.2 and Yii. Here's my code to generate the long-lived access token from App_User_1
Yii::import('application.vendors.facebook.Facebook');
$facebook = new Facebook(
array(
'appId' => Yii::app()->params['facebookApi'],
'secret' => Yii::app()->params['facebookSecretCode'],
'cookie' => true,
)
);
$loginUrl = $facebook->getLoginUrl(array('display' => 'touch', 'scope' => 'publish_actions'));
$fbUser = $facebook->getUser();
if(!empty($fbUser))
{
$facebook->setExtendedAccessToken(); //long-live access_token 60 days
$access_token = $facebook->getAccessToken();
exit(print_r($access_token));
}
Here's my code to test posting to App_User_1's Facebook wall.
$message = "A message";
$link = "http://www.alink.com";
$picture = "http://www.alink/image.png";
$sendTo = "`**App_User_1**`";
$access_token = "xxxxxxxxxx";
Yii::import('application.vendors.facebook.Facebook');
$facebook = new Facebook(
array(
'appId' => Yii::app()->params['facebookApi'],
'secret' => Yii::app()->params['facebookSecretCode'],
'cookie' => true,
)
);
$attachment = array('message' => $message, 'link' => $link, 'picture' => $picture );
$api = "/$sendTo/feed/?access_token='.$access_token,";
$result = $facebook->api($api,'post', $attachment);
I have 2 test app user. If I substitute the App_User_1's access token, I can also post into App_User_2's Facebook Wall. Is this normal?
I think I may have been doing this the wrong way. Using the PHP SDK, the api method does not recognize the access_token as part of its path parameter. (e.g. /me/feed/?access_token=blah)
Instead, the access token should be specified under optional parameters in an array format.
Here's how I got mine to work.
$facebook_uid = '1234567890';
//Initialize array for the params parameter
$fb_data = array();
$fb_data['access_token'] = 'xxxxxxxxxx';
$fb_data['message'] = 'A test message';
$facebook->api('/'.$facebook_uid.'/feed/', 'post', $fb_data);
Tried swapping the access token with other app user's access token and not specifying access_token at all. Both will result in error (#200) The user hasn't authorized the application to perform this action.
I would also recommend using this tool by Facebook to verify that the access_token is generated correctly by your app. https://developers.facebook.com/tools/debug

Posts scheduled via Graph API frequently do not get published

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.

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

Categories