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
Related
I'm trying without success for 2 days now to retrieve page feed with Facebook PHP SDK. Details :
I got a user, who is page admin
I created an app (not public, is that a problem?)
I use an AJAX called PHP script to try to retrieve feed, because I don't want to pollute main page loading.
All stuff given on PHP SDK doc is related to manual login and access token retrieval.
I Managed to retrieve a user token using the 2-scripts code (login, and callback), with manage_pages speical grant require :
$fb = new Facebook\Facebook([
'app_id' => $app_id,
'app_secret' => $app_secret,
'default_graph_version' => 'v2.2',
]);
$helper = $fb->getRedirectLoginHelper();
$permissions = ['manage_pages']; // Optional permissions
$loginUrl = $helper->getLoginUrl('http://domain.com/fb_callback.php', $permissions);
How can achieve the same thing without manual redirection, is one script, in AJAX context? SHould I use Curl to emulate manual redirection?
THing which puzzle me out is that the same stuff tok 2 lines using JS framework :
window.fbAsyncInit = function() {
// Framework init with Vinexpo app ID
FB.init({
appId : '012345789',
xfbml : true,
version : 'v2.4'
});
// Check status
FB.getLoginStatus(function(response) {
if (response.status === 'connected') {
// If connected, get last 2 posts on Facebook page
FB.api(
"/page_ID/posts?limit=2",
{
access_token : response.authResponse.accessToken
},
function (responsePost) {
if (responsePost && !responsePost.error) {
// Fill tiles on social network panel
}
}
);
}
});
Thanks in advance for answers or leads.
If you just want to read the newsfeed of one of you pages via AJAX, you don't necessarily need the PHP SDK if you generate yourself an eternal page access token and use this for your plain HTTP requests.
Have a look at my answer here on how to get such a token:
Post to a facebook page without "manage_pages" permission using php
Im getting started with the php sdk, and struggling to understand a few things (I have a basic example below - but everytime the pic goes to MY wall and not the fan page)
Code:
require_once("facebook.php"); // set the right path
$config = array();
$config['appId'] = 'app id';
$config['secret'] = 'app secret';
$config['fileUpload'] = true; // optional
$fb = new Facebook($config);
$params = array(
// this is the access token for Fan Page
"access_token" => "I create this via the graph api (select App and click get token), I select publish stream and photo_upload permissions.",
"message" => "test message",
"source" => "#" ."photo.png", // "#" .
);
try {
// **** is Facebook id of Fan page
$ret = $fb->api('/****/photos', 'POST', $params);
echo 'Photo successfully uploaded to Facebook Album';
} catch(Exception $e) {
echo $e->getMessage();
}
the picture keeps going to MY wall (logged in user) and not the fan page, is that because im getting a token for the currently logged in user (me) instead of the fan page? and if so how do i generate a token for the fan page whilst logged in as the developer? (is it by putting the fan page id into the Get bar?)
Apologies for the noob questions but the facebook documentation sucks (until u understand the core functionality of course). Most tutorials work once u know how to use the graph API - none ive looked actually EXPLAIN how to use the graph to generate correct tokens, etc.
\POST /<ID>/photos — this will post on the <ID>'s wall only, so please double-check the <ID> that you are using.
The access token will depict that on behalf of whom the photo would be posted on the <ID>'s wall. If you use the user access token, the photo will be published on behalf of the user and if page access token is used, it will be published on the page's behalf itself.
You can get the page access token of your pages by-
\GET /me/accounts?fields=access_token
(permission required: manage_pages)
Demo
I'am having a quiz program on my site where user logs in through their facebook account and play the quiz.
After successfully completing the quiz I want to post their score and rank on their wall. Facebook login and logout is working fine. How do I show their score and rank on their wall without displaying a dialog box?
I'm using this code to post the score and rank on user's wall-
require 'src/facebook.php';
<?php
$facebook = new Facebook(array(
'appId' => 'APP ID',
'secret' => 'SECRET KEY',
));
?>
<script>
FB.init({
appId:'APP ID', cookie:true,
status:true, xfbml:true
});
FB.ui({ method: 'feed',
message: '<?php echo "My score is ".$myscore." and rank is ".$rank; ?>'});
</script>
This code is opening a dialog box for me but that is with empty input field. If user will hust click on 'Publish' button then nothing will be posted on their wall and if they edit the text in input field then they will post wrong information. Either this field should be un editable or this box should not be there.
Please suggest me a solution with code example.
That's because FB not allowing pre-editing the message field. If you want to publish something in the user's Wall, you should have 'publish_stream' permission from the user, that way you will be able to post messages without requesting the user to enter something in it's message box or pressing the Publish button. But for this you have to call FB.api to access Graph API to access the user's Wall. For more details, see Graph API.
Adding to this code you wrote, you should use OAuth2 methods by adding 'oauth: true' to the FB.init parameter.
You should request "publish_stream" permissions to be able to publish Feed Stories without showing dialog to user.
Sample code may look like this:
FB.login(function(response) {
if (response.authResponse) {
console.log('Posting message');
FB.api('/me', 'post', {message: 'Beware, boiling water...'});
} else {
console.log('User cancelled login or did not fully authorize.');
}
}, {scope: 'publish_stream'});
i want to authenticate my facebook profile with my website so i can pull infor from the page.
i was suggested to one time authenticate with the facebook api through a temp page. somewhat like:
<fb:login-button params="some permission" />
i am new to coding facebook apps. but this seems like fbml. how can i use it to authenticate my website with my own profile. i dont need users to log into my website. i just need to pull info from my page.
the facebook documentation is sparse and fragmented. all i got for the Login was this code fragment. I dont understand how i can authenticate a weblink through this method.
FB.login(function(response) {
if (response.session) {
// user successfully logged in
} else {
// user cancelled login
}
});
can anyone throw some light??
Let's start from the beggining:
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:fb="http://www.facebook.com/2008/fbml" xml:lang="en" lang="en">
It's required for fbml to work. Next:
<fb:login-button autologoutlink="true"></fb:login-button>
<div id="fb-root"></div>
These two lines create the "facebook login button", you should place them in your html where you want the button to appear.
Right before your closing body tag add:
<script type="text/javascript" src="https://connect.facebook.net/en_US/all.js"></script>
<script>
window.fbAsyncInit = function() {
FB.init({appId: 'YOUR APP ID HERE', status: true, cookie: true, xfbml: true});
FB.Event.subscribe("auth.login", function(response) {
if(response.session) {
// this is where you handle facebook's response
}
});
};
</script>
What you are doing here is first initializing the connection to facebook, with your app id (you need to create an application), and register an "auth.login" event. The auth.login event is triggered every time you click the facebook login button and successfully login to facebook, or facebook auto logins you based on their cookie.
You can find an explanation of the auth.login and other events here, look at the sidebar at the left, all events are listed.
The response is JSON formatted and it contains your basic session information:
{
status: 'connected',
session: {
access_token: '...',
expires:'...',
secret:'...',
session_key:'...',
sig:'...',
uid:'...'
}
}
You can read more about it here. If your status is indeed "connected" the next most important bit of information is the uid, this is your unique facebook identifier, a public id with which you can send further requests to facebook. What you do with the response is up to you. An obvious choice would be to send it via ajax to a script that logs you in your application.
To get more info from facebook you need to download the php sdk. To use the sdk:
<?php
include_once "facebook-sdk-3.0.0/src/facebook.php";
$appID = "YOUR APP ID";
$appSecret = "YOUR APP SECRET";
$cookie = "fbs_{$appID}";
$cookie = isset($_COOKIE[$cookie]) ? trim($_COOKIE[$cookie], '"') : "";
if(empty($cookie)) {
echo "no facebook cookie";
die();
}
parse_str($cookie, $data);
$facebook = new Facebook(array(
"appId" => $appID,
"secret" => $appSecret,
"cookie" => true
));
$facebook->setAccessToken($data["access_token"]);
$user = $facebook->getUser();
$profile = $facebook->api("/me");
?>
So at first you parse facebook's cookie which is named "fbs_YOUR_APP_ID" and contains your session information (url encoded). What you actually need is the access_token (a unique identifier of the authenticated session), which was also returned to you in the JSON response object before. Then via the Facebook object you can do and api requests you want.
Now to have a full authentication mechanism you should create a similar connect script that instead of getting the session information from the cookie it should take them from the response object that is returned when auth.login occurs (possibly via ajax).
You should read the Authentication workflow document to better understand how facebook connect works.
A good and easy way to deal with Facebook authentication is to implement the server side flow with the Facebook PHP SDK (see on github). So you will have something like :
require "facebook.php";
$facebook = new Facebook(array(
'appId' => YOUR_APP_ID,
'secret' => YOUR_APP_SECRET,
));
$user = $facebook->getUser();
If the user is logged in, then $user is his Facebook ID. You then have to check if you have a valid access token by making an API call :
If it does not raise any exception, then you have a valid access token
If it does, then you have to re-authenticate the user.
Here :
if ($user) {
try {
$facebook->api('/me');
} catch (FacebookApiException $e) {
$user = null;
}
}
You need then to display the login or logout link :
<?php if ($user): ?>
Logout of Facebook
<?php else: ?>
Login with Facebook
<?php endif ?>
When the user is logged in and you have a valid access token, you can make API calls to get data from Facebook :
$user_profile = $facebook->api('/me');
You may want to check the example page of the Facebook PHP SDK which is well documented.
Hope that helps.
I own a couple of pages against Child abuse and now I'm developing a Facebook application for fighting against Child Abuse.
I'm somewhat a newbie, and I found many wonderful resources on the net, however, I don't seem to find what I really want.
I know to build a basic app that accesses a user's basic information(using fb_sig_user). However, I need the code to publish static content to my users' wall, request permissions for the same, (would be nice if it publishes each time they interact with my page).
It would also be nice if the app can post to the user's friends too..but its not a must.
Can someone help me? I have these files with me (its an FBML app,btw) and I'm stuck :
tab.php
<?php
if (isset($_REQUEST['name'])){
$uidc2 = $_REQUEST['fb_sig_user'];
echo $uidc2;
?>
<div id="update"></div>
<form action="" id="frm_test" method="post" onsubmit="return false;">
<input type="hidden" name="name" size="50" />
<input name="name" type="button" clickrewriteurl='http://somewebsite.com/fb/tab.php' clickrewriteform='frm_test' clickrewriteid='update' value="submit"/>
</form>
index.php
<?php
require 'facebook.php';
$app_id = 'xyzzy';
$application_secret = 'abc';
$facebook = new Facebook(array(
'appId' => $app_id,
'secret' => $application_secret,
'cookie' => true, // enable optional cookie support
));
if ($facebook->getSession()) {
echo 'Logout';
$user = $facebook->getUser();
} else {
echo 'Login';
}
?>
Any help a this point is really much appreciated. Thank you.
You can use the stream.publish method to publish stream to users of your app. If you want to post to users' wall even if they are not logged in, you need to ask them for the publish_stream extended permission first.
Update:
Getting Permissions
To get permissions, have a look at:
Create Facebook PopUp Authentication Window using PHP and javascript
Alternatively,
In your main config or header file , put code like this:
$facebook = new Facebook($appapikey, $appsecret);
$user = $facebook->require_login();
$facebook->redirect('https://graph.facebook.com/oauth/authorize?
client_id=[YOUR APP ID]&
redirect_uri=[YOUR APP URL]&
scope=publish_stream, offline_access');
Replace [YOUR APP ID] with application id that you can see from application settings where you created the site in Facebook Developers section. Also replace the [YOUR APP URL] with your app url.
To Publish Steam
There is another javascript sdk method named FB.ui. Using the code you can prompt user for stream publish or share your page. Checkout streamPublish() and share() methods defination in my demo’s source code .
Have a look at this tutorial for more info:
Graph api & javascript base Facebook Connect tutorial
Or You can use this function to publish the steam:
function publish() {
var attachment = {
'name': 'App Name',
'href': 'http://apps.facebook.com/someapp/', 'caption': '{*actor*} perfomed an action!!',
'description': 'The description goes here',
"media": [{ "type": "image", "src": "http://www.example.net/images/logo.png", "href": "http://apps.facebook.com/someapp/"}]
};
var action_links = [{ 'text': 'World Winner 2010', 'href': 'http://apps.facebook.com/world_winner/'}];
Facebook.streamPublish('', attachment, action_links);
}
Change the settings in above function as per your requirements and call it like this when you need to publish the stream:
publish();
More Resources:
Facebook Graph API — getting access tokens
How to retrieve facebook user’s friendlist
How to get mutual friends in facebook
And you can find good facebook-related tutorials at this site:
thinkdiff.net
You can check out https://github.com/brennannovak/codeigniter-facebook-oauth which lets you upload a CodeIgniter setup with a basic example application. It replaces the old php-sdk.