How can i post the feed to facebook page as admin using c# sdk? - facebook

I want to update the facebookpage using c# sdk. I have partially successful with this, the problem is whenever I post messages to the page, post is visible only for admin(i am the admin of the page)is logged In. I want the post or feed to be visible to every one who visit the page.
(even admin is logged out post's are not visible to admin also)
The following code i am trying to achieve
public ActionResult FacebookPagePost()
{
string app_id = "xxxx";
string app_secret = "xxx";
string scope = "publish_stream,manage_pages";
string page_Id = "xxX";
if (Request["code"] == null)
{
return Redirect(string.Format(
"https://graph.facebook.com/oauth/authorize?client_id={0}&redirect_uri={1}&scope={2}",
app_id, Request.Url.AbsoluteUri, scope));
}
else
{
try
{
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 = 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 fbAccounts = client.Get("/me/accounts");
dynamic messagePost = new ExpandoObject();
messagePost.picture = "http://pic.com/pic.png";
messagePost.link = "http://www.examplearticle.com";
messagePost.name = "name goes here";
messagePost.description = "description goes here";
//Loop over the accounts looking for the ID that matches your destination ID (Fan Page ID)
foreach (dynamic account in fbAccounts.data) {
if (account.id == page_Id)
{
//When you find it, grab the associated access token and put it in the Dictionary to pass in the FB Post, then break out.
messagePost.access_token = account.access_token;
break;
}
}
client.Post("/" + page_Id + "/feed", messagePost);
}
catch (FacebookOAuthException ex)
{
}
catch (Exception e)
{
}
}
}

1) Create a Facebook App at: developers.facebook.com and get yourself an APPID and APPSECRET. (there are a lot of tutorials online for doing this so I will skip repeating it)
2) Go to: http://developers.facebook.com/tools/explorer and choose your app from the dropdown and click "generate access token".
3) After that do the following steps here:
https://stackoverflow.com/questions/17197970/facebook-permanent-page-access-token to get yourself a permanent page token.
(I can not stress this enough, follow the steps carefully and thoroughly)*
*I have tool I built that does this for me, all I enter is the APPID, APPSECRET and ACCESSTOKEN which the tool then generates a permanent page token for me. Anyone is welcomed to use it and help make it better,
https://github.com/devfunkd/facebookpagetokengenerator
=========================================================================
Ok at this point you should have your APPID, APPSECRET and a PERMANENT PAGE TOKEN.
=========================================================================
In your Visual Studio solution:
4) Using Nuget:Install-Package Facebook
5) Implement the Facebook client:
public void PostMessage(string message)
{
try
{
var fb = new FacebookClient
{
AppId = ConfigurationManager.AppSettings.Get("FacebookAppID"),
AppSecret = ConfigurationManager.AppSettings.Get("FacebookAppSecret"),
AccessToken = ConfigurationManager.AppSettings.Get("FacebookAccessToken")
};
dynamic result = fb.Post("me/feed", new
{
message = message
});
}
catch (Exception exception)
{
// Handle your exception
}
}
I hope this helps anyone who is struggling to figure this out.

Related

Get facebook page token

As off right now i'm creating a post from my private account and on my
page. I'm trying to get the page it self to post the message i have
created. I been reading som documentation about page tokens. But
finding it difficult to find some eksampels. Does anyone of you guys
know the next step to getting to post messages as a page?? Would be
greatly thankful
public void CheckAutorization()
{
string app_Id = "my_app_id";
string app_secret = "my_secret_id";
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 = 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);
var myAccount = client.Get("/me/accounts");
dynamic parameters = new ExpandoObject();
parameters.message = "test message";
parameters.link = "http://www.facebook.com";
parameters.picture = "http://www.fabric.co.uk/wp-content/uploads/2014/06/Facebook-teen-usage.jpg";
parameters.name = "facebook.fo";
parameters.caption = "test caption";
client.Post("/mypageUrl/feed", parameters);
}
}
What you need to post as a Page is a Page Access Token. Take a look at the Facebook docs about how to get it: https://developers.facebook.com/docs/facebook-login/access-tokens
Basically, you just call /me/accounts to get Access Tokens for all Pages and you use the particular Token to post instead of the User Token.
HereĀ“s an article how to create an Extended Page Access Token without using the PHP SDK: http://www.devils-heaven.com/extended-page-access-tokens-curl/

Facebook login stuck in permissions page in dispaly=touch mode- windows 8

I was trying to implement Facebook login in windows 8 application . I am using following url to request Facebook login
https://www.facebook.com/dialog/oauth?client_id=APP_ID&response_type=token&scope=email%2coffline_access%2cpublish_stream&redirect_uri=http%3a%2f%2fwww.facebook.com%2fconnect%2flogin_success.html&display=touch
I am using webview to request this url .I am getting the login page correctly shown below.
After user enter login credential it is getting redirecting to another page and getting stuck there.I guess that page is supposed to be given permissions.I am attaching a screen shown below
Nothing will happen if i click on cancel or install ..
if i am removing display=touch from the request everything will works fine.But the login poge and permissions page are displayed like in web browser.That is not optimized for touch ..
I have tested the same with webbrowser control in wpf..But the problem is still exisiting there. Any ideas?
On Windows 8 You should be using WebAuthenticationBroker.
Here is code example:
private async void Authenticate()
{
//Facebook Authentication Uri
var facebookUri = "https://www.facebook.com/dialog/oauth";
//Standard redirect uri for desktop/non-web based apps
var redirectUri = "https://www.facebook.com/connect/login_success.html";
//Place your appa client id here
var clientId = "";
//The type of token that can be requested
var responseType = "token";
//Response pattern
var pattern = string.Format("{0}#access_token={1}&expires_in={2}", redirectUri, "(?.+)", "(?.+)");
try
{
String FacebookURL = "https://www.facebook.com/dialog/oauth?client_id=" +
clientId + "&redirect_uri=" + Uri.EscapeUriString(redirectUri) + "&scope=read_stream&display=touch&response_type=token";
System.Uri StartUri = new Uri(FacebookURL);
System.Uri EndUri = new Uri(redirectUri);
WebAuthenticationResult WebAuthenticationResult = await WebAuthenticationBroker.AuthenticateAsync(
WebAuthenticationOptions.None,
StartUri,
EndUri);
if (WebAuthenticationResult.ResponseStatus == WebAuthenticationStatus.Success)
{
var response = WebAuthenticationResult.ResponseData.ToString();
}
else if (WebAuthenticationResult.ResponseStatus == WebAuthenticationStatus.ErrorHttp)
{
//Handle HTTP error
}
else
{
//Handle error
}
}
catch (Exception ex)
{
//Handle error
}
}

Using Facebook C# SDK to post to page

I've been using the Facebook C# SDK for sometime now, but have a really old version and am still using the REST API (I think). I'm just concerned with using the API to post to my own Facebook page (I have a WCMS plugin that posts content to our institution's Facebook page). I was wondering if anyone knew of a good tutorial on how to get this setup with the latest version of the SDK? I'm also concerned with how this is going to work when offline_access goes away so any thoughts on that would be appreciated as well. I'd rather not have to go in an manually get a new access token every 60 days. This seems somewhat unnecessary since the app I'm using to do the posting is in the same FB account as the page I'm trying to post to.
Here's one way to do it:
public static string RefreshTokenAndPostToFacebook(string currentAccessToken)
{
string newAccessToken = RefreshAccessToken(currentAccessToken);
string pageAccessToken = GetPageAccessToken(newAccessToken);
PostToFacebook(pageAccessToken);
return newAccessToken; // replace current access token with this
}
public static string GetPageAccessToken(string userAccessToken)
{
FacebookClient fbClient = new FacebookClient();
fbClient.AppId = "app id";
fbClient.AppSecret = "app secret";
fbClient.AccessToken = userAccessToken;
Dictionary<string, object> fbParams = new Dictionary<string, object>();
JsonObject publishedResponse = fbClient.Get("/me/accounts", fbParams) as JsonObject;
JArray data = JArray.Parse(publishedResponse["data"].ToString());
foreach (var account in data)
{
if (account["name"].ToString().ToLower().Equals("your page name"))
{
return account["access_token"].ToString();
}
}
return String.Empty;
}
public static string RefreshAccessToken(string currentAccessToken)
{
FacebookClient fbClient = new FacebookClient();
Dictionary<string, object> fbParams = new Dictionary<string, object>();
fbParams["client_id"] = "app id";
fbParams["grant_type"] = "fb_exchange_token";
fbParams["client_secret"] = "app secret";
fbParams["fb_exchange_token"] = currentAccessToken;
JsonObject publishedResponse = fbClient.Get("/oauth/access_token", fbParams) as JsonObject;
return publishedResponse["access_token"].ToString();
}
public static void PostToFacebook(string pageAccessToken)
{
FacebookClient fbClient = new FacebookClient(pageAccessToken);
fbClient.AppId = "app id";
fbClient.AppSecret = "app secret";
Dictionary<string,object> fbParams = new Dictionary<string,object>();
fbParams["message"] = "Test message";
var publishedResponse = fbClient.Post("/your_page_name/feed", fbParams);
}
I would recommend you start by reading this blog post. http://blog.prabir.me/post/Facebook-CSharp-SDK-Writing-your-First-Facebook-Application-v6.aspx
And this documentation http://csharpsdk.org/docs/making-synchronous-requests
http://blog.prabir.me/post/Facebook-CSharp-SDK-Making-Requests.aspx
and find graph api post
i hope one day prabir and nathan will finish web site docs and we will learn it clearly.for now.just digg the web.

facebook publish to wall as page

I am developing a facebook application.
In my application I'd like to give page administrators the ability to publish to their page's wall, not as a user, but rather as they page itself.
Can this be done? If so how?
Thank you.
Apperently this possible when prompting user with the "manage_pages" permission. Then it is possible to query the page's access token, and perform the operation in the page's name.
You can check this documentation down here:
http://developers.facebook.com/docs/authentication/
And here's a small code sample, of how it might look using the facebook c# sdk:
dynamic pagesInfo = FacebookApp.Api("/me/accounts");
JavaScriptSerializer serializer = new JavaScriptSerializer();
string pageAccessToken = null;
foreach(IDictionary<string,object> page in serializer.DeserializeObject(pagesInfo.data.ToString()))
{
long pageId = long.Parse(page["id"].ToString());
if (pageId == localBusiness.FanPageId)
{
pageAccessToken = page["access_token"].ToString();
}
}
if (pageAccessToken == null)
return;
var pageFbApp = new FacebookApp(pageAccessToken);
// post as application
Dictionary<string, object> parameters = new Dictionary<string, object>()
{
{"from",
new Dictionary<string,object>()
{
{"id" , localBusiness.FanPageId},
{"name" , localBusiness.Name}
}},
{"description", description},
{"link", pageUrl },
{"name", name },
{"picture" , imageUrl }
};
dynamic result = pageFbApp.Post(localBusiness.FanPageId + "/feed", parameters);

DotNetOpenAuth Get Facebook Email Address

I have the following code where its grabbing First/Last name. I realize that email is an extended permission, but what would I need to modify to request extended permissions?
How do I get the email of an authenticated Facebook user through the DotNetOpenAuth?
fbClient = new FacebookClient
{
ClientIdentifier = ConfigurationManager.AppSettings["facebookAppID"],
ClientSecret = ConfigurationManager.AppSettings["facebookAppSecret"],
};
IAuthorizationState authorization = fbClient.ProcessUserAuthorization();
if (authorization == null)
{
// Kick off authorization request
fbClient.RequestUserAuthorization();
}
else
{
var request = WebRequest.Create("https://graph.facebook.com/me?access_token=" + Uri.EscapeDataString(authorization.AccessToken));
using (var response = request.GetResponse())
{
using (var responseStream = response.GetResponseStream())
{
var graph = FacebookGraph.Deserialize(responseStream);
// unique id for facebook based on their ID
FormsAuthentication.SetAuthCookie("fb-" + graph.Id, true);
return RedirectToAction("Index", "Admin");
}
}
}
return View("LogOn");
Add the following bits:
var scope = new List<string>();
scope.Add("email");
fbClient.RequestUserAuthorization(scope);
If you are using VS2012 built in oauth providers you just need to update your oauth package. See the last post on the following link: http://forums.asp.net/t/1847724.aspx/1. The only email I can't retrieve is MS Live. Currently I use facebook, google, and yahoo.