Post to Facebook Page as page - c#

After quite searching i was able to post on Facebook Page as myself. but my target was to post on the Page i manage as the page. I did some more research and i was able to get the access token of the page i manage. when i tried to POST on it, sdk gave me the error that
The user hasn't authorized the application to perform this action
here is my code for your reference :
string app_id = "xxxxx";
string app_secret = "yyyyyyy";
string scope = "publish_actions,manage_pages";
if (Request["code"] == null)
{
string url = string.Format(
"https://graph.facebook.com/oauth/authorize?client_id={0}&redirect_uri={1}&scope={2}",
app_id, Request.Url.AbsoluteUri, scope);
Response.Redirect(url, false);
}
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 = "Check out this funny article";
parameters.link = "http://www.natiska.com/article.html";
parameters.picture = "http://www.natiska.com/dav.png";
parameters.name = "Article Title";
parameters.caption = "Caption for the link";
//zzzzzzz is my fan page
string pageAccessToken = "";
JsonObject jsonResponse = client.Get("me/accounts") as JsonObject;
foreach (var account in (JsonArray)jsonResponse["data"])
{
string accountName = (string)(((JsonObject)account)["name"]);
if (accountName == MY_PAGE_NAME)
{
pageAccessToken = (string)(((JsonObject)account)["access_token"]);
break;
}
}
client = new FacebookClient(pageAccessToken);
client.Post("/zzzzzzz/feed", parameters);

You need the publish_pages permission to post as pages.
https://developers.facebook.com/docs/graph-api/reference/v2.3/page/feed#publish

Your Facebook App Dosn't have manage_page & publish_page permission, instead of this you can create test application and from that u can create test users for your testing .
From there u can manage all the pages posts and data.

Related

Post on facebook page using c# as page using graph api

private void CheckAuthorization()
{
string app_id = "*****";
string app_secret = "******";
string scope = "manage_pages,publish_pages";
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('&'))
{
//meh.aspx?token1=steve&token2=jake&...
tokens.Add(token.Substring(0, token.IndexOf("=")),
token.Substring(token.IndexOf("=") + 1, token.Length - token.IndexOf("=") - 1));
}
}
string access_token = tokens["access_token"];
//tokens["access_token"];
var client = new FacebookClient(access_token);
Dictionary<string, string> data = new Dictionary<string, string>();
client.Post("/1038145769594318/feed", new
{
message = " test page post",
picture = "http://service.extrabucks.in/EmailTemplateCss/7/images/bottom-background2.png",
name = "Nikunj Patel",
link = "www.extrabucks.in",
description = "Test Description",
type = "links"
});
}
}
Hey i am using this code for post on Facebook using c# but the problem is that it's not post as a page it's post as a user. I want to post as a Page in my Fan page. please give me a solution using the above code. and one more thing i want life-time Working access_token what should i do ?
thanks in advance
public static string GetPageAccessToken(string userAccessToken)
{
FacebookClient fbClient = new FacebookClient();
fbClient.AppId = "*****";
fbClient.AppSecret = "**************";
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("opening shortly"))
{
return account["access_token"].ToString();
}
}
return String.Empty;
}
this code is working for me for refreshing page access tokens every time
just add
client.Post("/1038145769594318/feed", new
{
message = " test page post",
picture = "",
name = "Nikunj Patel",
link = "www.extrabucks.in",
description = "Test Description",
type = "photo",
access_token = GetPageAccessToken(access_token)
});

using HttpWebRequest two or more times via c#

I have one problem. I have two methods which use HttpWebRequest. One of them post a message to my facebook wall. Another take count number of likes.
Thare is code:
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('&'))
{
//meh.aspx?token1=steve&token2=jake&...
tokens.Add(token.Substring(0, token.IndexOf("=")),
token.Substring(token.IndexOf("=") + 1, token.Length - token.IndexOf("=") - 1));
}
}
//get wall data
string access_token = tokens["access_token"];
var client = new FacebookClient(access_token);
//post message to my wall or image
dynamic messagePost = new ExpandoObject();
messagePost.message = "I need to get an id of this post";
try
{
var postId = client.Post("me/feed", messagePost);
id_mypost = postId["id"];
}
catch (FacebookOAuthException ex)
{
//handle oauth exception
}
catch (FacebookApiException ex)
{
//handle facebook exception
}
}
This method post message to my wall. Thare is the second method:
if (Response.BufferOutput == true)
{
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('&'))
{
//meh.aspx?token1=steve&token2=jake&...
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);
try
{
string str = client.Get("/me/feed").ToString();
JObject obj = JObject.Parse(str);
JToken jUser = obj["data"];
int numb = jUser.Count();
int id_post = 0;
for (int i = 0; i < numb; i++)
{
if (obj["data"][i]["id"].ToString() == id_mypost)
{
id_post = i;
}
}
string strr = obj["data"][id_post]["likes"].ToString();
string pattern = #"id";
int count_like = 0;
Regex newReg = new Regex(pattern);
MatchCollection matches = newReg.Matches(strr);
foreach (Match mat in matches)
{
count_like++;
}
}
catch (Exception)
{
}
}
So thare is the problem. I use two times HttpWebRequest. So , when I bild my app i got next error: Cannot redirect after HTTP headers have been sent.
Can somebody help me ?
Cannot redirect after HTTP headers have been sent.
This is the error of asynchronous operation. For example if you are using any thread operation and in that thread you try Response.redirect it will give this error.
The response is already sent to client before the statement executes.
Can you please tell me where exactly the error is occurring ?

In Facebook integration I have to access the url of in which access token is given, but instead I am getting my published url in asp.net

I am using the following code on Page_Load of facebook_login page in asp.net web application. After redirecting this url I have got the accesstoken in url but when I try to access this current url via HttpContext.Current.Request.Url.AbsoluteUri it gave the url of app where it is published not the url which is currently in window.
How can I access this access token or userdetails?
var uriParams = new Dictionary<string, string>() {
{"client_id", facebookAppId},
{"response_type", "token"},
{"scope", "user_about_me, read_stream, email"},
{"redirect_uri", "http://apps.facebook.com/appNameHere/"}
};
StringBuilder urlBuilder = new StringBuilder();
foreach (var current in uriParams)
{
if (urlBuilder.Length > 0)
{
urlBuilder.Append("&");
}
var encoded = HttpUtility.UrlEncode(current.Value);
urlBuilder.AppendFormat("{0}={1}", current.Key, encoded);
}
var loginUrl = "http://www.facebook.com/dialog/oauth?" + urlBuilder.ToString();
Response.Redirect(loginUrl);
In Facebook you can set call back url value which should point to your web application. So once you make request to http://www.facebook.com/dialog/oauth and after successfully login Facebook redirect to Callback Url (which is your web application).
Then you have to make call to url : https://graph.facebook.com/oauth/access_token something like this:
StringBuilder uri = new StringBuilder();
uri.Append("https://graph.facebook.com/oauth/access_token?");
uri.Append("client_id=" + ClientKey + "&");
uri.Append("redirect_uri=" + Curl + "&");
uri.Append("scope=offline_access&");
uri.Append("client_secret=" + ClientSecret + "&");
uri.Append("code=" + OAuthCode);
HttpWebRequest req = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(uri);
req.Headers.Add("Authorization", String.Empty);
req.Method = "POST";
req.ServicePoint.Expect100Continue = false;
req.ContentLength = 0;
req.ContentType = "application/x-www-form-urlencoded";
HttpWebResponse resp;
try
{
resp = (HttpWebResponse)req.GetResponse();
System.IO.StreamReader sr = new System.IO.StreamReader(resp.GetResponseStream());
string result = sr.ReadToEnd().Trim();
string[] resultCollection = Regex.Split(result, "&");
string access_token = Regex.Split(resultCollection[0], "=")[1];//This is the access token
//which you want and you can save it to database or some where for further use.
}
catch (WebException ex)
{
resp = (HttpWebResponse)ex.Response;
//pass on the exception
throw ex;
}
UPDATE :
OAuthCode you can get like this, it is available when after successfully login FB redirect to your web app page
OAuthCode = Request.Params["code"];
Header you can pass empty like String.Empty

How to post to the profile of other people using following code

I have the following code:
public void CheckAuthorization()
{
string app_id = "";//Your id here
string app_secret = "";//your secret key
string scope = "publish_stream, manage_pages";
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);
client.Post("me/feed", new { message="Hi"});
}
}
Using this code , I can post to my profile using the line
client.Post("me/feed", new { message="Hi"});
How can I go about posting on other profiles?
Try this:
client.Post("/PROFILE_ID/feed", new { message="Hi"});
More info: https://developers.facebook.com/docs/reference/api/#publishing

exchange code for token facebook-c#-sdk

I am using The Facebook-C#-Sdk v5.0.3 to create a non-canvas webforms app in vb.net and i am having trouble exchanging the returned facebook code for the access_token. Does anyone have an example (C# or vb.net) that I can look at?
Thanks awesome Stackoverflow community!
Try this:
var app = new FacebookClient(FacebookContext.Current.AppId, FacebookContext.Current.AppSecret);
var accessToken = app.AccessToken
or this:
var app = new FacebookClient(new Authorizer().Session.AccessToken);
var accessToken = app.AccessToken
You can use the appId and appSecret as the app accesstoken.
For instance you can do this when debugging an user token to see if it's valid
var client = new FacebookClient();
dynamic result = client.Get("debug_token", new
{
input_token = user.AccessToken,
access_token = string.Format("{0}|{1}", appId, appSecret)
});
Later you can check result.data.is_valid to see if the user token is still valid.
If you need the access_token of a user, you first need to set the scope correctly, later you can do this:
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
{
var 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"], appSecret);
var request = WebRequest.Create(url) as HttpWebRequest;
using (var response = request.GetResponse() as HttpWebResponse)
{
var 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));
}
}
// Get access token from tokens
var accessToken = tokens["access_token"];
}
This will redirect the user to Facebook asking for permission. Then Facebook will return to the return URL with code in the querystring, use that code to retreive the user's access_token.
Keep in mind this will be a short-lived access_token, you will probably have to expand it.

Categories