Facebook deauthorize my app - php

Can I use Facebook PHP SDK to deauthorize my app for a particular user, basically I like to have a toggle so the user can link or unlink their facebook account to my site, I have the link part working, now just need the unlink part.
Thanks

Now Graph API has a way to do this: https://developers.facebook.com/docs/reference/api/user/#permissions
Delete
You can de-authorize an application entirely, or just revoke a specific permission on behalf of a user by issuing an HTTP DELETE to USER_ID/permissions or USER_ID/permissions/PERMISSION_NAME
respectively. This request must be made with a valid user access_token or an app access token for the current app.

Using the graph API, this works fine:
$ret = $this->Facebook->api('/me/permissions', 'DELETE');

Not using the currently supported Graph API: as currently setup there is no interface in the Graph API (or even the legacy APIs) to deauthorize an application. The user has to explicitly choose to do it themselves through the Facebook settings pages.
However...
The legacy REST api has http://developers.facebook.com/docs/reference/rest/auth.revokeAuthorization/, which SOUNDS like it does what you want.
Let me know if that works for you: I'm curious.

Please note Facebook in the process of deprecating the REST API, and have adding equivalent support to the Graph API User object for "auth.revokeAuthorization" method.
For delinking or deauthorization the user by making app call:
$user_id = $this->facebook->getUser();
$access_token=$this->facebook->getAccessToken();
$result = $this->facebook->api(array(
'method' => 'auth.revokeAuthorization',
'uid' =>$user_id,
'access_token'=>$access_token
));

Using the JS API an app can be deauthorized like this:
FB.api('/me/permissions', 'DELETE', function(res){
if(res === true){
console.log('app deauthorized');
}else if(res.error){
console.error(res.error.type + ': ' + res.error.message);
}else{
console.log(res);
}
});
Or delete a specific permission:
FB.api('/me/permissions/user_birthday', 'DELETE', function(res){
if(res === true){
console.log('permission removed');
}else if(res.error){
console.error(res.error.type + ': ' + res.error.message);
}else{
console.log(res);
}
});

If you go to Facebook Developer, then select your application, then under the "Advanced" menu there is a field called "Deauthorize Callback". Set this as a URL on your domain which is pinged when a user deauthorizes themselves, there is some documentation on the format of the data it requests here.

Related

Using Google's API through laravel/hybridauth

I want to create an app that uses Google+ APIs through hybridauth.
I'm using atticmedia/anvard version of hybridauth, that is already configured with Google's clientID and secretKey that have been generated through Google Developer Console (I have inserted these info inside the hybridauth.php file inside the config folder of laravel). I have setted the scope too (as Google suggest).
"scope" => "https://www.googleapis.com/auth/plus.login https://www.googleapis.com/auth/userinfo.email",
I do the following in a laravel route:
if (!$hybridauth->isConnectedWith('Google')) {
$adapter = $hybridauth->authenticate('Google');
}
else {
$adapter = $hybridauth->getAdapter('Google');
}
$profile = $adapter->getUserProfile();
Till now, everything goes well. The profile is correctely printed using the var_dump() function. So I can assume I am logged in. Now I want to make a call to Google APIs (for example this). In the same laravel route, after printing the user's profile, i do the following:
$answer= $adapter->api()->api('/people', 'get', array(
'query' => 'Google'
));
As shown in this page, I can use the api() method to do the call. But the only result I can print is "NULL". I suspect that somehow the request is not correct, but I tryed almost anything, and I have not found yet a "real" example of Google API in conjuction with laravel/hybridauth.
When calling $adapter->api in hybridauth to access Google APIs, you must use the full HTTP URL request.
$answer= $adapter->api()->api('https://www.googleapis.com/plus/v1/people/me');
For other services, such as Facebook, you don't need to
$answer= $adapter->api()->api('/me');
I'm using Laravel 4.2.11 and hybridauth dev-master
Reference: http://hybridauth.sourceforge.net/userguide/tuts/advanced-access-google-api.html

graph api notifications returns empty data

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/

This does not let the app post to Facebook php

I am creating a Facebook app through php. I am using the following code for users to add the app:
$config = array();
$config['appId'] = '532241193565136';
$config['secret'] = '19de17575ad3d245c8cc32f5b623e310';
$config['cookie'] = true;
$config['fileUpload'] = true; // optional
$fb = new Facebook($config);
$user = $fb->getUser();
$loginUrl = $fb->getLoginUrl(
array(
'scope' => 'publish_actions'
)
);
This should allow users to post to Facebook through the app. The problem I'm having is the Permissions popup does not allow users to select the type of Publish Permission - Public, Custom, Only Me etc. I always get This does not let the app post to Facebook
Posts are being added to the Facebook Page but obviously they are private to the user who added the post.
Not sure if I'm missing something here...
Update:
I've tried deleting the application and adding a new, did not make any difference though.
Update 2:
I've just tried using the application from an Admin User of the Page...The following permissions have not been approved for use and are not being shown to people using your app: publish_actions
Information Update:
Just in case someone stumbles on this question. Facebook's Review Guidelines states that "The review time estimate will range between 7 to 14 business days." Always important to consider these delays :)
You're missing nothing here. From v2.0 onwards, the permissions other than public_profile, email and the user_friends need to the submitted for review before you can make your app live; until then, only the testers/admin/developers of the app will be able to test app with those permissions.
Since you are the admin of your app, you can test the publishing but-
it will be visible to you or other admins/testers/developers only
you'll not see the provacy setting option because that does not makes sense
For the login submission (after your app is ready to be live) see this link.
If your submission was rejected you can post using the Feed Dialog, the Requests Dialog or the Send Dialog. Your app does not need to request the publish_actions permission for that. It's an alternative. (see the publish_actions permission reference).
function publish() {
FB.api('/<albumid>/photos', 'POST',
{"url": 'example.com/image.jpeg',
"caption": 'text'
},
function(response) {
if (!response || response.error) {
// Error trying post method - now trying a feed dialog
FB.ui({message: text,
method: 'feed',
link: 'example.com',
picture: 'example.com/image.jpeg',
caption: text,
}, function(response){
//successful feed dialog without publish_actions permission
});
} else {
//successful post with publish_actions permission
}
});
}

Can I use the Facebook PHP SDK in Spotify apps?

I need to be able to post information from my application to the user's timeline. Now, the only way I know how to do that is with the Facebook PHP SDK. The thing is, since I use the standard JavaScript way to connect with Facebook's login, when I try to get the user id with the PHP SDK, it says it's 0. Is there any way I can use the PHP SDK, or is there just no way to post to Facebook from a Spotify application?
Also, can I use the PHP SDK as well for logging in instead of the standard code that looks like this:
function facebook(){
auth.authenticateWithFacebook('119914501490688', ['user_about_me', 'user_checkins'], {
onSuccess : function(accessToken, ttl) {
console.log("Success! Here's the access token: " + accessToken);
},
onFailure : function(error) {
console.log("Authentication failed with error: " + error);
},
onComplete : function() {}
});
}
You may need to make sure that Spotify will allow access to the Facebook API endpoints by adding them to your app manifest file. See "Talking to the Outside World" in the tutorial at https://developer.spotify.com/technologies/apps/tutorial/

Displaying a Facebook newsfeed/timeline on a website

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.

Categories