Suggest Page to friends using PHP-SDK - facebook

How to implement "Suggest MY-PAGE to friends" using PHP-SDK or using Javascript SDK?

First you need the Facebook SDK bundle that contains base_facebook.php, facebook.php and fb_ca_chain_bundle.crt . You will also need fbmain.php and config.php .
Next you should have a file (e.g postToWall.php) that includes fbmain.php
<?php
include_once "fbmain.php";
?>
An example of postToWall.php file.
<html>
<body id="my_body">
<div id="fb-root"></div>
<script>
window.fbAsyncInit = function() {
FB.init({
appId: '<?php echo $facebook->getAppID() ?>',
cookie: true,
xfbml: true,
oauth: true
});
FB.Canvas.setAutoGrow();
};
(function() {
var e = document.createElement('script'); e.async = true;
e.src = document.location.protocol +
'//connect.facebook.net/en_US/all.js';
document.getElementById('fb-root').appendChild(e);
}());
</script>
<?php
if ($me)
{
$params = array('message' => "message here",
'picture' => "picture hyperlink here",
'name' => "name here",
'link' => "facebook page hyperlink here",
'description' => " description here"
);
$status = $facebook->api('/me/feed', 'POST', $params);
if (isset($status['id']))
{
//do something
}
}
?>
</body>
</html>
Credits to my tutor, Mr Zen Leow

The earlier solution I have posted is using the PHP SDK method.
Using JavaScript SDK, you can have a HTML button using onclick attribute to call a function.
<input type="button" value="Share" onclick="share();"/>
Inside share function, the method property is compulsory and the other properties (link, picture, name, caption, description) are optional. The value "feed" in method property refers to feed dialog which you need, there are other values for method property such as "apprequests" (Request Dialog) and "send" (Send Dialog). For more information, check out http://developers.facebook.com/docs/reference/dialogs/
<script>
function share()
{
var obj = {
method: "feed",
link: "Facebook page hyperlink",
picture: "Picture hyperlink",
name: "Title",
caption: "A short caption right below the title",
description: "Description"
};
function callback(response) {
document.getElementById('msg').innerHTML = "Post ID: " + response['post_id'];
}
FB.ui(obj, callback);
}
</script>
The difference between PHP SDK and JavaScript SDK
For PHP SDK, the default message specified in postToWall.php will be posted straight to the user's wall upon clicking the share button. You have to redirect user to postToWall.php first and then redirects him/her back to your application page.
For JavaScript SDK, a window will pop up upon clicking the share button and user will be able to input their own message before he/she sends it. No additional redirection will be needed after sending as user is still on the same page.
P.S.: I'm still learning Facebook and PHP at the moment, so do correct me if I am making any mistake haha. Thanks =)

Related

facebook - how to get user id with phpsdk and js sdk

I'm implenting my fb app and it's connected to its own fb fanpage. I need to get a users info like username, id etc but when I click on my "Facebook authenticate" link, I end up going to a blank white page?
You can view my code in here: http://codepad.org/f0Tuh63v
error_reporting(E_ALL);
ini_set('display_errors', true);
require 'facebook/facebook.php';
$facebook = new Facebook(array(
'appId' => '1',
'secret' => '2',
));
// See if there is a user from a cookie
$user = $facebook->getUser();
if ($user) {
try {
// Proceed knowing you have a logged in user who's authenticated.
$user_profile = $facebook->api('/me');
print_r($user_profile);
} catch (FacebookApiException $e) {
echo '<pre>'.htmlspecialchars(print_r($e, true)).'</pre>';
$user = null;
}
}
else{
$loginUrl = $facebook->getLoginUrl(
array('scope' => 'user_about_me,user_birthday,email,publish_actions,offline_access,user_hometown,user_location',
'redirect_uri' => "https://domain.net/intro.php"
)
); // end of array
}
?>
<!DOCTYPE html>
<html xmlns:fb="http://www.facebook.com/2008/fbml">
<body>
<?php if ($user) { ?>
Your user profile is
<pre>
<?php print htmlspecialchars(print_r($user_profile, true)) ?>
</pre>
<?php } else { ?>
Facebook authenticate
<?php } ?>
<div id="fb-root"></div>
<script>
window.fbAsyncInit = function() {
FB.init({
appId: '<?php echo $facebook->getAppID() ?>',
cookie: true,
xfbml: true,
oauth: true,
status: true
});
FB.Event.subscribe('auth.login', function(response) {
//window.location.reload();
});
FB.Event.subscribe('auth.logout', function(response) {
//window.location.reload();
});
};
(function() {
var e = document.createElement('script'); e.async = true;
e.src = document.location.protocol +
'//connect.facebook.net/en_US/all.js';
document.getElementById('fb-root').appendChild(e);
}());
</script>
</body>
</html>
It's also here http://codepad.org/f0Tuh63v
What am I doing wrong?
Also is there a way to get the FB user id without using phpsdk or the js sdk? Or do I have to use these plugins?
I cannot see what's wrong with your code. But, If you are using Javascript, I can tell you an alternative for getting authenticated and then getting the info you require.
I used the following code behind my button, which authenticated my Facebook app and then redirected the user to my website. It worked for me.
<a class="fb-login-button" align="center" target="_blank" href="https://www.facebook.com/dialog/oauth?client_id=CLIENT_ID&response_type=token&scope=PERMISSION_1,PERMISSION_2&redirect_uri=YOUR_WEBSITE"> TEXT </a>
Then I extracted the token which was returned in the redirected URL.
var url_t; // Get the redirected URL.
access_token = url_t.split('=')[1].split('&')[0];
Then using the access token I sent the HTTP request for getting the required data. I used GRAPH API provided by facebook. For eg: For getting the first name of the user:
var xhr = new XMLHttpRequest();
var f_url_new = "https://graph.facebook.com/fql?q=SELECT%20name%20FROM%20user%20WHERE%20uid%20=%20me()&access_token=" + access_token;
xhr.open("GET", f_url_new , true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
obj1 = JSON.parse(xhr.responseText);
var str = obj1.data[0].name.toString();
var n=str.split(" ");
document.getElementById("name").innerText = n[0];
}
}
xhr.send();
Hope it gives you some idea with regards to the alternatives. This is not the correct answer to your question, but can help in the thought process.

Get user basic information using facebook Login button plugin?

Here I am using Facebook Login button plugin and javascript sdk
I am able to successfully login and logout by using above.
When a first time user has gone through authentication process I need to store user basic information i.e. Facebook login name, email in my database.
Please suggest how I can do this.
<p><fb:login-button autologoutlink="true"></fb:login-button></p>
<div id="fb-root"></div>
<script>
window.fbAsyncInit = function () {
FB.init({ appId: '123456', status: true, cookie: true,
xfbml: true
});
};
(function () {
var e = document.createElement('script');
e.type = 'text/javascript';
e.src = document.location.protocol +
'//connect.facebook.net/en_US/all.js';
e.async = true;
document.getElementById('fb-root').appendChild(e);
} ());
</script>
Subscribe to the event auth.login. If you do this, Facebook will call your handler after a login as happened.
In that handler, use FB.api to call the Graph API to get any information you desire. For example calling /me as shown in the second example will get you basic information about the logged in user.
Now you have all the data in JavaScript. To send that up to your server, do a plain old XMLHttpRequest/AJAX request. Your JavaScript library probably makes this easy -- in jQuery this is jQuery.ajax() -- but worst case you can use XHR directly.
Now you have the data on your server and you can do whatever you want, like store it in the database. If you only want to store the data once, just check that you haven't already stored info about that user ID yet.
It's also possible to use a combination of PHP SDK and JS SDK, with the latter performing the login and the former storing data on the server. Something like:
<?php
require_once 'config.php';
require_once 'lib/facebook.php';
$facebook = new Facebook(array(
'appId' => FB_APP_ID,
'secret' => FB_APP_SECRET,
));
?>
<!DOCTYPE html>
<html xmlns:fb="http://www.facebook.com/2008/fbml">
<body>
<div id="fb-root"></div>
<script>
window.fbAsyncInit = function () {
FB.init({
appId:'<?php echo $facebook->getAppID() ?>',
cookie:true,
xfbml:true,
oauth:true
});
FB.Event.subscribe('auth.login', function (response) {
window.location = "showUser.php"; //redirect to showUser.php on Login
});
FB.Event.subscribe('auth.logout', function (response) {
window.location.reload();
});
};
(function () {
var e = document.createElement('script');
e.async = true;
e.src = document.location.protocol +
'//connect.facebook.net/en_US/all.js';
document.getElementById('fb-root').appendChild(e);
}());
</script>
<div class="fb-login-button" data-show-faces="true" data-width="200"
data-max-rows="1"></div>
</body>
</html>
And in showUser.php you have something like:
<?php
#showUser.php
require_once 'config.php';
require_once 'lib/facebook.php';
$facebook = new Facebook(array(
'appId' => FB_APP_ID,
'secret' => FB_APP_SECRET,
));
$user = $facebook->getUser();
if($user)
{
if ($user) {
try {
// Proceed knowing you have a logged in user who's authenticated.
$user_profile = $facebook->api('/me');
var_dump($user_profile); //You can now save this data
} catch (FacebookApiException $e) {
echo '<pre>'.htmlspecialchars(print_r($e, true)).'</pre>';
$user = null;
}
}
}
?>
There's a hole in that solution -- this means the user can make up any information he wants and post an XHR back to my server. The server is going to need to check with Facebook directly.
//very simple just change this line
fb:login-button autologoutlink="true"
//with this one
fb:login-button autologoutlink="true" onlogin='your_ajax_fun_that_store_in_db()'
function your_ajax_fun_that_store_in_db(){
FB.api('/me', function(response) {
$.post( "ajax/store_user_info.php",response, function( data ) {
//write you js code here !
//you can use the (response) from facebook directly in your store_user_info.php as it will be sent in POST array
});
});
}
//last thing when you face such a problem the first thing to do is to go back to facebook reference of fun.

Redirect after clicking on the Facebook login button, even if already logged in Facebook

I have the standard Facebook login button on my homepage and I don't want people to automatically log into my site with their Facebook account, only if the user clicks the login button.
If the user is not logged in Facebook, a popup will appear asking him his credentials and he will be redirected to loggedin.html after that.
<div id="fb-root"></div>
<fb:login-button perms="email"></fb:login-button>
<script>
window.fbAsyncInit = function() {
FB.init({
appId : 'xxxxxxxxxxxx',
status : true,
cookie : true,
xfbml : true
});
FB.Event.subscribe('auth.login', function() {
window.location = "loggedin.html";
});
};
(function() {
var e = document.createElement('script');
e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js';
e.async = true;
document.getElementById('fb-root').appendChild(e);
}());
</script>
If the user is already logged in Facebook, when he clicks the button the popup appear and disappear right away, I am OK with that. But the user is not redirected to loggedin.html. How can I do that ?
If you use the PHP SDK, you can use the following code:
require_once 'path/to/facebook.php';
define('A_ID', '*YOUR APP ID*');
define('A_SECRET', 'YOUR APP SECRET');
$facebook = new Facebook(array('appId' => A_ID, 'secret' => A_SECRET, 'cookie' => true));
$userId = $facebook->getUser();
if (!$userId):
?>
<!-- HTML to show if the $userId isn't available (user isn't logged in) -->
<?php
else:
?>
<!-- HTML to show if the $userId is available (user is logged in)-->
<?php
endif;
Ideally you should use the PHP SDK as it gives you more control over the data and the way it is shown, than using the JS SDK to insert data.
Facebook have a reference for the PHP SDK here: developers.facebook.com/docs/reference/php/
The JavaScript SDK reference is here: developers.facebook.com/docs/reference/javascript/
I had the same problem. I solved it by using a regular link instead of the thingy and adding a click handler to this href with the facebook FB.login javascript function
http://developers.facebook.com/docs/reference/javascript/FB.login/
Within the different responses I could handle the corresponding Ajax things.

Detect Like with Facebook JavaScript API + iFrame

Building an app with the Facebook JavaScript API that will embedded into a page using the new iframe method.
I want to detect if they have liked the current page. Usually I would use print_r($_REQUEST) in PHP but that doesn't seem to work when using an iframe.
There is also this option: http://developers.facebook.com/docs/reference/fbml/visible-to-connection/ but it says its deprecated and I have never liked this method as its fairly hacky.
What is the way t do it now? Prefer to use XFBML + JavaScript API but can use PHP if required.
We've done this several times, and it seems to work pretty well. It uses XFBML to generate a Like Button widget and the JS SDK to render XFBML and subscribe to Facebook events. Code sample below:
edit: Since you're looking to detect if the user is a fan when the page loads, and FB deprecated the feature to let you get it directly from them when the canvas is loaded by passing fb_page_id to the address query string, you'll need an application install for the user to test their fan-dom of your page. It certainly adds a lot of friction to your application, but it is what it is for now - I guess.
<?php
require 'facebook.php';
// Create our Application instance (replace this with your appId and secret).
$facebook = new Facebook(array(
'appId' => 'YOUR APP ID',
'secret' => 'YOUR APP SECRET',
'cookie' => false,
));
try
{
$session = $facebook->getSession();
if (empty($session['uid']))
{
throw new Exception("User not connected to application.");
}
$is_fan = $facebook->api(array(
'method' => 'fql.query',
'query' => "SELECT uid, page_id FROM page_fan WHERE uid = {$session['uid']}"
));
if (false == $is_fan || count($is_fan) == 0) // 0 results will be returned if the user is not a fan
{
$is_fan = false;
}
else
{
$is_fan = true;
}
}
catch (FacebookApiException $e)
{
/**
* you don't have an active user session or required permissions
* for this user, so rdr to facebook to login.
**/
$loginUrl = $facebook->getLoginUrl(array(
'req_perms' => 'user_likes'
));
header('Location: ' . $loginUrl);
exit;
}
?>
<html>
<head>
</head>
<body>
<? if (empty($is_fan)): //user is not a fan. ?>
<fb:like href="http://www.facebook.com/your-facebook-page"
show_faces="true"
width="400">
</fb:like>
<? else: ?>
Yay! You're a fan!
<? endif; >?
<div id="fb-root"></div>
<script src="http://connect.facebook.net/en_US/all.js" type="text/javascript">
</script>
<script type="text/javascript">
FB.init({
appId: '<?= FB_APP_ID; ?>',
cookie: true,
status: true,
xfbml: true
});
// Subscribe to the edge creation event, from Facebook
FB.Event.subscribe('edge.create', function(response)
{
alert("Congratulations! We are so excited that you are a fan now! woot!")
});
</script>
</body>
</html>
okay, finally got got everything formatted with straight markdown. that wasn't painful at all.. (sike) :|

How to get the user email address in Facebook (Facebook Connect or Graph API)?

I previously have an FBML application in Facebook and now change to an IFrame application in FB, using the graph API. (under the same name, same game account. Just switch from FBML to iFrame).
I had a list of people with Extended Permission accepted for email. Since I change to IFrame, I can get their email... by what the API is told.
However, here is the problem.
1) When it was in FBML, I don't have their email. Only with their email permission. (that's what I was bounded)
2) I can get the user's email when they login and visit my application
3) However, I cannot get the user's email when they don't visit my application. Because some of them may not come back but I want to tell them about the update.
4) I tried to run the application using the email address I register for the application (i.e. the developer account), but still, I cannot retrieve their emails.
It seems that the application can only get the current login user. I cannot get their email even I'm the admin.
Is there any way I can do that?
For example:
If a user 12345678 and go to my application, i can run this can get his email:
$fql = "select email from user where uid=12345678";
Obviously, that user cannot run and get information for user 23456.
e.g. $fql = "select email from user where uid=23456"; <--- Fail
So, here is the problem come. I have thousands of people who previously signed up and accept the extended permission, how can I get their emails now?
I cannot run this...
$fql = "select email from user where uid=1000001";
$fql = "select email from user where uid=1000002";
$fql = "select email from user where uid=1000003";
// assum 1000001 ... 1000003 are those users.
I tried to login facebook using my dev account and do that, but, still it won't work.
Appreciate if anyone has the solution. thanks.
The idea is to get the user's email when he logs in, then store it in your own database for future reference.
You can get user email address and details in Facebook (Facebook Connect or Graph API)
<?php
require '../src/facebook.php';
$facebook = new Facebook(array(
'appId' => '344617158898614',
'secret' => '6dc8ac871858b34798bc2488200e503d',
));
// See if there is a user from a cookie
$user = $facebook->getUser();
if ($user) {
try {
// Proceed knowing you have a logged in user who's authenticated.
$user_profile = $facebook->api('/me');
} catch (FacebookApiException $e) {
echo "FacebookApiException";
echo '<pre>'.htmlspecialchars(print_r($e, true)).'</pre>';
$user = null;
}
}
?>
<!DOCTYPE html>
<html xmlns:fb="http://www.facebook.com/2008/fbml">
<body>
<?php if ($user) { ?>
Your user profile is
<pre>
<?php print htmlspecialchars(print_r($user_profile, true)) ?>
</pre>
<?php } else { ?>
<div class="fb-login-button" data-scope="email,user_checkins">
Login with Facebook
</div>
<?php } ?>
<div id="fb-root"></div>
<script>
window.fbAsyncInit = function() {
FB.init({
appId: '<?php echo $facebook->getAppID() ?>',
cookie: true,
xfbml: true,
oauth: true
});
FB.Event.subscribe('auth.login', function(response) {
window.location.reload();
});
FB.Event.subscribe('auth.logout', function(response) {
window.location.reload();
});
};
(function() {
var e = document.createElement('script'); e.async = true;
e.src = document.location.protocol +
'//connect.facebook.net/en_US/all.js';
document.getElementById('fb-root').appendChild(e);
}());
</script>
</body>
</html>
First, make sure that you include email in the scope of permissions like so:
https://www.facebook.com/dialog/oauth?client_id=595603433841467&redirect_uri=http://127.0.0.1:8000/faceb_login/&scope=email
Next retrieve the oauth token as documented elsewhere. Then, to actually retrieve a person’s email, you can make the following request:
https://graph.facebook.com/1162321772?fields=email&access_token=XXXXXXXXXXXXXXXXXXXXXX...
The documentation for the graph api is here:
https://developers.facebook.com/docs/graph-api/using-graph-api