How to make a wall post using windows phone 7 native app - facebook

I have created a native app on Windows Phone 7.
The user of the app will provide his login credentials to us when he registers as a new user. What i want to do is to give a handle of share on facebook in my app.
On clicking on the handle the selected image should be posted on to the user's wall and just display a message to the user that the image is posted successfully or not.
The problem is that facebook has not provided with a developent environment for Windows Phone 7 native apps.
I want some alternate solution to this.

thanks for the link. I had already visited the link earlier. I have implemented facebook integration in wp7. Its working properly and i am able to make wall posts.
Here's my code,
//Users clicks on Share on facebook button
private void btnFacebookPost_Click(object sender, RoutedEventArgs e)
{
//Check if access tokens are already set.
if (App.accessTokens == null)
{
GetAccessTokens();
}
else
{
//Use the access tokens to post on facebook
}
}
private void GetAccessTokens()
{
// Navigate user to facebooks login page
// if user has already authenticated your app you'll receive the access tokens directly
webBrowser.Source = new Uri("https://www.facebook.com/dialog/oauth?client_id='your app id'&redirect_uri=https://www.facebook.com/connect/login_success.html&response_type=token&scope='whatever extended permissions you require'");
}
//On The Navigated event of web browser check for access tokens
//Use the facebook c# sdk to get the access tokens from the url
void webBrowser_Navigated(object sender, System.Windows.Navigation.NavigationEventArgs e)
{
FacebookClient fbClient = new FacebookClient();
FacebookOAuthResult oauthResult;
if (fbClient.TryParseOAuthCallbackUrl(e.Uri, out oauthResult))
{
// The url is the result of OAuth 2.0 authentication
if (oauthResult.IsSuccess)
{
App.accessTokens = oauthResult.AccessToken;
}
else
{
var errorDescription = oauthResult.ErrorDescription;
var errorReason = oauthResult.ErrorReason;
}
}
else
{
// The url is NOT the result of OAuth 2.0 authentication.
}
}
Now use the access tokens with the facebook sdk for C#.net to make the wall posts or any other transactions as required.
The problem with this method is that the application user and the facebook's logged in user may be different thus making a transaction to different account.
Since the SSO for WP7 is not available this method should do the trick.

Related

Check Facebook login status using Alloy or Titanium in an iOS app

I want to add Facebook login to my Alloy/ Titanium ios app.
So far I have the following code:
var fb = require('facebook');
fb.initialize();
fb.setLoginBehavior(fb.LOGIN_BEHAVIOR_NATIVE);
fb.permissions = ['email', 'public_profile'];
function doFacebookLogin() {
// occurs when a button is clicked
if (fb.loggedIn) {
facebookLogin(fb);
} else {
fb.authorize();
}
}
fb.addEventListener('login', function(event) {
if (event.success) {
facebookLogin(fb);
}
});
function facebookLogin(fb) {
Ti.API.info(fb.accessToken);
// send the fb.accessToken server-side and register & login the user
}
For the most part the code works fine!
The issue is when the user de-authorises the app, fb.login still return true and so is using the same access token.
How can I check if the user has de-authorised my app. I know it's easily possible using the JavaScript SDK using FB.getLoginStatus: https://developers.facebook.com/docs/reference/javascript/FB.getLoginStatus , but I can't find an equivalent in Alloy/Titanium: https://docs.appcelerator.com/platform/latest/#!/api/Modules.Facebook
You need to call fb.logout() to set fb.loggedIn to false.
fb.logout clears the access token and resets the login state to false.
Note: I am not sure whether clearing the access token in Titanium module will also clear the token on FB server. So even after calling fb.logout(), you might receive the same access token if and only if it has not expired on fb server.
Read more about Facebook Access Token here

Facebook always logins with same user even though I am using different users

I'm developing an Android game in Unity and using Facebook SDK as the authenticator.
After completing the setup phase in Unity I tried to login and it worked. User that I used to login was the admin user which I also used to create the app at developer.facebook.com.
Later I tried to connect with other users. They were real accounts which have roles of developer and tester, I even used the test users that are automaticly created by FB but even though they all have different credentials they all logged as the admin user.
to make it clear I did the following:
1) Run the game on android.
2) Hit the login button and FB app will start to run.
3) Login with admin user.
4) Now I am logged with Admin user.
5) Close the app and logout from FB.
6) Run the app and this time login with user B (Dev, tester, etc.)
7) Instead of user B again admin user will be authenticate.
Edit: Today I upgraded the FB sdk. In first try I logged with a test user and logged in correctly. On later connections I used the Admin and other test users but they all logged as the first test user. I guess problem isn't related with admin user but the one that first login's.
I used friendsmash tutorial as example for my game and below you can find the code piece that I used in my app.
public void Init() {
FB.Init(SetInit, OnHideUnity);
}
private void SetInit() {
enabled = true;
}
private void OnHideUnity(bool isGameShown) {
Debug.Log("OnHideUnity");
if(!isGameShown) {
// pause the game - we will need to hide
Time.timeScale = 0;
}
else {
// start the game back up - we're getting focus again
Time.timeScale = 1;
}
}
public void FBLogin(LoginOnSuccess cb) {
loginOnSuccess = cb;
FB.Login("user_friends", LoginCallback);
}
void LoginCallback(FBResult result) {
if(FB.IsLoggedIn) {
FB.API("/me?fields=id,name", Facebook.HttpMethod.GET, delegate (FBResult response) {
if(response.Error != null) {
Debug.Log("Error: FB.API: /me?fields=id,name");
}
Debug.Log("Permissions: " + response.Text);
});
}
else {
//TODO login failed. Give a proper error message on gui
Debug.Log("FacebookController.cs: Couldn't connect to FB.");
}
}
Ok, I found the problem.
Logouting from the Android Facebook app doesn't logout you from your game. Also If there is already logged in user (this means FB.IsLoggedIn == true. as you can see from my code I removed this check. Originally this is used in friendsmash tutorial of FB), and you call FB.Login() this doesn't do anything. FB SDK keeps the previous session. I think API has to warn the developer/user that "you are switching user" or "you cant relog while you are allready logged in".
So what I am doing is, calling FB.Logout() in callback of FB.Init(SetInit, OnHideUnity):
private void SetInit() {
enabled = true;
FB.Logout();
}

How would I set a PHP session via JavaScript (Facebook SDK)

I'm creating a Login Function using Facebook's SDK. I'm re-using code from a previous project that had a Login button which redirected to a Login Box on the Facebook Domain (i.e. the Login box was not a popup, but redirected the user).
In the previous project when the user would come back to the site after accepting the app, there was a PHP script which created a $_Session:
$user = $facebook->getUser();
if (isset($user)){
$_SESSION['LoggedIn'] = $user;
}
I could then use the 'LoggedIn' session to check if the user was logged in or not, and modify the page based on that (e.g. replace content on the page).
Here's my question - I am now using the JS code that Facebook provides for a popup Login box. I'm guessing after the user Accepted the app from the Login Popup I need to start the session from within JavaScript? The problem is I can't figure out how....
$(".facebookButton").click(function(){
FB.login(function(response) {
if (response.authResponse) {
//User accepted the app -I need to start the SESSION here?
} else {
//User hasn't accepted the app.
}
});
});
Basically what I'm trying to achieve is for the site to know whether the user is logged in or not, even after they've refreshed the page. Thanks for the help!
When the user logs in using the JavaScript SDK, a cookie is immediately dropped on your site with their auth details. The dropped cookie can also be ready by the PHP SDK so all you need to really do is refresh the page for the PHP SDK to detect the user:
$(".facebookButton").click(function(){
FB.login(function(response) {
if (response.authResponse) {
// reload page
location.reload();
} else {
// User hasn't accepted the app.
}
});
});

Best practice for dual-use iFrame + External authentication for Facebook enabled app

Okay, if cookies are a no-no, then I need a little guidance as to the best way to implement the application(s) that I'm creating.
The scenario is that I'm trying to create a single Asp.Net MVC application that can authenticate a user regardless of whether the user visits a site directly or via an iFrame in Facebook. There are separate actions (in separate controllers, actually) for getting INTO the app depending on whether the user enters via Facebook or not, but there are also places in the Facebook app where I'm opening up a new window to "extended" functionality in other areas of the application that can't really work well within the iFrame. It is supposed to transition seamlessly. It's currently working quite well using cookies, but I've from multiple sources that this is not a good thing for iFrame apps. However, I'm not sure exactly what this means.
Without cookies, can you still somehow get server-side access to the authentication token? If not, then what is the "right" way to handle this. Do I need to resort to manually parsing the token using the JS API and sending an AJAX notification to the server of the fact that the user is authenticated and create a forms auth token? Will the CanvasAuthorize attribute work without cookies? Right now I have added code to the FormsAuthentication_OnAuthenticate event in Global.asax to create the forms auth token if the user is logged in via Facebook (and properly associated with a valid user in the external app) as follows:
protected void FormsAuthentication_OnAuthenticate(Object sender, FormsAuthenticationEventArgs args)
{
if (FormsAuthentication.CookiesSupported)
{
if (Request.Cookies[FormsAuthentication.FormsCookieName] == null)
{
// Attempt to authenticate using Facebook
try
{
FacebookApp fbApp = new FacebookApp();
if (fbApp.Session != null)
{
dynamic me = fbApp.Get("me");
String fbID = "" + me.id;
MembershipUser mUser = AppMembershipProvider.GetUserByFacebookID(fbID);
if (mUser != null)
{
FormsAuthentication.SetAuthCookie(mUser.UserName, false);
AppMembershipProvider.UpdateLastLogin(mUser.UserName);
Session["FacebookLogin"] = true;
}
}
}
catch (Exception e)
{
Elmah.ErrorSignal.FromCurrentContext().Raise(e);
}
}
}
else
{
throw new HttpException("Cookieless Forms Authentication is not " +
"supported for this application.");
}
}
Will I need to change this?
Sorry if this is basic knowledge, but I'm confused as to how best to implement this. Thanks!
First, let me address the issue with the cookies. So, when I say to not use cookies in iFrames I am saying that for a couple reasons. First in IE, there are some security issues. You need to add the following header to your app to make cookies work correctly inside iframes:
P3P: CP="CAO PSA OUR"
The second big issue with cookies in iframe apps is Safari. Due to security settings in Safari, cookies cannot be created by iframes. As such, you will not be able to rely on cookies for authentication inside of iframes.
Give that you are using the app inside and outside of the iframe, you should have cookie support turned on. However, your app must be designed in a way that will work around the iframe issues. That is going to be the hard part.
The most reliable authentication inside iframe apps is the signed request method. What happens is facebook will append a query parameter to your url when the url is rendered inside the iframe. This query parameter contains the user's session. The Facebook C# SDK handles reading this for you, so you dont need to parse it etc. But you need to be aware that it is there. If you view the incoming request url of your iframe app in facebook you will see something like http://www.mysite.com/page/?signed_request={blahblahblah}.
So the key is that you need to make sure that if you are in the iframe you keep that ?signed_request value on the url.
You can do this several ways. First, you can use the CanvasRedirect methods. These are extension methods on System.Web.Mvc.Controller in the Facebook.Web.Mvc namespace. The canvas redirect uses javascript to redirect your page in the top url. This way Facebook is actually handling the redirects and will always add the signed_request to your iframe url. The problem for you is that this method of redirecting will only work in the iframe, not outside.
The second way would be to manually add the ?signed_request to the url when you redirect. You would do something like:
public ActionResult Something() {
return RedirectToAction("something", new { signed_request = Request.Querystring["signed_requets"]);
}
There are other ways also, like storing data in the session or something, but I wouldn't recommend going down that path.
What you are doing is definitely an advanced senario, but hopefully the above will help you get going in the right direction. Feel free to contact me directly if you have any questions. nathan#ntotten.com or #ntotten on twitter.
I am in a similar situation to you. What I do to handle the various situations that can arise is:
Enable cookies in both the C# and
JavaScript SDK.
Create a custom actionfilter that
inherits from
FacebookAuthorizeAttribute and
overrides the
HandleUnauthorizedRequest method to
redirect to either a connect
authorization page or an action
decorated with the
CanvasAuthorizeAttribute.
Pass either the signed_request
(canvas app) or auth_token (connect
app) as a querystring parameter to
everything.
Check for null sessions and oauth
tokens that don't match what has been
passed in the querystring.
The main point is to ensure that both the session and oauth tokens are valid. When inside Facebook the signed_request will ensure this is true. By passing the token from your connect auth page you can ensure you have a valid token to inject into the FacebookApp constructor.
public class FbAuthenticateAttribute : FacebookAuthorizeAttribute
{
private FacebookApp _fbApp;
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
base.OnActionExecuting(filterContext);
var accessToken = filterContext.HttpContext.Request.Params["access_token"];
if (FacebookApp.AccessToken != accessToken && !string.IsNullOrEmpty(accessToken))
{
_fbApp = new FacebookApp(accessToken);
}
else
{
_fbApp = FacebookApp;
}
filterContext.Controller.ViewBag.Context = GetContext().ToString();
filterContext.RequestContext.HttpContext.Response.AppendHeader("p3p", "CP=\"CAO PSA OUR\"");
try
{
dynamic user = _fbApp.Get("me");
var signedRequest = filterContext.HttpContext.Request.Params["signed_request"];
filterContext.Controller.ViewBag.QueryString = string.IsNullOrEmpty(signedRequest)
? "?access_token=" + _fbApp.AccessToken
: "?signed_request=" + signedRequest;
}
catch (Exception ex)
{
string url = GetRedirectUrl(filterContext);
filterContext.Result = new RedirectResult(url);
}
}
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
string url = GetRedirectUrl(filterContext);
filterContext.Result = new RedirectResult(url);
}
private string GetRedirectUrl(ControllerContext filterContext)
{
return new UrlHelper(filterContext.RequestContext).Action(GetRedirectAction(GetContext()), "Authentication");
}
private Enums.AppContext GetContext()
{
//Note: can't rely on this alone - find something more robust
return FacebookApp.SignedRequest == null ? Enums.AppContext.FBWeb : Enums.AppContext.FBApp;
}
private string GetRedirectAction(Enums.AppContext context)
{
return context == Enums.AppContext.FBWeb ? "ConnectAuthenticate" : "Authenticate";
}
}
It could definitely do with a refactor and still has problems but is the best solution I have found so far.

Facebook status update with PHP

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
}