I am developing an asp.net website and I want to post to facebook from my website so I created an application in facebook and I used below code but wher I run my website I get error
code :
private void Authorization()
{
string AppId = "1138658742823914";
string AppSecret = "87471caa78f52e3919e43c3dc72b542a";
string scope = "public_profile,user_friends";
if (Request["code"]==null)
{
Response.Redirect(string.Format("https://graph.facebook.com/oauth/authorize?client_id={0}&redirect uri={1}&scope={2}",AppId,Request.Url.AbsoluteUri,scope));
}
else
{
Dictionary<string, string> tokens = new Dictionary<string, string>();
string url = string.Format("https://graph.facebook.com/oauth/access_token?client id={0}&redirect uri={1}&scope={2}&code={3}&client_secret={4}",AppId,Request.Url.AbsoluteUri,scope,Request["code"].ToString(),AppSecret);
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
using (HttpWebResponse response=request.GetResponse() as HttpWebResponse)
{
StreamReader reader = new StreamReader(response.GetResponseStream());
string vals = reader.ReadToEnd();
foreach (string token in vals.Split('&'))
{
// meh.aspx?token1=steve&token2=jack&....
tokens.Add(token.Substring(0, token.IndexOf("=")),
token.Substring(token.IndexOf("=") + 1, token.Length - token.IndexOf("=") - 1));
}
}
string access_token = tokens["access_token"];
var client = new FacebookClient(access_token);
client.Post("/me/feed",new { message="Atefeh Ahmadi Hello every One"});
}
error :
Facebook.FacebookOAuthException: (OAuthException - #200) (#200) The user hasn't authorized the application to perform this action
See Picture
It looks like you have not configured your app properly in facebook or you have not mentioned your website url correctly while creating an app on facebook.
Related
I want to create a C# console application to create a post on my FaceBook account wall.
I tried to search how to get this but all i get is information about get access_token in web application where we can add redirect URL : http://localhost.
I am using below code to get an access_token in Console application.
But i get output from this below code is :
{
"access_token": "*****|*************",
"token_type": "bearer"
}
Which App_ID|App_Secret..where user Access_token should be of very big length.
Is this possible to post on facebook account wall using console application??
private const string FacebookApiId = "************";
private const string FacebookApiSecret = "**************************";
private const string AuthenticationUrlFormat =
"https://graph.facebook.com/oauth/access_token?client_id={0}&client_secret={1}&grant_type=client_credentials&scope=manage_pages,offline_access,publish_stream";
static void Main(string[] args)
{
string accessToken = GetAccessToken(FacebookApiId, FacebookApiSecret);
PostMessage(accessToken, "My message");
}
static string GetAccessToken(string apiId, string apiSecret)
{
string accessToken = string.Empty;
string url = string.Format(AuthenticationUrlFormat, apiId, apiSecret, "manage_pages,offline_access,publish_stream");
WebRequest request = WebRequest.Create(url);
WebResponse response = request.GetResponse();
using (Stream responseStream = response.GetResponseStream())
{
StreamReader reader = new StreamReader(responseStream, Encoding.UTF8);
String responseString = reader.ReadToEnd();
NameValueCollection query = HttpUtility.ParseQueryString(responseString);
accessToken = query["access_token"];
}
if (accessToken.Trim().Length == 0)
throw new Exception("There is no Access Token");
return accessToken;
}
I have a c# asp.net web application.
I am using the facebook login through their javascript sdk and it does the login.
Now I have a Simple WYSIWYG Editor in which whatever is added should be posted on the facebook page of that logged in user.
Following is the code:
string FacebookApiId = "952214336368241";
string FacebookApiSecret = "fb2213d66523c8cb0bc99306f46ee457";
string accessToken = GetAccessToken(FacebookApiId, FacebookApiSecret);
PostMessage(accessToken, "My message");
private string GetAccessToken(string apiId, string apiSecret)
{
string AuthenticationUrlFormat = "https://graph.facebook.com/oauth/access_token?client_id={0}&client_secret={1}&grant_type=client_credentials&scope=manage_pages,offline_access,publish_stream";
string accessToken = string.Empty;
string url = string.Format(AuthenticationUrlFormat, apiId, apiSecret);
WebRequest request = WebRequest.Create(url);
WebResponse response = request.GetResponse();
using (Stream responseStream = response.GetResponseStream())
{
StreamReader reader = new StreamReader(responseStream, Encoding.UTF8);
String responseString = reader.ReadToEnd(); // this gives me {"access_token":"952214336368241|McqSGYIMU1eYBZ1zGydWj9hu6Bt","token_type":"bearer"}
NameValueCollection query = HttpUtility.ParseQueryString(responseString);
accessToken = query["access_token"]; // This line throws error
}
//if (accessToken.Trim().Length == 0)
//throw new Exception("There is no Access Token");
return "952214336368241|McqSGYIMU1eYBZ1zGydWj9hu6B"; // hard-coded to get it working;
}
private void PostMessage(string accessToken, string v)
{
try
{
FacebookClient facebookClient = new FacebookClient(accessToken);
dynamic messagePost = new ExpandoObject();
messagePost.access_token = accessToken;
messagePost.message = v;
var result = facebookClient.Post("/[user id]/feed", messagePost);
}
catch (FacebookOAuthException ex)
{
//handle something
}
catch (Exception ex)
{
//handle something else
}
}
This throws error:
{"(OAuthException - #803) (#803) Some of the aliases you requested do not exist: [user id]"}
I even wrote my facebook emailid instead of [user id] but it still does not work and gives me error:
Message: "(OAuthException - #2500) An active access token must be used to query information about the current user."
Can anyone please advise how can I remove this error.
The code is VERY old, offline_access and publish_stream do not exist anymore since many years.
You have to use a Page Token with the publish_pages permission in order to post to your Page with the API.
You can use "me/feed" or "page-id/feed", but not an Email.
Information about Tokens and how to generate them:
https://developers.facebook.com/docs/facebook-login/access-tokens/
https://www.devils-heaven.com/facebook-access-tokens/
Try stuff in the API Explorer before programming: https://developers.facebook.com/tools/explorer/
i want to fetch user details with profile picture using Facebook c# SDK.I have done some coding and able to login using Facebook in my app.I am explaining my code below.
immediateHelp.aspx.cs:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
if (Request.Params["code"] != null)
{
//Facebook.FacebookAPI api = new Facebook.FacebookAPI();
FacebookClient client = new Facebook.FacebookClient(GetAccessToken());
object me = client.Get("/me");
lblTextImage.ImageUrl="need picture here" ;
lblTextEmail.Text="need email here";
// JSONObject meFriends = client.Get("/me/friends");
}
}
}
private string GetAccessToken()
{
if (HttpRuntime.Cache["access_token"] == null)
{
Dictionary<string, string> args = GetOauthTokens(Request.Params["code"]);
HttpRuntime.Cache.Insert("access_token", args["access_token"], null, DateTime.Now.AddMinutes(Convert.ToDouble(args["expires"])), TimeSpan.Zero);
}
return HttpRuntime.Cache["access_token"].ToString();
}
private Dictionary<string, string> GetOauthTokens(string code)
{
Dictionary<string, string> tokens = new Dictionary<string, string>();
string clientId = "*************";
string redirectUrl = "http://localhost:3440/immediateHelp.aspx";
string clientSecret = "************************";
string scope = "user_photos,email";
string url = string.Format("https://graph.facebook.com/oauth/access_token?client_id={0}&redirect_uri={1}&client_secret={2}&code={3}&scope={4}",
clientId, redirectUrl, clientSecret, code, scope);
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
StreamReader reader = new StreamReader(response.GetResponseStream());
string retVal = reader.ReadToEnd();
foreach (string token in retVal.Split('&'))
{
tokens.Add(token.Substring(0, token.IndexOf("=")),
token.Substring(token.IndexOf("=") + 1, token.Length - token.IndexOf("=") - 1));
}
}
return tokens;
}
I need to attach image in image field and email in text Box after login.I need also logout properties with destroy session using Facebook c# SDK.Please help me to resolve this.
The following code will help you get email and profile picture. The code client.Get("/me?fields=picture")) return picture in format of Json so that we need to extract the url as the code show :
FacebookClient client = new FacebookClient(access_token);
dynamic myInfo = fb.Get("/me?fields=email");
var picture = (((JsonObject)(JsonObject)client.Get("/me?fields=picture"))["picture"]);
var url = (string)(((JsonObject)(((JsonObject)picture)["data"]))["url"]);
lblTextImage.ImageUrl=url;
lblTextEmail.Text=myInfo.email;
Hop this work for you.
I have a website write (.net 4) and i am tring to create some facebook login.
After i download Facebook sdk for c#, i am tring to get user info using the access token.
It seems to me that i am doing something wrong, all the examples i examined, were little bit diffrent from mine. instead of getting me paramethers by :
me["id"] // mine
me.id // examples
when i try to get values like the examples i got errors.
also i am having problem with get the email address of user, already add email to scope:
This method responsible for get the access token:
public string GetAccessToken()
{
Dictionary<string, string> tokens = new Dictionary<string, string>();
string url = string.Format("https://graph.facebook.com/oauth/access_token?client_id={0}&redirect_uri={1}&scope={2}&code={3}&client_secret={4}",
strAppId, Request.Url.AbsoluteUri, strScope, Request["code"].ToString(), strAppSecret);
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
StreamReader reader = new StreamReader(response.GetResponseStream());
string vals = reader.ReadToEnd();
foreach (string token in vals.Split('&'))
{
tokens.Add(token.Substring(0, token.IndexOf("=")),
token.Substring(token.IndexOf("=") + 1, token.Length - token.IndexOf("=") - 1));
}
}
string access_token = tokens["access_token"];
return access_token;
}
This method responsible for get user information:
public string GetUserInfo(string strToken)
{
var client = new FacebookClient(strToken);
dynamic me = client.Get("me");
User user = new User();
try
{
string user_id = me["id"];
string user_first_name = me["first_name"];
string user_last_name = me["last_name"];
string user_name = me["username"];
string user_location = me["location"]["name"];
string user_city = me["hometown"]["name"];
//user_mail = me.email; }
catch(Exception ex)
{
}
return string.Empty;
}
when try to run on me.email or me["email"] i get this error:
'me.email' threw an exception of type 'Microsoft.CSharp.RuntimeBinder.RuntimeBinderException' dynamic {Microsoft.CSharp.RuntimeBinder.RuntimeBinderException}
I suggest you to use Microsoft.AspNet.Mvc.Facebook. It's easy to use and has all these properties already done.
http://www.asp.net/mvc/tutorials/mvc-4/aspnet-mvc-facebook-birthday-app
I manage get access token from FB.
I can post on wall. But I need to display popup window (dialog?) to allow user add comment and see what he posting (sharing).
Im confused with Open graph which I believe I use and graph API. Is the same thing?
Bellow is my code:
private string CheckAuthorization()
{
string app_id = "xxxxxxxxxxxxxxxx";
string app_secret = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
string scope = "publish_stream,email,user_location,user_birthday";
if (Request["code"] == null)
{
Response.Redirect(string.Format("https://graph.facebook.com/oauth/authorize?client_id={0}&redirect_uri={1}&scope={2}",
app_id, Request.Url.AbsoluteUri, scope));
}
else
{
Dictionary<string, string> tokens = new Dictionary<string, string>();
string url = string.Format("https://graph.facebook.com/oauth/access_token?client_id={0}&redirect_uri={1}&scope={2}&code={3}&client_secret={4}",
app_id, Request.Url.AbsoluteUri, scope, Request["code"].ToString(), app_secret);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream());
string vals = reader.ReadToEnd();
foreach (string token in vals.Split('&'))
{
tokens.Add(token.Substring(0, token.IndexOf("=")),
token.Substring(token.IndexOf("=") + 1, token.Length - token.IndexOf("=") - 1));
}
return tokens["access_token"];
}
}
Above code working fine Im getting access token (login popup when Im not logged and popup with information about what info will be shared).
Then I post on FB wall:
var client = new FacebookClient(access_token);
client.Post("/me/feed", new { message = "some text to post" });
My question is how to get popup window before post with description what Im posting and option to add user own comment.