Here is what I'm seeing in the docs:
Apps can send notifications to any existing user that has authorized the app. No special or extended permission is required.
Okay, sounds good. I'm using the JS SDK and here is what I'm trying to do:
FB.api('/me/notifications?access_token=' + window.accessToken + '&href=test&template=test', function(response) {
console.log(response);
});
This is what I'm getting:
"(#200) The "manage_notifications" permission is required in order to query the user's notifications."
I have tried replacing the href parameter with my app's real domain. Using my facebook ID instead of "/me/" makes no difference either. HELP!
I HAVE tried adding the manage_notifications permission (and still doesn't work...), but my question is why does it say the opposite in the docs?
EDIT: Went to PHP:
<?php
include_once('sdk/facebook.php');
$user = $_POST['user'];
$message = $_POST['message'];
$config = array();
$config['appId'] = '609802022365238';
$config['secret'] = '71afdf0dcbb5f00739cfaf4aff4301e7';
$facebook = new Facebook($config);
$facebook->setAccessToken($config['appId'].'|'.$config['secret']);
$href = 'href';
$params = array(
'href' => $href,
'template' => $message,
);
$facebook->api('/' . $user . '/notifications/', 'POST', $params);
?>
EDIT 2: After a silly logic mistake it now works :)
To send a notification you must use application access token - appid|appsecret, so you should send it server side and execute via AJAX call. PHP example:
require_once("facebook.php");
$config = array();
$config['appId'] = 'YOUR_APP_ID';
$config['secret'] = 'YOUR_APP_SECRET';
$facebook = new Facebook($config);
$facebook->setAccessToken($config['appId'].'|'.$config['secret']);
$user = 'userid';
$message = 'message';
$href = 'href';
$params = array(
'href' => $href,
'template' => $message,
);
$facebook->api('/' . $user . '/notifications/', 'post', $params);
https://developers.facebook.com/docs/concepts/notifications/
Related
I'm trying to use the facebook php api to rsvp users to a public event.
So far I can only get it to work for users who have already been invited.
I've tried:
$path = $event_id.'/attending';
$method = 'POST';
try
{
$this->facebook->api($path, $method);
}
catch(FacebookApiException $e){}
Which does nothing.
My code as it stands is:
function rsvpEvent($event_id)
{
$fb_config = array(
'appId' => APP_ID,
'secret' => APP_SECRET,
'cookie' => true,
);
$this->load->library('facebook', $fb_config);
$me = $this->facebook->api('/me/');
$user_id = $me['id'];
$path = $event_id.'/invited/'.$user_id;
$status = $this->facebook->api($path, 'GET');
$status = $status['data'][0]['rsvp_status'];
if($status === 'not_replied')
{
$path = $event_id.'/attending';
$method = 'POST';
try
{
$this->facebook->api($path, $method);
}
catch(FacebookApiException $e){}
}
}
Has anyone got any ideas how I can get this to work?
$path = $event_id.'/attending?access_token='.$SOME_ACCESS_TOKEN;
You're not using the access token in your code, so I am uncertain of whether you skipped it when you copied it, If it's not in the code, then it may be that.
I retrieved the information here
I have problems to upload a photo to an album by the facebook API. this is my code.
$facebook->setFileUploadSupport(true);
//Create an album
$album_details = array(
'message'=> 'Message',
'name'=> 'Album Name'
);
$create_album = $facebook->api('/me/albums?access_token='.$access_token, 'post', $album_details);
//Get album ID of the album you've just created
$album_id = $create_album['id'];
echo $album_id." - ";
//Upload a photo to album of ID...
$photo_details = array();
$img = "app.jpg";
$photo_details['source'] = '#' . $img;
$photo_details['message'] = 'Wow.. cool image!';
$upload_photo = $facebook->api('/'.$album_id.'/photos?access_token='.$access_token, 'post', $photo_details);
When i upload the image with a form, it works! but this code does not upload the image into the album.
I have tried also with CURL but there is nothing... i don't know where the problem is...
After testing few things on Graph API Explorer, Here's a working PHP Version:
<?php
# Path to facebook's PHP SDK.
require_once("facebook.php");
# Facebook application config.
$config = array(
'appId' => 'YOUR_APP_ID',
'secret' => 'YOUR_APP_SECRET',
'fileUpload' => true # Optional and can be set later as well (Using setFileUploadSupport() method).
);
# Create a new facebook object.
$facebook = new Facebook($config);
# Current user ID.
$user_id = $facebook->getUser();
# Check to see if we have user ID.
if($user_id) {
# If we have a user ID, it probably means we have a logged in user.
# If not, we'll get an exception, which we handle below.
try {
# Get the current user access token:
$access_token = $facebook->getAccessToken();
# Create an album:
$album_details = array(
'access_token' => $access_token,
'name' => 'Album Name',
'message' => 'Your album message goes here',
);
$create_album = $facebook->api('/me/albums', 'POST', $album_details);
# Get album ID of the album you've just created:
$album_id = $create_album['id'];
# Output album ID:
echo 'Album ID: ' . $album_id;
# Upload photo to the album we've created above:
$image_absolute_url = 'http://domain.com/image.jpg';
$photo_details = array();
$photo_details['access_token'] = $access_token;
$photo_details['url'] = $image_absolute_url; # Use this to upload image using an Absolute URL.
$photo_details['message'] = 'Your picture message/caption goes here';
//$image_relative_url = 'my_image.jpg';
//$photo_details['source'] = '#' . realpath($image_relative_url); # Use this to upload image from using a Relative URL. (Currently commented out).
$upload_photo = $facebook->api('/' . $album_id . '/photos', 'POST', $photo_details);
# Output photo ID:
echo '<br>Photo ID: ' . $upload_photo['id'];
} 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, user_photos'));
echo 'Please login.';
error_log($e->getType());
error_log($e->getMessage());
}
} else {
# No user, print a link for the user to login and give the required permissions to perform tasks.
$params = array(
'scope' => 'publish_stream, user_photos', # These permissions are required in order to upload image to user's profile.
);
$login_url = $facebook->getLoginUrl($params);
echo 'Please login.';
}
?>
I have added comments so you could understand what it does by reading the code.
This works with both absolute url and relative url, I have commented out code for uploading image using relative url as you have mentioned in your comments you can't read real path of the image.
EDIT: Note: The user has to give extended permissions to your facebook application to upload images to their profile, Those permissions are publish_stream and user_photos.
Let me know if this helped you and if it works :)
$user = $this->facebook->getUser();
$this->facebook->setFileUploadSupport(true);
$user_profile = $this->facebook->api('/me');
$album_details = array(
'message' => 'Hello everybody this is me ' . $user_profile['name'],
'name' => 'I am so slim because I dont have money to eat....:('
);
$create_album = $this->facebook->api('/me/albums', 'post', $album_details);
// Upload a picture
$photo_details = array(
'message' => 'I am so slim because I dont have money to eat....:('
);
$photo_details['image'] = '#' . realpath('./a.jpg');
$upload_photo = $this->facebook->api('/' . $create_album['id'] . '/photos', 'post', $photo_details);
Please use $facebook on $this->facebook
i am trying to post to my friends' feeds using this code, but it is not working . i am stuck, any help ??
$app_url ="http://localhost.local/PMS/facebook/PostWithPHP.php";
$facebook = new Facebook(array(
'appId' => 'APPID',
'secret' => 'APPSECRET',
'cookie' => true,
));
// Get User ID
$user = $facebook->getUser();
if ($user) {
$user_friends = $facebook->api('/me/friends');
sort($user_friends['data']);
try {
// Proceed knowing you have a logged in user who's authenticated.
$access_token = $facebook->getAccessToken();
$vars = array(
'message' => 'My Message',
'name' => 'title',
'caption' => 'Caption',
'link' => 'Link',
'description' => 'Description',
'picture' => 'image'
);
foreach($user_friends['data'] as $f){
$sendTo = $f['id'];
$sendToName = $f['name'];
$result = $facebook->api("/".$sendTo ."/feed", 'post', $vars);
}
} catch (FacebookApiException $e) {
error_log($e);
$user = null;
}
}
// Login or logout url will be needed depending on current user state.
if ($user) {
$logoutUrl = $facebook->getLogoutUrl();
} else {
$loginUrl = $facebook->getLoginUrl(array('redirect_uri'=> $app_url));
echo "<script type='text/javascript'>";
echo "top.location.href = '{$loginUrl}';";
echo "</script>";
}
and another question is that using this code, but with replacing $facebook->api("/".$sendTo ."/feed", 'post', $vars); by $facebook->api("/me/feed", 'post', $vars); and of course without looping friends, posts on my timeline. how can i make it post on my wall ??
I guess for a post to a timeline you will need an accessToken from the user where to publish the content. In your case you just have the accessToken of the registered user, not of his friends. That is a restriction by FB I think.
1st check you getting the user id(place echo and check) if not try this... I think this will help you brother
$token_url = "https://graph.facebook.com/oauth/access_token?" ."client_id=" . $app_id ."&client_secret=" . $app_secret .
"&grant_type=client_credentials";
$access_token = file_get_contents($token_url);
$signed_request = $_REQUEST["signed_request"];
list($encoded_sig, $payload) = explode('.', $signed_request, 2);
$data = json_decode(base64_decode(strtr($payload, '-_', '+/')), true);
$user_id = $data["user_id"];
There are a few things wrong with your code. First of all, make sure the link and picture parameters for the post are valid URLs. Facebook will give you a error message otherwise ((#100) link URL is not properly formatted). Also, the link must go to the Canvas or Site URL for your application.
That should solve the issues with posting to a friend's wall.
However, may I remind you that your application is in violation of the Facebook Platform Policy. Facebook doesn't allow multiple posts to the stream (whether its yours or a friends) unless there is explicit permission from the user. It also to stop common friends seeing the same message from multiple friends.
You can follow the tutorial here:
https://www.webniraj.com/2012/11/22/facebook-api-posting-a-status-update/
But, instead of making a API call to: /me/feed, you replace me with the friend's User ID, so it looks like /12345/feed
Please note that Facebook has now disabled posting to Friends' walls via the API. Instead, you should either tag the user in an action or use the Requests API.
I am creating a Facebook Application containing multiple PHP pages. If I reinstantiate Facebook objects in all the files I get an Error Invalid OAuth access token signature.
I have tried a number of alternatives, also the $facebook->getSession() function doesn't work in the new framework and is deprecated.
So I tried to keep the access token in the session and use the same access token in my next PHP file's Facebook object.
On my first page i Have instantiated my App using:
$app_id = "107684706025330";
$app_secret = "__SECRET__";
$my_url = "http://www.sentimentalcalligraphy.in/wp-content/then_n_now/";
$config = array(
'appId' => $app_id,
'secret' => $app_secret,
'cookie' => true,
);
session_start();
$facebook = new Facebook($config);
$access_token = $facebook->getAccessToken();
echo $access_token;
$_SESSION['fob'] = $access_token;
On the next PHP file were I need to use the Facebook object for the second time:
$config = array(
'appId' => '107684706025330',
'secret' => '__SECRET__',
);
$facebook = new Facebook($config);
$access_tocken = $_SESSION['fob'];
echo $access_token;
$facebook->setAccessToken($access_token);
I still get an error that the access token is not valid. How am I supposed to use this. I need to use the following code in my second PHP file:
$friends = $facebook->api('/me/friends','GET');
Thanking you in Advance,
Nasir
I have a some code for Facebook API. I want to share with you.
// App user account and password
$app_id = 'blabla';
$app_secret = 'blabla';
// Create our Application instance (replace this with your appId and secret).
$facebook = new Facebook(array(
'appId' => $app_id,
'secret' => $app_secret,
));
// Get User ID
$user = $facebook->getUser();
// Login or logout url will be needed depending on current user state.
if ($user) {
$logoutUrl = $facebook->getLogoutUrl();
} else {
$loginUrl = $facebook->getLoginUrl();
}
$access_token = $facebook->getAccessToken();
if(isset($_GET["code"])){
// Get our app user feed
$user_profile_feed = $facebook->api('/me');
// Insert user id into users table while user login our app
// We have to control user who inserted our users table after before
$query_is_user = mysql_query("SELECT * FROM `users` WHERE `user_id` = ".$user_profile_feed['id']) or die("hata 1");
$count = mysql_num_rows($query_is_user);
if($count == 0) {
mysql_query("INSERT INTO `users`(`user_id`) VALUES (".$user_profile_feed['id'].")") or die("hata 2");
echo '<script language=Javascript>alert("Uygulamamiza Basariyla Giris Yaptiniz...");</script>';
}
$token_url = "https://graph.facebook.com/oauth/access_token?"
. "client_id=" . $app_id . "&redirect_uri=" . "http://apps.facebook.com/machine_learning/"
. "&client_secret=" . $app_secret . "&code=" . $_GET["code"];
$response = #file_get_contents($token_url);
$params = null;
parse_str($response, $params);
mysql_query("UPDATE users SET access_token='$params[access_token]' WHERE user_id='$user_profile_feed[id]'") or die("hata 4");
}
$url = "https://graph.facebook.com/oauth/authorize?"
."client_id=262609310449368&"
."redirect_uri=http://apps.facebook.com/machine_learning/&scope=read_stream";
I'm using the Facebook Graph API and want to check if a user has authenticated my Facebook app by user ID. How do I do this?
You use:
SELECT is_app_user FROM user WHERE uid=USER_ID
This should return:
[
{
"is_app_user": true
}
]
If the user has logged in to your application.
Expanding on ifaour's answer, in PHP this query would look something like this:
<?php
$facebook = new Facebook(
'appID' => YOUR_APP_ID,
'secret' => YOUR_APP_SECRET
);
$result = $facebook->api(array(
'method' => 'fql.query',
'query' => "SELECT is_app_user FROM user WHERE uid=$user_id"
));
$is_installed = $result[0]['is_app_user'];
Here you can batch multiple requests together and avoid using FQL.
Assuming you have already logged into facebook and set the access token to the application access token, you can do this:
$batch = array();
foreach($friendArray AS $friend) {
$batch[] = array(
'method' => 'GET',
'relative_url' => '/' . $friend . '?fields=installed'
);
}
FB()->useApplicationAccessToken();
$batchResponse = FB()->facebook()->api('?batch='.json_encode($batch), 'POST');
Then you can process the batch response with code like this:
$installedUsers = array();
$notInstalledUsers = array();
foreach ($batchResponse AS $response) {
$body = json_decode($response['body'], true);
if (!isset($body['id']))
continue;
$id = $body['id'];
if (isset($body['installed']))
$installedUsers[] = $id;
else
$notInstalledUsers[] = $id;
}