Facebook status update with PHP - facebook

My requirement was to update members status from my site, i am also thinking about displaying their friends photos and their last status update.
I have looked all over the docs and cant decide which works for my need. RESTful API, JavaScript API, FQL, XFBML, FBML, FBJS ?? whcin one works best? or best way?
It should be like, when they first go to the page,there will be nothing but a login option. when they click on it, a pop up should appear and when they are authorized, we display a text area to post update. Here, i wanted to show their friends pics too
when they came back later, they should able to post right away, must not ask for login again.
Can some one help me with the code?? I dont expect you to write everything, get the friends pic and their last update into a PHP array would be nice.
Many thanks

If u need to update users data stored at ur database so u will use the facebook API to check user signed in and get his data. i have an ifram application at facebook and i am using C# code (asp.net application) and when the user request the application i authenticate that he is signed in to facebook and check if he is already exist in my database? if not so i get his information(by using facebook API) and add the user in my data base and each time he visits the application i update his information.
With respect to his friends i get all facebook ids of the user friends and then loop these IDs and get the pic of each ID.
Download Facebook Developer Toolkit that enables u communicate with facebook and use facebook API to get user information.
hope that is will help u
Visit my application in facebook and u will see these features at the following link :
http://apps.facebook.com/hanggame/
Getting the session Key :
protected void Page_Load(object sender, EventArgs e)
{
//Facebook code for integration with facebook users:
_fbService.ApplicationKey = "Application Key";
_fbService.Secret = "Secret Key";
_fbService.IsDesktopApplication = false;
string sessionKey = (string)Session["Facebook_session_key"];
if (Session["Facebook_userId"] != null)
userId = (long)Session["Facebook_userId"];
// When the user uses the Facebook login page, the redirect back here will will have the auth_token in the query params
string authToken = Request.QueryString["auth_token"];
if (!String.IsNullOrEmpty(sessionKey))
{
_fbService.SessionKey = sessionKey;
_fbService.uid = userId;
}
else if (!String.IsNullOrEmpty(authToken))
{
_fbService.CreateSession(authToken);
Session["Facebook_session_key"] = _fbService.SessionKey;
Session["Facebook_userId"] = _fbService.uid;
Session["Facebook_session_expires"] = _fbService.SessionExpires;
}
else
{
Response.Redirect(#"http://www.Facebook.com/login.php?api_key=" + _fbService.ApplicationKey + #"&v=1.0");
}
userId = _fbService.uid;
//End of Facebook code
}

Related

Identifying Facebook Messenger user with UserID from a Facebook Login

I am trying out the new Facebook Messenger Platform and have hit a bit of a problem.
When a user first chats with my Bot, I want to use the sender.id to lookup the user in my DB and verify whether they're a customer or not and offer a more tailored UX.
User's sign up to my service using Facebook Login, but unfortunately it appears my App's Facebook ID & my Bot's Facebook ID are different due to IDs being limited to App-scopes.
Is there any way associate the 2 IDs to allow me to find a user in my DB?
UPDATE (4/20/2016):
We got around this by asking users on first contact via messenger to click a link to login to their account so we could associate their messenger_id with their account in our DB.
Would be awesome if facebook instead included PAGE_SCOPED IDs in the ids_for_business endpoint.
UPDATE: (6/1/2016):
Facebook's latest update includes a new "Account Linking" functionality that appears to solve this issue. See https://developers.facebook.com/docs/messenger-platform/account-linking
Facebook's latest update includes a new "Account Linking" functionality that appears to solve this issue. See https://developers.facebook.com/docs/messenger-platform/account-linking
Unfortunately, there's no way of doing that currently. Asking them to login for new threads is the best way of linking accounts.
Yes. You can get details like first name, last name, profile pic url, locale, timezone, gender from an api. Only you have to pass is their recipient id/sender id and acccess_token of your messenger bot.
https://graph.facebook.com/v2.6/USER_ID?fields=first_name,last_name,profile_pic,locale,timezone,gender&access_token=TOKEN
I solved it different way but it works perfectly by graph API,i read mailbox of my page so that when any one can interact by messenger bot than i read pages inbox and iterate through,
Step 1:
Do a HTTP get request by graph API ,
you want a PAGE_UNIQUE_ID from Graph API ,
GET REQUEST
https://graph.facebook.com/v2.6/<PAGE_UNIQUE_ID>?fields=conversations.limit(10){participants,updated_time,id}&access_token=<PAGE_ACCESS_TOKEN>
PAGE_UNIQUE_ID Hints:
Go ===> https://developers.facebook.com/tools/explorer/ ==> Press "Get Token" ===> Select your desired page ===>Finally Submit , You show a id on output that is PAGE_UNIQUE_ID in here.
Check on browser for resoponse.
Step 2:
After doing above http request ,you get a JSON object that will show latest 10 conversation of pages where desired facebook id included.
Step 3:
Do iteration through by user full name or you can use lodash or underscore at your choice,
getUserID(response,'Zahid Rahman')
function getUserID(response, fullname) {
if (response && response.conversations && response.conversations.data) { //Check response is correct
var conversations = response.conversations.data; //Get all conversations
for (var j = 0; j < conversations.length; j++) {
var conversationsParticipants = conversations[j].participants.data;
for (var k = 0; k < conversationsParticipants.length; k++) { //Get all particiapnts of a single conversation.
var conversationsParticipantsEach = conversationsParticipants[k];
if (conversationsParticipantsEach.name === fullname) { //Check fullname match or not
console.log("Desired Facebook User ID : " + conversationsParticipants[k].id);
return conversationsParticipants[k].id;
}
}
}
}
}
Hope it will help you.
This is probably what you want: https://developers.facebook.com/docs/apps/for-business
It allows you to get all of the app-scoped user ids on a per-business basis.

How do I remove the Facebook login prompt when displaying images pulled with graph api on a page?

I recently started playing around with Facebook graph API and wanted to integrate images pulled from my Facebook page to display on my website. I have the images displaying properly but my problem is whenever anyone tries to view the page they are asked to log into Facebook first. Is there any way to display the images without prompting the user to log into Facebook?
Here is what I am using to make the session:
$app_id = 'id';
$app_secret = 'secret';
$redirect = 'my webpage';
// init app with app id and secret
FacebookSession::setDefaultApplication($app_id,$app_secret);
// login helper with redirect_uri
$helper = new FacebookRedirectLoginHelper($redirect);
try {
$session = $helper->getSessionFromRedirect();
} catch( FacebookRequestException $ex ) {
// When Facebook returns an error
} catch( Exception $ex ) {
// When validation fails or other local issues
}
Any help would be appreciated.
Step one: familiarize yourself with the API. Read the docs, and play around with the Graph API Explorer
Step two: the code you provided has nothing to do with what you are trying to achieve (displaying page photos). That code is basically the getting started code used in the docs. If you need help, post the relevant code.
Step three: as mentioned by #CBroe, authenticating the visitor is not needed to display photos from a page. What you might want to explore:
The page admin authenticating your app with the right permissions (maybe manage_pages)
with the user access token you just got, you extend it to long-lived one
then you query the API to get a page access token that won't expire
you store this access token and query the API to get the relevant data and store it (GET /{PAGE-ID}/photos or GET /{PAGE-ID}/albums ... etc)
you show the stored data to your visitors
Notes:
Do not make these calls on client-side ... i.e. reveal your page access token, since you can do this in the backend.
Use the realtime updates to get notified when you should query the API and get new photos instead of periodically querying the API to pull new photos, or even worst, querying the API on each user visit.

How to get ids of facebook invited friends by user in my asp.net4.0 web application

I am developing an ASP.NET application. I implemented Facebook JavaScript API in my application, for connect with Facebook and get FB friend list of user. I had done this successfully.
Now, I want to count how many friends are invited by user. Is it possible with facebook API. User can select multiple friends and i want to count how many friends selected and invited by user, Invited friends Id is bonus if We can get.
Please don't forget that facebook changed its Oauth settings for security reasons.
I'm also trying to get ids values after Send Invitation button clicked and page post back to
if (Request.Form["ids"] != null)
{
span1.InnerHtml = "ids";
//put success code here..
}
else
{
span1.InnerHtml = "oops no id";
}
if (Page.PreviousPage != null)
{
span1.InnerHtml = "ids";
//put success code here..
}
else
{
span1.InnerHtml = "oops no id";
}
but in this case program control always goes to else condition it means after page is post back form return null value.
Is there any way to get ids of invited friends.
Thanks.
If you using Facebook Requests to send invites (you really should, it's intended for this), the only way to get invited friends is via Facebook Requests Dialog callback:
FB.ui({method: 'apprequests', message: 'Whoa!'}, callback);
function callback(response){
// response.to now contain array of invited users ids
console.log('Invited friends ids', response.to);
if (response.request) {
console.log('Efficient Request id', response.request);
} else {
console.log('Requests Ids', response.request_ids);
}
}
There is no way to get request sent by user via Graph API or FQL, you only can get requests received by user. You may save all requests sent by your users and rely on this data if you need aggregated count of invitation sent...
Ok finally I resolve this issue and get invited friends ids..
As we know we use javascript sdk for FB connect so my solution is in concern of Java script:
Just make on change in your .js file where you put your facebook connect javascript code. Use Get or Request Method instead of Post Method in fb:request-form tag.
<script type="text/javascript>
var fbhtml = "<fb:serverFbml width=\"" + width_of_invitation_div + "\">
<script type=\"text/fbml\"><fb:fbml><fb:request-form action=" + window.location + " method="REQUEST" invite="true" type="" + type_of_fb_request_form + "" hold=" /><br mode="></fb:request-form></fb:fbml></script></fb:serverfbml>"
</script>
After invitation send to users selected friends you get ids[] in url.
you can get these ids through query string and split ids by comma(,) and store in array.
Hope this will help for other devs.

Cannot get page "like" status using Facebook C# SDK

I am using the latest Facebook C# SDK (v5.0.40 at time of writing) from here: http://facebooksdk.codeplex.com/.
I have created a test iFrame app in Facebook and got the CSASPNETFacebookApp sample running so that it displays the name of the currently logged in user within Facebook.
What I would now like to do is display different content in my iFrame depending on whether the user has "liked" the page. However the signed_request never seems to contain that information. From what I can see in the FacebookSignedRequest.cs I will only get the payload which contains the page information if the algorithm is AES-256-CBC HMAC-SHA256 but I only ever get HMAC-SHA256 returned.
What am I doing wrong? How do I get it to return the page information? Is it a problem with the setup of my app in Facebook or a configuration issue with the .NET app?
Thanks in advance.
var fb = new FacebookClient("access_token");
dynamic parameters = new ExpandoObject();
parameters.method = "pages.isFan";
parameters.page_id = "{you page id}";
dynamic result = fb.Get(parameters);
bool isFan = result == true;
Neil Knight's answer is technically correct, you can use FQL to look up whether a user has liked a page and it did help to set me on the right path. However my issue was actually more one of set up rather than code. What I didn't understand is that you only receive the "like" information in the signed request if your app is running within the "context of a page". If you set it up correctly then Facebook will pass your app the like flag without the user needing to "Allow" your app.
The steps are:
(1) Create your iframe application in Facebook
(2) Set up a tab url for your app in the app settings. This is what the parent page will use when it generates a link in the left hand column to go to your app.
(3) Go to your "App profile page", the URL will be something like this: http://www.facebook.com/apps/application.php?id=12345 Where 12345 is your app ID.
In the left hand column below the logo image there should be a link "Add to Page". If you click on that link you will be presented with a list of pages that you are the admin for. Select the page you want to like in your app.
Now if you navigate to your page you should get a link to your app in the left hand column. It is only when clicking on that link that you will get the page id and like status passed through to your application.
Hope this helps someone having the same issue.
You could use FQL in order to achieve this. I have just done this using the following statement:
var the_query = FB.Data.query("SELECT uid FROM page_fan WHERE page_id = {0} and uid={1}", page_id, user_id);
In order for this to work, I had to ask the user to "Allow" my application so that I had permission to check to see if they liked the page. Then, it was a simple case of checking the result and displaying the necessary <div>:
the_query.wait(function (rows) {
if (rows.length == 1 && rows[0].uid == user_id) {
$("#myLikeContent").show();
} else {
$("#myNoLikeContent").show();
}
});

Facebook fan page tab and user id

As per the documentation in the following link, we can get the user id if the uer will interact with the form..
http://wiki.developers.facebook.com/ind … d_Policies
"If a viewing user interacts with the tab (like submits a form, takes an action that causes an AJAX load of new content, or follows a relative URL that loads on the tab), that user's UID is sent to the application as the fb_sig_user parameter, the profile owner's user ID is sent as the fb_sig_profile_user parameter. The viewing user's session key is key is sent only if the user authorized the application. "
In my fan page tab am I have an AJAX form which the user can submit with some value.. now I need the users id also.. how can I get this..
I tried to get the value in my AJAX submit page using $_POST['fb_sig_user'] with no success.. can anyone help me with this please..
You won't be able to get the id of the user using $_POST['fb_sig_user'] unless you authenticate the user by having this in the facebook's ajax function:
ajax.requireLogin = true;
For example, I'm retrieving it fine with this:
function do_ajax(url, div_id)
{
document.getElementById('poller_waitMessage').setStyle('display', 'block');
var ajax = new Ajax();
ajax.responseType = Ajax.FBML;
ajax.onerror = function(error)
{
new Dialog().showMessage("Error:", "Some communication error occured, Please reload the page.","Ok");
};
ajax.ondone = function(data)
{
document.getElementById('poller_waitMessage').setStyle('display', 'none');
document.getElementById(div_id).setInnerFBML(data);
}
ajax.requireLogin = true; // <----- this is important
ajax.post(url);
}
I've been happily using the form variable fb_sig_profile_user for previous apps, and when developing a new app last week, the variable was no where to be found.
Searched for several days, I was about to give up, and then the found answer:
ajax.requireLogin = true;
I understand FB cares about privacy and all, but they really need to announce these kinds of changes before just taking it away.
Million Thanks!