I've been working on a native C# Windows App that integrates with Facebook. However, i keep getting the same error no matter what I do with my code or even if i change the Facebook Developer > App settings (You are not logged in. Please log in and try again). Basically, I want my users to login through Facebook while my app retrieves there email & name & phone number (still in progress)
My app never logs in to Facebook, even when i try a static URL (https://www.facebook.com/dialog/oauth?client_id=1521075254860950&redirect_uri=https://www.facebook.com/connect/login_success.html)
I believe it has something to do with my "Valid OAuth redirect URIs" but i've played around for a bit with no luck. So please, if anyone could spot my mistake I would be eternally grateful! :)
Thanks, and have a good day!
private string GenerateLoginUrl()
{
string ApplicationID = "app_id";
string ApplicationSecret = "app-secret";
string ExtendedPermissionsNeeded = "email,offline_access";
dynamic parameters = new ExpandoObject();
parameters.client_id = ApplicationID;
parameters.redirect_uri = "https://www.facebook.com/connect/login_success.html";
parameters.response_type = "token";
parameters.display = "popup";
if (!string.IsNullOrWhiteSpace(ExtendedPermissionsNeeded))
parameters.scope = ExtendedPermissionsNeeded;
var fb = new FacebookClient();
Uri loginUri = fb.GetLoginUrl(parameters);
return loginUri.AbsoluteUri;
}
private void button1_Click(object sender, EventArgs e)
{
var tempUrl = GenerateLoginUrl();
//webBrowser.Navigate(tempUrl); //dynamic
label.Text = tempUrl.ToString();
webBrowser.Navigate("https://www.facebook.com/dialog/oauth?client_id=app_id&redirect_uri=https://www.facebook.com/connect/login_success.html"); //static
//webBrowser.Navigate("https://www.facebook.com/login/"); //static login
}
Related
im very new with Facebook apps and read several threads for creating them, but I have some problems with it.
First of all what I want to do: I want to create a web application that is able to post pictures, text and links on a facebook page that is managed by me.
I used the Facebook C# SDK: here!
What I have:
string facebookPageId = "<my page id>";
string app_id = "<my app id>";
string app_secret = "<my app secret>";
string scope = "publish_stream,manage_pages";
var fb = new FacebookClient();
dynamic res = fb.Get("oauth/access_token", new
{
client_id = app_id,
client_secret = app_secret,
grant_type = "client_credentials"
});
var access_token = res.access_token;
dynamic messagePost = new ExpandoObject();
messagePost.access_token = access_token;
messagePost.link = "http://www.test.at";
messagePost.name = "Testbot";
messagePost.caption = "{*actor*} " + "hello this is a test";
messagePost.description = "[SOME_DESCRIPTION]";
FacebookClient app = new FacebookClient(access_token);
app.AppId = app_id;
app.AppSecret = app_secret;
try
{
var result = app.Post("/hrechttest" + "/feed", messagePost);
}
catch (Exception e)
{
}
Well the code runs without any exceptions but in the output window I get the following:
Exception thrown: 'Facebook.FacebookOAuthException' in Facebook.dll
The next problem is:
As I understood it you must link your facebook app with your facebook page, but when I want to do that I cant select the page:
So what I did wrong or missed?
publish_stream is deprecated since many years, publish_pages is the correct permission to post to a Page (as Page).
API reference: https://developers.facebook.com/docs/graph-api/reference/page/feed#publish
Make sure you are using a Page Token, not a User Token:
https://developers.facebook.com/docs/facebook-login/access-tokens
http://www.devils-heaven.com/facebook-access-tokens/
How to create Page Apps is explained in the docs too: https://developers.facebook.com/docs/pages/tabs
I want to authenticate a user from my wp8 app using users google login credentials. So that I can get profile info of user. I found two articles in web with source code. But I was unable to get what I want.
First code I've found in this Link. But after getting authentication code it didn't have any code to get profile. May be I could not understand.
Second code I've found in this Link. It was following mvvm pattern, so I was totally blank to understand this code.
If anyone have used it properly, please help me. What actually I want that after getting client id and client secret what to do in app to get user's profile info. Helps are appreciated. Thanks in advance.
Here is code
protected override void OnNavigatedTo(NavigationEventArgs e)
{
base.OnNavigatedTo(e);
IDictionary<string, string> parameters = this.NavigationContext.QueryString;
string authEndpoint = parameters["authEndpoint"];
string clientId = parameters["clientId"];
string scope = parameters["scope"];
string uri = string.Format("{0}?response_type=code&client_id={1}&redirect_uri={2}&scope={3}",
authEndpoint,
clientId,
"urn:ietf:wg:oauth:2.0:oob",
scope);
webBrowser.Navigate(new Uri(uri, UriKind.Absolute));
}
private async void LayoutRoot_Loaded(object sender, RoutedEventArgs e)
{
if(!App.loggedin)
{
OAuthAuthorization authorization = new OAuthAuthorization(
"https://accounts.google.com/o/oauth2/auth",
"https://accounts.google.com/o/oauth2/token");
TokenPair tokenPair = await authorization.Authorize(
"YOUR_CLIENT_ID",
"CLIENT_SECRET",
new string[] { GoogleScopes.UserinfoEmail });
// Request a new access token using the refresh token (when the access token was expired)
TokenPair refreshTokenPair = await authorization.RefreshAccessToken(
"YOUR_CLIENT_ID",
"CLIENT_SECRET",
tokenPair.RefreshToken);
}
}
what to do after getting access token?
This is the code that allows you to view the profile details:
private void LoadProfile(string access_token)
{
Debug.WriteLine("loading profile");
RestClient client = new RestClient("https://www.googleapis.com");
client.Authenticator = new OAuth2AuthorizationRequestHeaderAuthenticator(access_token);
var request = new RestRequest("/oauth2/v1/userinfo", Method.GET);
client.ExecuteAsync<Profile>(request, ProfileLoaded);
}
private void ProfileLoaded(IRestResponse<Profile> response)
{
Profile = response.Data;
}
Just pass in the access_token you got from your prior code and the data should be contained in response.Data
I am trying to integrate Facebook authentication into my Windows desktop application using Facebook C# SDK. I tried to have user login using Facebook with a WebBrowser in an area of my application window. The WebBrowser will always show Given URL is not allowed by the Application configuration.
What URL should I give to my App Setting? Because my application will not be on a web page and Facebook App Setting does not have Windows Desktop platform.
private Uri GenerateFBLoginUrl(string appId, string extendedPermissions)
{
// reference: "http://blog.prabir.me/posts/facebook-csharp-sdk-writing-your-first-facebook-application-v6"
// var parameters = new Dictionary<string,object>
// parameters["client_id"] = appId;
dynamic parameters = new ExpandoObject();
parameters.client_id = appID;
parameters.redirect_uri = "https://www.facebook.com/connect/login_success.html";
// The requested response: an access token (token), an authorization code (code), or both (code token).
parameters.response_type = "token";
// list of additional display modes can be found at http://developers.facebook.com/docs/reference/dialogs/#display
parameters.display = "popup";
// add the 'scope' parameter only if we have extendedPermissions.
if (!string.IsNullOrWhiteSpace(extendedPermissions))
parameters.scope = extendedPermissions;
// generate the login url
var fb = new FacebookClient();
return fb.GetLoginUrl(parameters);
}
private void FacebookLogin()
{
loginUrl = GenerateFBLoginUrl(appID, "id");
this.FBLogin.Navigate(loginUrl.AbsoluteUri);
}
I am not familiar with this but I have two suggestions: 1) if you pass a null string what happens? and 2) pass a arbitrary URL. Good luck.
I have created a facebook page and a facebook application for my website and now I need to post messages onto the facebook page with help of facebook SDK .NET.
This is what I got so far :
public static bool UploadPost(string message)
{
dynamic result;
//https://developers.facebook.com/tools/explorer/
//https://developers.facebook.com/tools/access_token/
FacebookClient client = new FacebookClient("secret access token");
result = client.Get("oauth/access_token", new
{
client_id = "[Client ID number]",
client_secret = "[Client sercret",
grant_type = "client_credentials",
});
result = client.Post("[facebook app Id]/feed", new { message = "Test Message from app" });
//result.id;
result = client.Get("[facebook app Id]");
return false;
}
When running this I get : Additional information: (OAuthException - #200) (#200) The user hasn't authorized the application to perform this action on client.Post. If I remove the client.Post row every thing works good, the correct data is fetched.
I have tried follow some helps on facebook SDK .NET website but it is still not working.
The main problem now is that I get permission exception. I was hoping that my facebook app hade enouth permissions to publish post from my website to the facebook page.
Here is a step wise tutorial to register your application with facebook and get an app Id for your application.
Then for permissions ::
private const string ExtendedPermissions = "user_about_me,read_stream,publish_stream";
This is a string of permissions. Pass it on further for getting correct permissions to post messages on page. Post using your standard code for posting no FB pages.
Cheers. Hope it helps.
Are you trying to post to [facebook app id]?
I would recomend to post to "me/feed" and test if that works.
Also, to post to Facebook you have to have the publish_stream permission
private async Task Authenticate()
{
string message = String.Empty;
try
{
session = await App.FacebookSessionClient.LoginAsync("user_about_me,read_stream,publish_actions");
App.AccessToken = session.AccessToken;
App.FacebookId = session.FacebookId;
Dispatcher.BeginInvoke(() => NavigationService.Navigate(new Uri("/Pages/LandingPage.xaml", UriKind.Relative)));
}
catch (InvalidOperationException e)
{
message = "Login failed! Exception details: " + e.Message;
MessageBox.Show(message);
}
}
Should work :)
The following should work.
var fb = new FacebookClient("access_token");
fb.PostCompleted += (o, e) => {
if(e.Error == null) {
var result = (IDictionary<string, object>)e.GetResultData();
var newPostId = (string)result.id;
}
};
var parameters = new Dictionary<string, object>();
parameters["message"] = "My first wall post using Facebook SDK for .NET";
fb.PostAsync("me/feed", parameters);
This was taken directly from the documentation.
By creating a extended page token and use it to make the post everything works just fine. See this : How to get Page Access Token by code?
Im surprised that this simple task was so hard to get running and that there was vary little help to get.
I'm using Facebook C# sdk with the code,
i'm trying to create a new score for a user
but i get this error:
(OAuthException) An active access token must be used to query information about the current user.
what am i missing?
protected void btnAddScore_Click(object sender, EventArgs e)
{
if (CanvasAuthorizer.Authorize())
{
var fb = new FacebookWebClient();
dynamic parameters = new ExpandoObject();
parameters.score = 77;
parameters.access_token = GetAppAccessToken();
try
{
dynamic id = fb.Post("me/scores", parameters);
lblPostMessageResult.Text = "Message posted successfully";
txtMessage.Text = string.Empty;
}
catch (FacebookApiException ex)
{
lblPostMessageResult.Text = ex.Message;
}
}
}
private string GetAppAccessToken()
{
var oauthClient = new FacebookOAuthClient
{
AppId = FacebookWebContext.Current.Settings.AppId,
AppSecret = FacebookWebContext.Current.Settings.AppSecret
};
dynamic result = oauthClient.GetApplicationAccessToken();
string appAccessToken = result.access_token;
return appAccessToken;
}
edit:
I got the answer form here:
http://facebooksdk.codeplex.com/discussions/279307
the new right code is:
if (CanvasAuthorizer.Authorize())
{
var fb = new FacebookClient(CanvasAuthorizer.FacebookWebRequest.AccessToken);
var oauthClient = new FacebookOAuthClient(FacebookApplication.Current);
dynamic parameters = new ExpandoObject();
parameters.score = 100;
dynamic ac = oauthClient.GetApplicationAccessToken();
parameters.access_token = ac.access_token;
dynamic result = fb.Post(CanvasAuthorizer.FacebookWebRequest.UserId + "/scores", parameters);
}
Answer:-
Actually for using SCORE Graph API you need the "Application access token" which is different than a normal access token
So if you want your task to be done GET an Application access token by using the following script.......
And then replace the generated application_access_token with old access_token, that's it
The below code is written in php try convert it in c# and then apply it
$APPLICATION_ID = "APP_ID";
$APPLICATION_SECRET = "APP_SECRET";
$token_url = "https://graph.facebook.com/oauth/access_token?" .
"client_id=" . $APPLICATION_ID .
"&client_secret=" . $APPLICATION_SECRET .
"&grant_type=client_credentials";
$app_token = file_get_contents($token_url);
After getting this application access token you can easily do this task.
When You Need An Application Access Token
You need to use a Facebook application access token when you have a process that acts on behalf of the application, rather than on behalf of a particular user. This happens when you access your Facebook Insights data for your app via the graph, and also when you want to create test Facebook users for your app.
Sadly, the documentation for this is buried in the authentication guide for the Facebook graph API.
Your application need to take "publish_actions" permission from user to update the score.
Refer to Create or update a score for a user section of the below documentation.
https://developers.facebook.com/docs/score/