im building a facebook app and i want to notify the user
https://developers.facebook.com/docs/games/notifications
im using facebook php sdk
what i do:
user auths the app and accepts permission
i get the accesstoken like:
$facebook->getAccessToken()
and then i generate a long-time token like:
public function generateLongTimeToken($token){
$long_time_token_req_body = array(
"grant_type"=>"fb_exchange_token",
"client_id"=>$this->facebookOptions["appId"],
"client_secret"=>$this->facebookOptions["secret"],
"fb_exchange_token"=>$token
);
$query = http_build_query($long_time_token_req_body);
$lttreq = file_get_contents("https://graph.facebook.com/oauth/access_token?".$query);
$lttresp = parse_str($lttreq, $output);
if ( array_key_exists("access_token", $output)){
$this->logger->info("Facebook-app: Successfuly generated long_time_token");
return $output["access_token"];
}else {
$this->logger->err("Facebook-app: generating oauth long_time_token failed \n".$lttreq);
return false;
}
}
some later i use this token for background processes to post on the users wall and them all work fine
now i also want to notificate the user like that :
public function notifyUser($message,$facebookClientId,$token){
$appsecret_proof= hash_hmac('sha256', $token, $this->facebookOptions["secret"]);
$req_body = array(
"access_token"=>$token,
"appsecret_proof"=>$appsecret_proof,
"href"=>"/index",
"template"=>$message,
"ref"=>"post"
);
$query = http_build_query($req_body);
$url = "https://graph.facebook.com/".$facebookClientId."/notifications?".$query;
$lttreq = file_get_contents($url);
return $lttreq;
}
but when i try to notify the user i always get empty data back
when i open the url in browser with all parameters facebook returns the same
{
data: [ ]
}
so i have no idea whats going on,when i look on SO i only find about people posting to sites but i want to notify the user itself
thanks for any help
First, from the Facebook docs:
Currently, only apps on Facebook.com can use App Notifications.
Notifications are only surfaced on the desktop version of
Facebook.com.
Also, an App Token is needed, not a User Token.
Btw, file_get_contents is very bad, use CURL for Facebook. May be another reason why it does not work. A basic example of using CURL with the Facebook API: http://www.devils-heaven.com/extended-page-access-tokens-curl/
Additional Info: I recently wrote a blogpost about App Notifications, it is in german but the small code part may be interesting for you: http://blog.limesoda.com/2014/08/app-notifications-facebook-apps/
Related
I have an android client, that initiate log-in to facebook, receives access token and other details about the profile.
The android client passes the access_token and details to the Server (PHP).
Both have facebook sdk installed.
When I initiate a FacebookRequest from the PHP, for example '/me/' It's working.
BUT when I initiate a (friends who have installed the APP) FacebookRequest from the PHP
'/me/friends'. I get "null".
When I use the graph explorer provided by facebook the result is :
{
"data": [
]
}
Additional information for the helpers:
The app contains only two users at the moment, which are friends on facebook.
Those users are both administrators of the app.
Currently the app is not live\published.
We haven't "Start a Submission" in Stats and Reviews as suggested somewhere.
We asked for the permission 'user_friends'.
Since everything in stack overflow requires reputation,
This is how the permissions look like:
http://i.stack.imgur.com/kURwB.png
Thanks
EDIT:
OK I added two test users, Made them friends of each other, and /me/friends through graph explorer is working for them.
BUT why doesn't it work for non-test-users?
Okay,
So apparently Facebook had a problem providing new Access Tokens.
Don't know why, but it provided the same access token, for new Log-Ins.
Now that they fixed that here is a Handy function that I wrote in PHP that will let users
Parse Facebook responses, this might come in hand since there is NOTHING explained over the Docs, Google, StackOverFlow.
use Facebook\FacebookSession;
use Facebook\FacebookRequest;
function find_my_facebook_friends($access_token){
require_once 'facebook-php-sdk-v4-4.0-dev/autoload.php';
FacebookSession::setDefaultApplication('app_key','secret_key');
$session = new FacebookSession($access_token);
$request = new FacebookRequest(
$session,
'GET',
'/me/friends'
);
$response = $request->execute();
$graphObject = $response->getGraphObject()->asArray();
return $graphObject;
}
Usage:
include_once 'path/to/function.php';
//You wanna use it, just so the PHP file contains your app_key, secret_key Wont be exposed.
$access_token = isset($_POST['access_token']) ? $_POST['access_token'] : NULL;
$facebook_object = find_my_facebook_friends($access_token);
for($i = 0 ; $i < count($facebook_object['data']) ; $i++){
$id = get_object_vars($facebook_object['data'][$i]);
echo $id['id'];
echo $id['name'];
//You don't have to echo, you could handle those fields as you wanted.
}
This function refers to a Mobile Client passing his Log In User's access token to the server.
I hope this will save you lots of time!
I am currently developing in social engine in zend framework.
Social engine has this built in plugin that let you stay connected to facebook even you are logged out to facebook site. So when you're posting status in my social engine site, it will still be posted on your wall even you're not logged in facebook site(I mean here in facebook.com) but I don't know how to do this in my custom widget in social engine that's why I thought I should just use the Facebook SDK.
I was successful using Facebook SDK but the problem is that it asks the user to login every time the script detects that the user is not logged in facebook.com .
How to solve this??
I can actually retrieve the user details like openid, facebookemail. Yeps, that's only the thing I know :(
I've developed same kind of application in Zend-Framework. I've used Facebook/PHP-SDK with oAuth 2.0.
In this case you need to save access tocken in your database for the particular user. and with that access token you can get any data as well as post to. Yes for that you need to grant necessary permission from the user for your Facebook APP.
Here is the two function that I've used in my application to fetch the access token , extended it and store in the database.
/**
* Getting User Acess Tocken , extended it and save it in to database......
*/
public function getAccessToken($user_id,$fb_account_id)
{
$access_token=$this->facebook->getAccessToken();
$extended_access_token=$this->getExtendedAccessToken($access_token);
/**
* To save Access tocken and other necessary option
*/
$usr_bus_model = new Application_Model_UserBusinessAccounts;
$usr_bus_model->loadAccount($user_id,'Facebook',(int)$fb_account_id);
$usr_bus_model->details=$extended_access_token;
$usr_bus_model->save();
return $extended_access_token;
}
/**
* Exrending User Acess Tocken.....
*/
public function getExtendedAccessToken($access_token)
{
$token_url="https://graph.facebook.com/oauth/access_token";
$params=array('client_id'=>self :: appId,'client_secret'=>self :: appSecretId,'grant_type'=>'fb_exchange_token','fb_exchange_token'=>$access_token);
$response = $this->curl($token_url,$params);
$response = explode ('=',$response);
$response = explode ('&',$response[1]);
$response = $response[0];
return $response;
}
Hope it helps.
I'm using http://wordpress.org/extend/plugins/simple-twitter-connect/ to use twitter on a wordpress blog. But I've a problem with request tokens.
Here's my code:
$to = new TwitterOAuth($options['consumer_key'], $options['consumer_secret']);
$tok = $to->getRequestToken();
function getRequestToken() {
$r = $this->oAuthRequest($this->requestTokenURL());
$token = $this->oAuthParseResponse($r);
$this->token = new OAuthConsumer($token['oauth_token'], $token['oauth_token_secret']);
return $token;
}
But after clicking on the sign in button, Twitter returns this:
'Whoa there!
There is no request token for this page. That's the special key we need from applications asking to use your Twitter account.'
The URL is https://twitter.com/oauth/authenticate?oauth_token=
Presumably the missing value is the problem.
I'm hoping to then allow the logged in user to tweet from the site, yet I haven't even gone near that with the above problem.
Any ideas??
Haves you tried logging into Twitters Developer site (https://dev.twitter.com/) to get your access token? If not you need to create an app which will allow access from your site to twiiter. The Directions on the developer site are pretty easy to follow.
I have started off by reading Displaying Facebook posts to non-Facebook users which is of some use but I cannot believe it is this difficult to get a public feed from Facebook.
The page I want a feed from is public, you do not need to be logged into get to it.
Am I right in presuming that I need an access_token to get to this information, attempting to access the URL without results in an OAuth error.
So the flow should be like this (massively, overly complex):
Authenticate using a user (what if the user isn't on Facebook?)
Some complex OAuth nonsense - just to read the feed, I do not even want a like button or post to wall functionality
Get the feed using a PHP request to the correct URL with the user's access_token
Render the feed
Assuming the user isn't on Facebook, what do you do, use a generic app to get the feed?
Hardcode an auth request to Facebook using my generic app's ID and secret
Some complex OAuth nonsense
Get the feed using a PHP request to the correct URL with the app's access_token
Render the feed
Oh no, the auth has expired, re-auth and capture this new access_token for use in future requests.
This seems really complex for no reason other than Facebook wants to know EVERYTHING that is going on, it'd be easier to do a cURL and scrape the content from the public URL using XPath.
Any help on this would be great.
Thanks,
Jake
EDIT
An edit to show this is not an exact duplicate.
I had this working with an access_token in place, but now it fails, the token has expired and I can no longer use it to obtain information from the public wall.
I attempted to extend the expiration date of this token using the methods mentioned in other posts but this didn't work and the expiration was not extended - we are now here, with an invalid token and no further along.
It seems that the manual process of having to approve the OAuth request means that it is impossible to programatically get the feed of a public page.
Two years later, you can programmatically do this with a Facebook App (an example using PHP and Slim): https://developers.facebook.com/apps/
$base_api="https://graph.facebook.com/";
$client_id="XXXXXX";
$app_secret="XXXXXX";
//get a profile feed (can be from a page, user, event, group)
$app->get('/feed/:profileid/since/:start_date', function ($profile_id,$start_date) {
$start_time=date('m/d/Y h:i:s',$start_date);
$request = new FacebookRequest(
getSession(),
'GET',
'/'.$profile_id.'/feed?since='.$start_time
);
$response = $request->execute();
$graphObject = $response->getGraphObject();
//do something with $graphObject
});
function getSession(){
$session = new FacebookSession(getAccessToken());
return $session;
}
function getAccessToken(){
global $base_api, $client_id, $app_secret;
$url=$base_api."oauth/access_token?client_id=".$client_id."&client_secret=".$app_secret."&grant_type=client_credentials";
$str = file_get_contents($url);
$token = str_replace ( "access_token=" , "" , $str );
return $token;
}
I have some success with reading in the direct feed without tokens etc.
(using magpie, simplepie or querypath or similar).
http://www.facebook.com/feeds/page.php?format=rss20&id=........
http://www.facebook.com/feeds/page.php?format=atom10&id=........
found on: http://ahrengot.com/tutorials/facebook-rss-feed/
Facebook has changed how to retrieve a public Facebook page's feed since the other answers were posted.
Check out my answer/question. It's not PHP, but it provides the URLs and process you need.
I have a client who wants their company's Facebook newsfeed/timeline to be displayed on their website. It's not a personal timeline/newsfeed, but an organisation's.
Everything I've read seems a few years old, but the upshot appears to be: Facebook wants to keep all its data on its own servers -- they don't want people exporting it, and people have been banned for trying. (As I say, this information was several years old.)
The closest current thing I've found is the Activity Feed Plugin, but that only registers other user's interactions with the site or a FB app.
Has anyone had any success exporting their public updates to an external website, or do I have to tell my client that it can't be done?
Thanks for any help!
AFAIK, it is possible, in a way. The simplest solution, but not best for your situation could be the Like Box plugin:
The Like Box enables users to:
See how many users already like this Page, and which of their friends like it too
Read recent posts from the Page
Like the Page with one click, without needing to visit the Page
Better solution: use their Graph API, however you can only read the data(as JSON), not have the stream exactly replicated on your client's website, don't expect to be able to apply the styles that facebook uses(i.e you won't be able to scrape it), you'll have to either replicate it, or create your own styles.
Now if the page is public and can be read by all, as in there are no privacy rules, then you can simply call the url with any valid access_token(can be app access_token also):
https://graph.facebook.com/<clientpagename_OR_id>/feed
or
https://graph.facebook.com/<clientpagename_OR_id>/posts
depending on what exactly you need, try the graph api explorer to check that(and also see the kind of data being returned). When there are lots of posts, there will be pagination urls, which you'll be able to notice in the explorer too.
Incase the page is not public, you'll need an access_token with the read_stream permission, hence you'll need to create a facebook app, of type website. Then get your client's page's admin to authorize the app, with read_stream permission. After that you can call the urls with the access_token that you receive after authentication and can continue reading the stream.
https://graph.facebook.com/<clientpagename_OR_id>/posts?access_token=thetoken
In this case use the PHP SDK, to simplify authentication and calling the graph api.
Important Links: Authentication Guide , Real-time-updates.
Good luck.
Edit: you do need an access token to access the feed or posts connections, but you do not necessarily need an access token to read the page object itself, as given in this documentation.
Note from the doc:
For connections that require an access token, you can use any valid access token if the page is public and not restricted. Connections on restricted pages require a user access token and are only visible to users who meet the restriction criteria (e.g. age) set on the page.
You can retrieve the organization's newsfeed using Facebook's Graph API. Timeline can't be retrieved via public API.
There is no plugin to do this. You would need to call
https://graph.facebook.com/USER_ID/home
which gives you a JSON response.
You then need to parse the JSON into a new layout on the organization's web page.
Confusingly, calling
https://graph.facebook.com/USER_ID/feed
doesn't retrieve the newsfeed, but a user's wall posts, which may or may not be what you want.
Here is a tutorial that goes through the basics of setting up a newsfeed on a website with php.
The easiest way to do this is to read the Facebook timeline RSS:
function FacebookFeed($pagename, $count, $postlength) {
$pageID = file_get_contents('https://graph.facebook.com/?ids='.$pagename.'&fields=id');
$pageID = json_decode($pageID,true);
$pageID = $pageID[$pagename]['id'];
ini_set('user_agent', 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.9) Gecko/20071025 Firefox/2.0.0.9');
$rssUrl = 'http://www.facebook.com/feeds/page.php?format=rss20&id='.$pageID;
$xml = simplexml_load_file($rssUrl);
$entry = $xml->channel->item;
for ($i = 0; $i < $count; $i++) {
$description_original = $entry[$i]->description;
$description_striphtml = strip_tags($description_original);
$description = substr($description_striphtml, 0, $postlength);
$link = $entry[$i]->link;
$date_original = $entry[$i]->pubDate;
$date = date('d-m-Y, H:i', strtotime($date_original));
$FB_feed .= $description."…<br>";
$FB_feed .= "<small><a href='".$link."'>".$date."</a></small><br><br>";
}
return $FB_feed;
}
Yes, it can be done. First register the web site at facebook's developer page. Than you can use any suitable API for interacting with FB. Sometimes ago I used SpringSocial (since I was working tightly with Spring)... You can use FB's own api which is also very useful you can read the tutorial here
It can definitely be done. You just need to get an access token through facebook and then you can access a JSON feed of posts through the facebook API.
You need to go to the facebook developer site and click on Apps at the top. Follow the steps to get an app secret and client ID. Then just put them into the following URL and it will return your access token:
https://graph.facebook.com/oauth/access_token?grant_type=client_credentials&client_id=YOUR_CLIENT_ID&client_secret=YOUR_CLIENT_SECRET
Step by step instructions here: http://smashballoon.com/custom-facebook-feed/access-token/
This document details the steps to obtain the facebook access tokens and the using the tokens to fetch FB feeds.
Example:
A live example is available in
https://newtonjoshua.com
Introduction to Graph API:
The Graph API is the primary way to get data in and out of Facebook's platform. It's a low-level HTTP-based API that you can use to query data, post new stories, manage ads, upload photos and a variety of other tasks that an app might need to do.
FaceBook Apps:
https://developers.facebook.com
Create a Facebook app. You will get an App_Id and App_Secret
Graph API Explorer:
https://developers.facebook.com/tools/explorer/{{App_Id}}/?method=GET&path=me%2Ffeed&version=v2.8
You will get an access_token which is short lived. So this will be our short_lived_access_token.
note: while creating access token select all the fb fields that you require.This will give permission to the access token to fetch those fields.
Access Token Extension:
https://graph.facebook.com/oauth/access_token?grant_type=fb_exchange_token&client_id={{App_Id}}&client_secret={{App_Secret}}&fb_exchange_token={{short-lived-access_token}}
You will get an access_token with a validity of 2 months.
Access Token Debugger:
https://developers.facebook.com/tools/debug/accesstoken?q={{access_token}}&version=v2.8
you can check check the details of the access_token.
Facebook SDK for JavaScript:
Include the below JavaScript in your HTML to asynchronously load the SDK into your page
(function (d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) {
return;
}
js = d.createElement(s);
js.id = id;
js.src = "//connect.facebook.net/en_US/sdk.js";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
Graph API:
Let's make an API call to get our FB id, profile pic, cover pic and feeds.
window.fbAsyncInit = function () {
FB.init({
appId: '{{App_Id }}',
xfbml: true,
version: 'v2.7'
});
FB.api(
'/me',
'GET', {
fields: 'id,picture{url},cover,feed',
access_token: {{access_token}}
},
function (response) {
if (response.error) {
console.error(response.error.message);
}
if (response.picture.data.url) {
profilePic = response.picture.data.url;
}
if (response.cover.source) {
coverPic = response.cover.source;
}
if (response.feed.data) {
feeds = response.feed.data;
feeds.forEach(function (feed) {
// view each feed content
});
}
if (response.feed.paging.next) {
nextFeedPage = response.feed.paging.next;
// a request to nextFeedPage will give the next set of feeds
}
}
);
};
Use the Graph API Explorer to design your query that should be entered in the 'fields' (eg: 'id,picture{url},cover,feed')
Now you can fetch your Facebook data from Facebook Graph API using your access_token.
Refer to https://developers.facebook.com/docs/graph-api/overview/
Note: Your access_token will expire in 2 months. Create a new access_token after that.