Contents Posted on Facebook Page not visible? - c#

I am trying to post on my Facebook page using c# and Facebook sdk. I am able to post the contents on my Facebook page but it is not properly visible to others. Even the admin of the page can view only the heading of the post but can not see the picture or the content of that post. But the admin of the page can see the contents of the post by clicking on ">" this sign beside post to page. Please guide me why this is happening and how can I resolve this.
protected void Page_Load(object sender, EventArgs e)
{
CheckAuthorization();
}
private void CheckAuthorization()
{
string app_id = "My App ID";
string app_secret = "My App Secret";
string scope = "publish_stream, publish_actions";
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 = System.Net.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"];
var client = new FacebookClient(access_token);
dynamic parameters = new ExpandoObject();
parameters.message = "Hello This Is My First Post To Facebook";
parameters.link = "http://www.google.com";
parameters.picture = "http://www.mywebsite.com/picture/welcome.jpg";
parameters.name = "Hello Users We welcome you all";
parameters.caption = "Posted By Ashish";
client.Post("/My Facebook Page ID/feed", parameters);
}
}
Please guide me where I am doing wrong since I am trying this for the first time after following certain posts on several websites.

You are using the user access token to post a feed to the page. So, the feeds are posted on behalf the user (not the page), which are visible as summary on the timeline.
If you post the feed on behalf of page admin itself (so that the post is visible normally on the timeline), you need to use the page access token with publish_actions permissions.
And to get the page access token you need to query: /<page-id>?fields=access_token using the normal user token with manage_pages permission.

I just want to add that sometimes your app is in MODE : developer so everything you do is visible only to the developers, it is actually the problem i had, So you need to go to your application Dashboard and look for something like "Review" [i hate giving exact paths because Facebook changes everything every once in a while], and look for something like : Your app is in development and unavailable to the public, put it to public

Related

How to get "user" access token in a Web API using Facebook C# SDK?

I am developing a web API to handle realtime updates (Lead information) from Facebook to integrate with my CRM.
In the WEB API POST request, I am able to capture the leadID but the problem comes when I get leadinfo by invoking FB.Get(LeadID). To make a Graph API GET request(for lead information) I need to have a user access token and this is where i have been struggling for quite sometime. I have looked up several posts online but havent got any solution for my problem.
In my sample implementation, GetLoginUrl(parameters) returns a uri and when when I request the uri in a browser, I see that the access token gets generated in the redirected Uri. But how to do this programatically ? I have tried the following
string FBAccessUrl = "https://graph.facebook.com/oauth/authorize?client_id=XXXXXXXXXXXX&response_type=token&redirect_uri=https://www.facebook.com/connect/login_success.html";
var accessTokenRequest = System.Net.HttpWebRequest.Create(FBAccessUrl);
HttpWebResponse response = (HttpWebResponse)accessTokenRequest.GetResponse();
but then i get this ResponseUri = {https://www.facebook.com/unsupportedbrowser} which is not what I want.
Can someone help me with how the user access token can be generated using C# in the Web API (without the facebook login dialog)
[HttpPost]
[ActionName("Complex")]
public void PostComplex(RootObject root)
{
FacebookClient fb = new FacebookClient();
// Get leadID from the inital HTTP POST request
long leadgen_id = root.entry[0].changes[0].value.leadgen_id;
string leadID = leadgen_id.ToString();
// to get user access token
dynamic parameters = new ExpandoObject();
parameters.client_id = "XXXXXXXXXXXXXXX";
parameters.redirect_uri = "https://www.facebook.com/connect/login_success.html";
parameters.response_type = "token";
// generate the login url
Uri uri = fb.GetLoginUrl(parameters);
// reuest the uri in browser and uri2 is the redirected uri
Uri uri2 = "****************"
string accesstoken = "";
FacebookOAuthResult oauthResult;
if (fb.TryParseOAuthCallbackUrl(uri, out oauthResult))
{
if (oauthResult.IsSuccess)
{
accesstoken = oauthResult.AccessToken;
}
else
{
var errorDescription = oauthResult.ErrorDescription;
var errorReason = oauthResult.ErrorReason;
}
}
fb.AccessToken = accesstoken;
string me = fb.Get(leadID).ToString();
// Then fetch required lead information
}

How to resolve (OAuthException - #190) Error validating access token: This may be because the user logged out or may be due to a system error

I am trying to post on my Facebook fan page using Facebook Graph API. To do this I am using extended Page access token. I was able to post my contents on Facebook, but the moment I logged out from administrator account and tried posting the contents on my Fan Page I am getting this error. Please guide me how can I resolve this issue?
To get Extended Page Access token I have followed these processes-
Created an FB App to get AppID and AppSecret.
Headed over to Facebook Graph API Explorer
On the top right in "Application" I have selected my app which I have created.
Clicked on Get Access Token Button
Added "manage_pages" permission.
Converted short-lived access token into a long lived one by making this Graph API
https://graph.facebook.com/oauth/access_token?client_id=MYID&client_secret=MYSECRET&grant_type=fb_exchange_token&fb_exchange_token=SHORT LIVED TOKEN
Grabbed new long lived access token returned back.
Now I am using this long lived access token in my code. Please guide me how can I resolve this issue.
CS Code-
protected void Page_Load(object sender, EventArgs e)
{
CheckAuthorization();
}
private void CheckAuthorization()
{
string app_id = "XXXXXX";
string app_secret = "XXXXX";
//string my_url = "http://localhost:6943/ashish/Default2.aspx";
string scope = "publish_stream, publish_actions, manage_pages, 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));
}
string access_token = "Long Lived Access Token";
var client = new FacebookClient(access_token);
dynamic parameters = new ExpandoObject();
parameters.message = "xxxxxxxxxxxxxxxxxxxxxxxx";
parameters.link = "XXXXXXXXXXXX";
parameters.picture = "XXXXXXXXXXXXXXXXX";
parameters.name = "XXXXXXXXXXXXXXX";
parameters.caption = "XXXXXXXXXXX";
client.Post("/FB Fan page ID/feed", parameters);
}
}
When receiving this error, you should re-initialise the authentication process. This is due to security reasons; when logging out, all associated access tokens (can be) reset.
You can not solve this issue without interaction from the administrator. So the way to handle this is catching this situation and directing the user to the authentication part in your app.

Post message from Website to Facebook wall

I have a website made with ASP.NET webform .NET 4.5 C#. This site contains a forum(homemade by me), parts of this forum needs to be posted to the specific facebook wall(made for this webpage). What I need :
Post just created thread(message) from specific part of the forum to the corsponding facebook wall.
Optional : Sync the forum thread on webpage with message/comments on the specific facebook page
I have looked at these guides :
http://www.codeproject.com/Articles/569920/Publish-a-post-on-Facebook-wall-using-Graph-API
http://www.c-sharpcorner.com/UploadFile/raj1979/post-on-facebook-users-wall-using-Asp-Net-C-Sharp/
But im not sure that this is really the solution for me? I have tried to follow the guide but it does not look the same.
Edit :
dynamic result;
//https://developers.facebook.com/tools/explorer/
//https://developers.facebook.com/tools/access_token/
FacebookClient client = new FacebookClient(ConfigurationManager.AppSettings["FacebookAppToken"]);
//result = client.Get("debug_token", new
//{
// input_token = ConfigurationManager.AppSettings["FacebookAppToken"],
// access_token = ConfigurationManager.AppSettings["FacebookAppToken"]
//});
//result = client.Get("oauth/access_token", new
// {
// client_id = ConfigurationManager.AppSettings["FacebookAppId"],
// client_secret = ConfigurationManager.AppSettings["FacebookAppSecret"],
// grant_type = "client_credentials",
// //redirect_uri = "http://www.MyDomain.net/",
// //code = ""
// });
result = client.Get("oauth/access_token", new
{
client_id = ConfigurationManager.AppSettings["FacebookAppId"],
client_secret = ConfigurationManager.AppSettings["FacebookAppSecret"],
grant_type = "client_credentials"
});
client.AccessToken = result.access_token;
result = client.Post("[IdOfFacebookPage]/feed", new { message = "Test Message from app" });
//result.id;
result = client.Get("[IdOfFacebookPage]");
return false;
Approach to post to a facebook wall:
You need to register in facebook developer tools.
Create a app (fill a form).
Download FGT 5.0.480 (Facebook graph toolkit)
Reference FGT dlls in your web application.
FGT has methods to post to facebook wall but needs appId.
Use the app id of your app created in step 2.
To post to an user's wall through facebook, it is only possible through an app.
Try this asp .net app, which will allow you to post in your wall:
https://apps.facebook.com/aspdotnetsample/?fb_source=search&ref=br_tf
This will allow you to envision what you need.
Your app gets an appId with which you need to generate auth token.
Limitation: The user's wall where you want to post should have added the app created at step 2, this is compulsory and there is no work around.
When the user accesses the app for the first time, it automatically asks for permission to post to wall--> the user needs to accept it.
Hope this gives you an idea on how to go about doing this.
You can then post into the user's wall.
For Banshee's below request using Facebook SDK for .NET:
userId - facebook user id, wall to post the message
This user should have added the app created by you in step 1 else it will say unauthorized access.
dynamic messagePost = new ExpandoObject();
messagePost.picture = "http://www.stackoverflow.com/test.png";
messagePost.link = "http://www.stackoverflow.com";
messagePost.name = "This is a test name";
messagePost.caption = "CAPTION 1";
messagePost.description = "Test desc";
messagePost.message = "message"
var fb = new FacebookClient();
dynamic result = fb.Get("oauth/access_token", new {
client_id = "app_id",
client_secret = "app_secret",
grant_type = "client_credentials"
});
fb.AccessToken = result.access_token;
try
{
var postId = fb.Post(userId + "/feed", messagePost);
}
catch (FacebookOAuthException ex)
{
//handle oauth exception
}
catch (FacebookApiException ex)
{
//handle facebook exception
}
You will need an extended token to publish to a wall.. Steps to get extended token is explained well by Banshee..
Edit: How to get extended token by Banshee:
Please follow this post
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.

How to login to Instagram from codebehind?

I need to show images of a specific instagram user on my webpage.
As stated in the Instagram API documentation I need to get authenticated to be able to "browse" a user's feed.
"We only require authentication in cases where your application is making requests on behalf of a user (commenting, liking, browsing a user’s feed, etc.)."
(http://instagram.com/developer/authentication/)
So as stated in the API documentation, I send a request to this URL:
https://instagram.com/oauth/authorize/?display=touch&client_id=[ClientID]
&redirect_uri=[callbackuri]/&response_type=token
to be redirected to another URL: http://your_redirect_uri?code=CODE to be able to get the access_token (CODE) to be able to call the instagram RESTful services with it.
The problem is that if my website visitor is not logged in to Instagram, he/she will be forwarded to a login page to authenticate first and only then I can get an access token.
My question is: how can I bypass this login page by automatically login with my application's instagram account from the codebehind (or probably by javascript!)?
I am using C# and Instasharp(http://instasharp.org/) by the way.
Any ideas?
Thank you in advance!
first of create Developer app in Instagram and get consumerkey & consumersecret and set path call back url somthing link http://localhost:3104/Instagram.aspx
private void Authentication()
{
string rest = string.Empty;
GlobusInstagramLib.Authentication.ConfigurationIns config = new GlobusInstagramLib.Authentication.ConfigurationIns("https://instagram.com/oauth/authorize/", ConfigurationManager.AppSettings["consumerKey"], ConfigurationManager.AppSettings["consumerSecret"], ConfigurationManager.AppSettings["callbackurl"], "https://api.instagram.com/oauth/access_token", "https://api.instagram.com/v1/", "");
oAuthInstagram _api = oAuthInstagram.GetInstance(config);
rest = _api.AuthGetUrl("likes+comments+basic+relationships");
Response.Redirect(rest);
}
Automatic redirect on this page and call this code
public void Instagram()
{
string code = (String)Request.QueryString["code"];
oAuthInstagram objInsta = new oAuthInstagram();
GlobusInstagramLib.Authentication.ConfigurationIns configi = new GlobusInstagramLib.Authentication.ConfigurationIns("https://api.instagram.com/oauth/authorize/", ConfigurationManager.AppSettings["consumerKey"], ConfigurationManager.AppSettings["consumerSecret"], ConfigurationManager.AppSettings["callbackurl"], "http://api.instagram.com/oauth/access_token", "https://api.instagram.com/v1/", "");
oAuthInstagram _api = new oAuthInstagram();
_api = oAuthInstagram.GetInstance(configi);
AccessToken access = new AccessToken();
access = _api.AuthGetAccessToken(code);
string accessToken = access.access_token;
string id =access.user.id;
}
you will get token and user id

Can't add album to facebook page with C# SDK

I'm driving myself to despair trying to get an album added to a facebook page using the C# SDK..
I think my code is OK as I can successfully create an album on my own profile page through the SDK and API. So, I expect something's getting confused with my access tokens and permissions etc.
My c# code is here:
string accessToken = "TOKEN HERE";
FacebookClient facebookClient = new FacebookClient(accessToken);
var albumParameters = new Dictionary<string, object>();
albumParameters["message"] = "new message";
albumParameters["name"] = "new name";
facebookClient.Post("/412639422128107/albums", albumParameters);
The error Im getting is:
(OAuthException - #1) An unknown error has occurred.
I've read loads of posts on here and elsewhere on the web about getting the page's access token. Which I'm pretty sure I'm doing right -
I go to this page: https://developers.facebook.com/tools/explorer
I type in "me/accounts"
I see a couple of pages i'm the admin of, and grab the access token that corresponds with my page id that i'm trying to add the album to (412639422128107)
I check the permissions on this access token by going here:
https://developers.facebook.com/tools/debug/access_token?q=
I see that I've got the following permissions: create_event, create_note, manage_pages, photo_upload, publish_actions, publish_stream, read_stream, share_item, status_update, video_upload
But, I'm clearly not doing something quite right as it's not working! Please could anyone point me in the right direction?
Thanks loads in advance :)
you can create an album in the facebook page with this code.
string accessToken = "";
FacebookWebClient fbApp = new FacebookWebClient();
dynamic parametersForToken = new ExpandoObject();
parametersForToken.fields = "access_token";
try
{
dynamic me = fbApp.Get(idExternalPage, parametersForToken);
accessToken = me.access_token;
}
catch (Exception ex)
{
return;
}
FacebookClient facebookClient = new FacebookClient(accessToken);
var albumParameters = new Dictionary<string, object>();
albumParameters["message"] = "new message";
albumParameters["name"] = "new name";
facebookClient.Post("/me/albums", albumParameters);
or try this
https://developers.facebook.com/tools/explorer?method=GET&path='Page_Id'%3Ffields%3Daccess_token
Sorry i'm testing my script, and i have the same problem. (only for creating gallery)
see this bug: https://developers.facebook.com/bugs/376442565760536?browse=search_50361119879b15494037772 (the bug is fixed)

Categories

Resources