Facebook Id temporarily locked while fetching data from different location - facebook

I am trying to fetch comments from Facebook and trying reply that from the application using the access token again a facebook id.
When I am using that from one location continuously it works well even on dynamic IP of my system for days .. but when I tries to use the same at my home.. it is working for 2 times hardly and then blocks the ID... please help me resolve this.
Code here :
string AccessToken = "Acess token here";
GET_POST_LINK posts;
string url = "https://graph.facebook.com/v2.11/mefields=posts%7Bmessage%2Cpermalink_url%7D&access_token=" + AccessToken + "";
HttpWebRequest feedRequest = (HttpWebRequest)WebRequest.Create(url);
feedRequest.Method = "GET";
feedRequest.Accept = "application/json";
feedRequest.ContentType = "application/json; charset=utf-8";
WebResponse feedResponse = (HttpWebResponse)feedRequest.GetResponse();
using (feedResponse)
{
using (var reader = new StreamReader(feedResponse.GetResponseStream()))
{
posts = JsonConvert.DeserializeObject<GET_POST_LINK>(reader.ReadToEnd());
int count = posts.posts.data.Count;
}
}

Related

Submitting POST request to Facebook Messenger API

I'm struggling to connect to the Facebook Messenger API. The server keeps returning:
The remote server returned an error: (400) Bad Request.
I've been at this for a few days, tried multiple methods, even tried a few VS packages that don't quite work. I've checked my Auth Token several times, and I don't know what else it might be.
Is there something obvious that's causing a bad request? I've copied the root URL from Facebook's API page. The token in the code below has been removed. The application throws an exception when I attempt to read the response. (WebResponse FBresponse = FBrequest.GetResponse();)
private string FBSendMessage(string user, string message)
{
string result = null;
string FBroot = "https://graph.facebook.com/v2.6/me/messages?access_token=";
string token = "EAA...DZD";
string FBURI = FBroot + token;
string FBstring = "{ \"recipient\": { \"id\":\"" + user + "\" }, \"message\": { \"text\":\"" + message + "\" } }";
try
{
//using (WebClient FBclient = new WebClient())
//{
// result =
// FBclient.UploadString(FBURI, FBstring);
//}
HttpWebRequest FBrequest = (HttpWebRequest)WebRequest.Create(FBURI);
FBrequest.Credentials = CredentialCache.DefaultCredentials;
FBrequest.ProtocolVersion = HttpVersion.Version11;
FBrequest.Method = "POST";
FBrequest.ContentType = "application/json";
byte[] FBbytes = Encoding.UTF8.GetBytes(FBstring);
FBrequest.ContentLength = FBbytes.Length;
Stream FBstream = FBrequest.GetRequestStream();
FBstream.Write(FBbytes, 0, FBbytes.Length);
FBstream.Close();
WebResponse FBresponse = FBrequest.GetResponse();
Output((((HttpWebResponse)FBresponse).StatusDescription), Log.Error);
FBstream = FBresponse.GetResponseStream();
StreamReader FBreader = new StreamReader(FBstream);
result = FBreader.ReadToEnd();
FBreader.Close();
FBresponse.Close();
}
catch(Exception ex)
{
Output(ex.Message, Log.Error);
}
return result;
}
I have determined that my code isn't the issue. The issue is that I'm making a request with an invalid user id. Facebook creates a user ID in the application context that isn't the same as your default user id. I have to receive a message to learn that contextualized id before I can send a message.

Can't post on my own business time line. Error says. The user hasn't authorized the application to perform this action

I have a problem when trying to post on my own business time line on facebook.
I get an error that says:
"(OAuthException)(#200) The user hasn't authorized the application to perform this action"
I think this has to do with the scope "publish_actions" in somehow but how can I authorize this publish_actions permission exactly?
I have looked everywhere in my account under "https://developers.facebook.com"
I have put my App for review but I cant add "publish_actions" as a permission for Facebook to review because on this permission there is a message which says: "It looks like you haven't made any API requests to access content with the publish_actions permission in the last 30 days"
But how can I use this permission without having the permission??
I would be very greatful for help if I am on the right track and what I am missing out?
Thank you!
try
{
String appID = "12345";
String appSecret = "123456";
String accessToken = "123|1234_a-b";
String clientToken = "1234567";
String pageID = "123456789";
Facebook.FacebookClient client = new Facebook.FacebookClient(accessToken);
var dicParams = new Dictionary<string, object>();
dicParams["message"] = "Hello on the time line message!";
dicParams["caption"] = string.Empty;
dicParams["description"] = string.Empty;
dicParams["name"] = "Some Name";
dicParams["req_perms"] = "publish_stream,manage_pages,status_update,publish_actions";
dicParams["scope"] = "publish_stream,manage_pages,status_update,publish_actions";
dicParams["access_token"] = accessToken;
var publishResponse = client.Post("/" + pageID + "/feed", dicParams);
MessageBox.Show("You posted on the timeline successfully!");
}
catch (Exception ex)
{ MessageBox.Show(ex.ToString()); }
Attempt 2:
I was looking at the facebook documentation and found an URL which seems relevant to post a message on the business page timeline:
POST graph.facebook.com/{user-id}/feed?message={message}&access_token={access-token}
I have tried to put it down in code like below but again, I receive the same error message:
(OAuthException)(#200) The user hasn't authorized the application to perform this action
Question is what I do wrong. Do I need to get any other access token with "publish_action" permission?. If that is the case I can't figure out how to get such token?
String appID = "12345";
String appSecret = "123456";
String accessToken = "123|1234_a-b";
String clientToken = "1234567";
String pageID = "123456789";
String message = "Hello World";
String requestUrl = "https://graph.facebook.com/" + pageID + "/feed?message=" + message + "&access_token=" + accessToken;
RestSharp.RestClient rc = new RestSharp.RestClient();
RestSharp.RestRequest request = new RestSharp.RestRequest(requestUrl, RestSharp.Method.POST);
request.AddHeader("Content-Type", "application/json");
request.AddHeader("x-li-format", "json");
request.RequestFormat = RestSharp.DataFormat.Json;
RestSharp.RestResponse restResponse = (RestSharp.RestResponse)rc.Execute(request);
RestSharp.ResponseStatus responseStatus = restResponse.ResponseStatus;
//"(OAuthException)(#200) The user hasn't authorized the application to perform this action"
MessageBox.Show(restResponse.Content.ToString());
I have found a solution which works. This code do post a "Message" to the timeline.
Question This code works for my business page. I also like to post on my personal page for friends. So tried to change the pageID to the the ID which is my personal page: (pageID = "987654321") but still it posts on my business page.
I wonder if I need to get a page token specifically for the personal page as well?
If that is the case, I wonder how this token can be achieved?
/*********************************************************************************************************************************************************************/
//STEPS!!! to get a non-expiring page access token:
//1. access the following URL and note the returned access token within the browser's address bar:
//https://www.facebook.com/dialog/oauth?client_id=APP_ID&redirect_uri=REDIRECT_URI&scope=manage_pages,publish_actions&response_type=token
//2. access the following URL and within the returned data find the desired page's name and note the access token:
//https://graph.facebook.com/me/accounts?access_token=ACCESS_TOKEN_RETURNED_FROM_STEP_1
//3. access the following URL and note the returned access token:
//https://graph.facebook.com/oauth/access_token?client_id=APP_ID&client_secret=APP_SECRET&grant_type=fb_exchange_token&fb_exchange_token=PAGES_ACCESS_TOKEN_FROM_STEP_2
//use the Access Token Debugger to ensure your access token's profile ID matches the desired page's ID and it never expires
String newaccesstoken = "aaaaaaaaaaaabbbbbbbbbbbbbbccccccccccccccddddddddddddddddddd";
/*********************************************************************************************************************************************************************/
String appID = "12345";
String appSecret = "123456";
String accessToken = "123|1234_a-b";
String clientToken = "1234567";
String pageID = "123456789"; //Business page
//String pageID = "987654321"; //Personal page
String redirectURI = "http://example.com";
String message = "Hello Facebook";
String imageURL = "http://example.com/images/example-image.png";
String link = "http://example.co";
String caption = "example";
//Post a message to the time line
String requestUrl = "https://graph.facebook.com/" + pageID + "/feed?message=" + message + "&url=" + imageURL +
"&access_token=" + newaccesstoken;
RestSharp.RestClient rc = new RestSharp.RestClient();
RestSharp.RestRequest request = new RestSharp.RestRequest(requestUrl, RestSharp.Method.POST);
request.AddHeader("Content-Type", "application/json");
request.AddHeader("x-li-format", "json");
request.RequestFormat = RestSharp.DataFormat.Json;
RestSharp.RestResponse restResponse = (RestSharp.RestResponse)rc.Execute(request);
RestSharp.ResponseStatus responseStatus = restResponse.ResponseStatus;
MessageBox.Show(restResponse.Content.ToString() + "," + responseStatus.ToString());

Facebook API: error 400 when posting with test user, but works with administrator

I have facebook integrated on my login page, and now I'm trying to call a build-in action: books.rates using a Test App.
My app gets a valid access_token, and creates new feed items without problems. But when I'm tryng to make a books.rates API call, only works if the logged user is a real person (in my tests is me, also the App administrator), and fails allways with Error 400 when I try to rate a book with a Test User.
In both cases, the code is the same (only access_token and userid changes) and has "publish_actions" premission enabled. I think I'm missing something on Test App configuration, but I'm really lost right now.
Thanks!
Update 1
This is the code that makes the action. It's a test code so its very basic
Dictionary<string, string> postInfo = new Dictionary<string, string>();
postInfo["book"] = "http://www.whakoom.com/comics/6jMl7/52/4";
postInfo["rating:value"] = "4";
postInfo["rating:scale"] = "5";
postInfo["fb:explicitly_shared"] = "true";
string graphUrl = string.Format("https://graph.facebook.com/v2.1/{0}/books.rates?access_token={1}", FbUserID, FbAccessToken);
string fbResp = PostPageContent(graphUrl, postInfo);
private static string PostPageContent(string url, Dictionary<string,string> postData)
{
string postInfo = string.Empty;
foreach(string key in postData.Keys)
{
if (postInfo.Length > 0)
postInfo += "&";
postInfo += string.Format("{0}={1}", HttpContext.Current.Server.UrlEncode(key), HttpContext.Current.Server.UrlEncode(postData[key]));
}
var request = WebRequest.Create(url);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = postInfo.Length;
StreamWriter streamOut = new StreamWriter(request.GetRequestStream(), System.Text.Encoding.ASCII);
streamOut.Write(postInfo);
streamOut.Close();
string retValue = string.Empty;
WebResponse response = request.GetResponse();
var reader = new StreamReader(response.GetResponseStream());
retValue = reader.ReadToEnd();
reader.Close();
return retValue;
It seems that Test App with Test Users is unable to make books.rates calls until the main App is approved. The same api calls targeting a real App with a Test User works without problems.

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 C# sdk batch request method return empty data array

I am creating Facebook application which get insights for user's page for multiple metric. Ex. for "page_active_users" and "page_active_users in one batch request.
I am using Facebook C# SDK. But not able to get data from Facebook insights (GraphAPI).
I used 5 different way to get the data but not succeed. By using Graph API method in browser shows data for a page but in batch request it returns empty array of data.
//type1
var para1 = new FacebookBatchParameter(HttpMethod.Get, "MyPageId/insights/")
{
Data = new { access_token = aToken, since = "2012-01-01", metric = "page_active_users" }
};
//type2
var para2 = new FacebookBatchParameter(HttpMethod.Get, "fql/", new
{
q = new[]{
"SELECT value,end_time FROM insights WHERE object_id=MyPageId AND metric='page_active_users' AND end_time=end_time_date('2012-01-01') AND period=86400"
}
}) { Data = new { access_token = aToken } };
//type 3
var para3 = new FacebookBatchParameter().Query(
"SELECT value,end_time FROM insights WHERE object_id=MyPageId AND metric='page_active_users' AND end_time=end_time_date('2012-01-01') AND period=86400");
//type 4
var para4 = new FacebookBatchParameter
{
Path = "MyPageId/insights/",
//Parameters = new {since = "2012-01-01"},
Data = new { access_token = aToken, since = "2012-01-01", metric = "page_active_users" },
HttpMethod = HttpMethod.Get
};
//type 5
var para5 = new FacebookBatchParameter
{
Path = "MyPageId/insights/page_active_users?since=2012-01-01",
//Parameters = new {since = "2012-01-01"},
Data = new { access_token = aToken },
HttpMethod = HttpMethod.Get
};
//Executed all above type by passing it to below method one by one.But always return empty data array while data is exists on Facebook which I tested using Grap API tool.
var result = client.Batch(para1-5);
Any help appreciated.
Thanks in advanced.
Dharmendra Mistry
I found solution on my own. Hope this will help someone. Here is the solution.
///I created an enum for list of metrics that facebook is providing
public enum FacebookMatricType
{
page_active_users,
page_active_users_locale
}
//Created a list of Facebook batch request for each metric using LINQ to Object and //concatenate string using string.format method.
var batchParameters = (from FacebookMatricType matricType in Enum.GetValues(typeof (FacebookMatricType))
select new object[]
{
pPageAccessToken,"insights",matricType.ToString(),pFromDate.Date.ToString("yyyy-MM-dd"),pPageId
}
into objectParamter
select new FacebookBatchParameter
{
HttpMethod = HttpMethod.Get,
Path =
string.Format(
"https://graph.facebook.com/{0}/{1}/{2}?since={3}&access_token={4}",
objectParamter)
}).ToList();
//Once I get the list of request I execute it using facebook web client using C# SDK.
var facebookClient = new FacebookClient(pProfileAccessToken);
var results = facebookClient.Batch(batchParameters.ToArray());
//Results are ready to deserialize.
Thank you. ;)
Dharmendra Mistry