I added a Facebook comment box to my website a while ago. What I want now is to trigger some code "mail() in php" when someone adds a comment. I want my website to send an email to the user telling him/her that a visitor has left a comment on your item/page.
It was easy to do with the old comment section I created but I don't know now how to do it with FB. Is it even possible?
If yes please include a detailed answer if you don't mind since I am not that good at this :)
If you are not happy with the solution FB already provides (as scjosh explained), you can use Facebooks Javascript SDK a bit of ajax (jquery would be my favorite) to load a script with the mail() function.
First load the JS SDK (make sure you change 'YOUR_APP_ID' and the channelURL!!):
<div id="fb-root"></div>
<script>
window.fbAsyncInit = function() {
FB.init({
appId : 'YOUR_APP_ID', // App ID
channelURL : '//WWW.YOUR_DOMAIN.COM/channel.html', // Channel File
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
oauth : true, // enable OAuth 2.0
xfbml : true // parse XFBML
});
// Additional initialization code here
};
// Load the SDK Asynchronously
(function(d){
var js, id = 'facebook-jssdk'; if (d.getElementById(id)) {return;}
js = d.createElement('script'); js.id = id; js.async = true;
js.src = "//connect.facebook.net/en_US/all.js";
d.getElementsByTagName('head')[0].appendChild(js);
}(document));
</script>
more information about js sdk, the loading and the channel file can be found here. You should have an app or create an app in facebook for that reason. Information about setting up an app is here.
Next step is to load the script with the mail() per jquery:
FB.Event.subscribe('edge.create',
function(response) {
$(document).load('mail.php?response='+response);
}
);
And finally the mail.php:
if(isset($_GET['response'])) {
$msg = 'A comment was left on '.$_GET['response'];
mail('user#webpage.com','New comment',$msg);
}
Hope that helps!
If I understand you correctly, Facebook already includes integrated email communications via their website. I.E., if the Facebook user has notifications enabled for your comment threads, an email will be sent to that user upon request. The only other way to make this possible would be to hack together your own comment box and hook it with the Facebook API.
Related
I'm using the following form to allow users register to my web app through their facebook account. I have my own policy regarding Username's length, password's complexity etc. and I want to force it also on user that register through facebook, I know that I can do it in the register.php file (the Facebook php api: Verify user details according to my app's policy, see below) but then the user is already registered from facebook's perspective.
My question is, then, how can I prevent a user from being registered to my app without providing registration details which fit my app's policy?
<div id="fb-root"></div>
<script type="text/javascript">
window.fbAsyncInit = function() {
FB.init({
appId : 'MY_FB_APP_ID',
channelUrl : 'channel.html',
status : true,
cookie : true,
oauth : true,
xfbml : true
});
FB.Event.subscribe('auth.login', function(response) {
window.location.reload();
});
FB.Event.subscribe('auth.logout', function(response) {
window.location.reload();
});
};
(function(d){
var js, id = 'facebook-jssdk';
if (d.getElementById(id)) {return;}
js = d.createElement('script');
js.id = id;
js.async = true;
js.src = "//connect.facebook.net/en_US/all.js";
d.getElementsByTagName('head')[0].appendChild(js);
}(document));
</script>
<div class="fb-registration"
data-fields='[{"name":"name"},
{"name":"birthday"},
{"name":"location"},
{"name":"gender"},
{"name":"email"},
{"name":"username","description":"Username","type":"text"},
{"name":"password"}]'
data-redirect-uri= MY_DOMAIN . "register.php" >
</div>
You can make a DELETE call to /user/permissions. Since this would make the user re-auth your app, I wouldn't do this as soon as the user tries to create an invalid registration on your site. Instead, depending on your complexity, issue the DELETE call when the user has left your registration page for good.
According to the docs:
The second thing you can do is to completely de-authorize the app
making the delete call. Once this is done, anyone using your app will
have to go through the Facebook Login process as if they were a new
user. This can be effective when an explicit 'log out' function is
provided, or an option to delete in-app accounts
I tried to implement facebook login in local,i used below code in my website
<html>
<head></head>
<body>
<div id="fb-root"></div>
<script>
window.fbAsyncInit = function() {
FB.init({
appId : '{your-app-id}',
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true // parse XFBML
});
// Here we subscribe to the auth.authResponseChange JavaScript event. This event is fired
// for any authentication related change, such as login, logout or session refresh. This means that
// whenever someone who was previously logged out tries to log in again, the correct case below
// will be handled.
FB.Event.subscribe('auth.authResponseChange', function(response) {
// Here we specify what we do with the response anytime this event occurs.
if (response.status === 'connected') {
// The response object is returned with a status field that lets the app know the current
// login status of the person. In this case, we're handling the situation where they
// have logged in to the app.
testAPI();
} else if (response.status === 'not_authorized') {
// In this case, the person is logged into Facebook, but not into the app, so we call
// FB.login() to prompt them to do so.
// In real-life usage, you wouldn't want to immediately prompt someone to login
// like this, for two reasons:
// (1) JavaScript created popup windows are blocked by most browsers unless they
// result from direct interaction from people using the app (such as a mouse click)
// (2) it is a bad experience to be continually prompted to login upon page load.
FB.login();
} else {
// In this case, the person is not logged into Facebook, so we call the login()
// function to prompt them to do so. Note that at this stage there is no indication
// of whether they are logged into the app. If they aren't then they'll see the Login
// dialog right after they log in to Facebook.
// The same caveats as above apply to the FB.login() call here.
FB.login();
}
});
};
// Load the SDK asynchronously
(function(d){
var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0];
if (d.getElementById(id)) {return;}
js = d.createElement('script'); js.id = id; js.async = true;
js.src = "//connect.facebook.net/en_US/all.js";
ref.parentNode.insertBefore(js, ref);
}(document));
// Here we run a very simple test of the Graph API after login is successful.
// This testAPI() function is only called in those cases.
function testAPI() {
console.log('Welcome! Fetching your information.... ');
FB.api('/me', function(response) {
console.log('Good to see you, ' + response.name + '.');
});
}
</script>
after i login to my website , facebook login button is appering.but when i click on login button, i is showing URL error
I tried all below url to set Site URL in facebook dashboard
but still am getting same error.
am using wamp(php)
can any one help me, what is the url ia have to set as site url in facebook dashboard to it should work locally??????
Here is two solutions to run your facebook application in your localhost..
Running Facebook application on localhost
http://ankurm.com/blog/using-localhost-for-facebook-app-development/
also you have to enable curl extension in your php..
After proving your App Id for facebook , use redirect_url and set it to local address.
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.
I am trying to implement Facebook Login System into my website.
While it try to connect to facebook, I get an error from console log:
Unsafe JavaScript attempt to access frame with URL https://s-static.ak.fbcdn.net/connect/xd_proxy.php?xxxxxxxxxxxxxxxx
I am using JavaScript SDK
I added this in the body tag:
<div id="fb-root"></div>
<script>
window.fbAsyncInit = function() {
FB.init({
appId : 'xxxxxxxxxxxxxx',
status : true,
cookie : true,
xfbml : true
});
};
(function(d){
var js, id = 'facebook-jssdk'; if (d.getElementById(id)) {return;}
js = d.createElement('script'); js.id = id; js.async = true;
js.src = "//connect.facebook.net/en_US/all.js";
d.getElementsByTagName('head')[0].appendChild(js);
}(document));
</script>
Facebook Login button:
<div class="fb-login-button" data-perms="email">Login with Facebook</div>
I am testing from localhost - I have register my website on facebook develop apps (Site URL: http://localhost)
How to fix this problem? or should I use PHP SDK?
Edit: Same problem when I uploaded to server with public domain.
The error that you see there is a non-fatal error. There is no workaround for this, as your browser is advising you that it is not a great idea to load JavaScript from foreign domains. Just ignore this message and look elsewhere for bugs if your scripts do not run. Sajith is also correct that you can't debug from localhost.
See here also,
"Unsafe JavaScript attempt to access frame with URL..." error being continuously generated in Chrome webkit inspector
Be sure to have this line on the top of your page (it works for me) :
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:fb="https://www.facebook.com/2008/fbml">
It is not possible to test all Facebook integration using domain localhost. You need to place your script in any public access domain and need to update the url in developer app settings page. The security error showing from JavaScript is due to this localhost access by facebook scripts
You can only use the same domain name in which you have registered with Facebook apps.
1. You need a public domain name (www.example.com).
2. You need to register with Facebook apps.
3. Get the 2 keys from the Facebook and use in the code:
appId : 'xxxxxxxxxxxxxx',
Had this error when I implemented fileglu and it may be a CORS error since you are running off localhost. Try running on Facebook and can you replace the bottom half with the code below:
(function() {
var e = document.createElement('script');
e.src = document.location.protocol +
'//connect.facebook.net/en_US/all.js#appId=<your-app-id>&xfbml=1';
e.async = true;
document.getElementById('fb-root').appendChild(e);
}());
I also had Oauth 2.0 and custom channel enabled in my FB.init() page. See: http://fbdevwiki.com/wiki/FB.init for more information.
You can tweak your localhost machine to appear to be of the domain that facebook requires.
On linux or OSX, add an entry to /etc/hosts; on windows, edit c:\windows\system32\drivers\etc\hosts. Add an entry like this:
127.0.0.1 local-dev.mydomain.com local-dev
Where "mydomain.com" is the domain with which your FB app ID is registered.
In my case error was caused by like widget that was loaded using addthis on the site that already had FB app.
It looked like problem was in conflicting with multiple fb js-sdk.
So solution could be replace addthis facebook like wdiget by native facebook like widget.
I've also had another bug in webkit when js-sdk was not loaded. I fixed that by replacing window.fbAsyncInit by jQuery.getScript().
Eventually it fixed error "Unsafe JavaScript attempt to access frame with URL" also.
Here is example:
$.ajaxSetup({ cache: true });
$.getScript('//connect.facebook.net/en_UK/all.js', function() {
FB.init({
appId: 'your app id',
cookie: true,
xfbml: true,
oauth: true,
status: true
});
// Trigger custom event so we can use it to run init dependent actions in different places.
$(document).trigger('FBSDKLoaded');
//...
});
Is it possible for me to post a message on a given users facebook wall, if they perform a certain action on my website?
Basically, I am looking for a step by step guide to achieve this, as I have not been able to figure out how to do this via the facebook documentation.
Step 1:
Set up a new application at facebook. Enter details like your website address and domain name. Note down the api key, application id, and application secret. You can set up a new facebook application here. Note: To be able to access facebook developers dashboard you need to be a verified developer, i.e. you should either have your mobile number or credit card verified with it.
Step 2:
Set up an authentication method to check if user is logged into facebook and if facebook session exists ask for basic permissions from user. You can do this easily using PHP SDK:
$fb_sdk_path = FACEBOOK_SDK_PATH;
require_once($fb_sdk_path);
//initialize FB object
$facebook = new Facebook(array(
'appId' => FB_APP_ID,
'secret' => FB_APP_SECRET,
'cookie' => true,
'domain' => 'example.com'
));
//try to get session. if this fails then it means user is not logged into facebook
$session = $facebook->getSession();
if (!$session) {
//get facebook login url
$url = $facebook->getLoginUrl(array(
'canvas' => 1,
'fbconnect' => 0
)
);
//put login url script to redirect to facebook login page (if you want to do this)
echo "<script type='text/javascript'>top.location.href = '$url';</script>";
exit;
} else {
//try to get user details from session this will trigger the permissions dialog.
try {
$uid = $facebook->getUser();
} catch (FacebookApiException $e) {
}
}
Step 3:
Use Facebook Javascript FB.ui method to generate a post form.
<div id="fb-root"></div> <!-- don't forget to include this -->
<script src="http://connect.facebook.net/en_US/all.js"></script><!-- include fb js -->
<script type="text/javascript">
//initialize facebook
FB.init({
appId:'YOUR_APP_ID',
cookie:true,
status:true,
xfbml:true
});
//call this function on click or some other event
function post_to_profile() {
FB.ui({
method: 'feed',
name: 'title of the feed',
link: 'link on the title',
caption: 'caption to show below link, probably your domain name',
description: 'description',
picture:'picture to show',
message: 'default message. this can be edited by the user before posting'
});
}
</script>
This should be enough to get it working.
I would recommend using the Javascript API. While you can certainly do it PHP, I find all the redirects required a poor user experience. Here is how you can get started loading the javascript API. It also has an example on how to post to a wall.
http://developers.facebook.com/docs/reference/javascript/
Posting to someones wall (yours or a friends) via javascript uses the FB.ui call.
http://developers.facebook.com/docs/reference/javascript/FB.ui/
Taken directly from http://developers.facebook.com/docs/guides/web/
<html>
<head>
<title>My Great Website</title>
</head>
<body>
<div id="fb-root"></div>
<script src="http://connect.facebook.net/en_US/all.js">
</script>
<script>
FB.init({
appId:'YOUR_APP_ID', cookie:true,
status:true, xfbml:true
});
FB.ui({ method: 'feed',
message: 'Facebook for Websites is super-cool'});
</script>
</body>
</html>
This will open a prompt to post onto the currently logged in user's wall.
The getting started guide to the Graph API should help you. Specifically, you'll be dealing with the post object (that page contains a note about publishing, scroll down to the "Publishing" section). You'll also need the publish_stream permission, which you can learn more about here. And since you're doing this in PHP, the official Facebook PHP SDK will be of interest to you as well.
Here's the general flow
Register an app at developers.facebook.com
Create page w/ this link to this page: https://www.facebook.com/dialog/oauth?
client_id=164837516907837&
type=user_agent&
scope=email,read_stream,user_videos,friends_videos,user_about_me,offline_access&
redirect_uri=http://www.facebook.com/connect/login_success.html
Save the user x's oath token that is returned from step2
Via API call post to user x's wall
To reference: http://thinkdiff.net/facebook/graph-api-iframe-base-facebook-application-development/
Various steps involved
1)Register App at facebook
developers
2)Get PHP SDK of Facebook
3)Get Offline access from user
so that you can post in users wall
without his permission(Use
accordingly)
4)Save the access token given by
facebook for the user
5)Using the access token by php
SDK post into the wall
Check this question it may be of some help
Publishing To User's Wall Without Being Online/Logged-in - Facebook Sharing Using Graph API