Facebook post link to feed fails with uninformative error - facebook

On using Android Facebook SDK, I'm able to successfully post a message to the me/feed (so I guess the problem isn't with the session status or the permissions) but posting a link (with it's additional parameters) fails with error:
{Response: responseCode: 500, graphObject: null, error: {HttpStatus: 500, errorCode: 100, errorType: FacebookApiException, errorMessage: Invalid parameter}, isFromCache:false}
I use hardcoded parameters that are confirmed to work in a different app.
What could this error mean?

I had the same problem and i was looping between it and require upload file permission error while trying to fix it.
I was sharing 2 types of posts : status and photos through using the link
https://www.facebook.com/permalink.php?story_fbid={POST-ID}&id={PAGE-ID}
or
https://www.facebook.com/{PAGE-ID}/posts/{POST-ID}
but recently i found out the facebook seems to have made some changes and this way stopped working for photos, the only way to get it to work was through using the graph api to get the post link that exists with the post object and use it for posting.
example for getting the link from a post:
Request request = new Request(Session.getActiveSession(), mPageID+ "/posts", null, HttpMethod.GET, new Request.Callback() {
public void onCompleted(Response response) {
GraphMultiResult list = response.getGraphObjectAs(GraphMultiResult.class);
if (list != null) {
GraphObjectList<GraphObject> graphOList = list.getData();
for (int i = 0; i < graphOList.size(); i++) {
GraphObject graphObjectItem = graphOList.get(i);
if (graphObjectItem != null) {
Post p = new Post();
if (graphObjectItem.getProperty("link") != null)
p.setURL(graphObjectItem.getProperty("link").toString());
if (graphObjectItem.getProperty("id") != null) {
p.setPostID(graphObjectItem.getProperty("id").toString());
}
}
}
}
}
});
// i use execute and wait because i'm calling the function inside a background task
Request.executeAndWait(request);
function that i used to share the link :
public static void sharePost(String message, String link){
Bundle b = new Bundle();
b.putString("message", message);
b.putString("link", link);
b.putString("access_token", Session.getActiveSession().getAccessToken());
Request postRequest = new Request(Session.getActiveSession(),
"/me/feed", b, HttpMethod.POST, new Request.Callback() {
#Override
public void onCompleted(Response response) {
responseMessage = response.toString();
}
});
Request.executeAndWait(postRequest);
}

Related

Post to group wall using Facebook SDK .net 2015

It seems that nowdays there's no way to allow to post onto facebook user groups via a new, unreviewed app.
I've created an App with live features availible to gen public, with approvements for email, public_profile, user_friends.
I'm trying to post on the wall of a group I've created and I'm an admin of.
Now, when firing up my code, I get the nasty "OAuthException - #200) (#200) Insufficient permission to post to target..." exception.
Posting my wall work perfectly...
public class HomeController : Controller
{
private const long GroupId = 15473890820xxxx;
//
// GET: /Home/
public ActionResult Index(string code)
{
ViewBag.Message = "Welcome to Facebook App Demo!";
//user denied permissions on Facebook.
if (Request["error_reason"] == "user_denied")
{
//this is not implemented. For reference only.
return RedirectToAction("LogOn", "Account");
}
if (string.IsNullOrEmpty(code))
{
ViewBag.Error = "There was an error while loggin into Facebook. Please try again later.";
return RedirectToAction("LogOn", "Account");
}
var fb = new FacebookClient();
dynamic result = fb.Post("oauth/access_token", new
{
client_id = "93199615018xxxx",
client_secret = "2089ae4447877e7388500b844235xxxx",
redirect_uri = "http://localhost:13301/",
code = code
});
var appToken = result.access_token as string;
// update the facebook client with the access token so
// we can make requests on behalf of the user
fb.AccessToken = appToken;
//get extended App/User Token
dynamic result2 = fb.Get("oauth/access_token", new
{
client_id = "93199615018xxxx"
client_secret = "2089ae4447877e7388500b844235xxxx",
grant_type="fb_exchange_token",
fb_exchange_token = appToken,
// code = code
});
var extendedAppToken = result2.access_token as string;
//generate Extended User Token (valid for 60 days)
Session["Facebooktoken"] = extendedAppToken;
dynamic me = fb.Get("me/accounts");
var response = fb.Get("/me/accounts?access_token=" + extendedAppToken) as JsonObject;
return View(me);
}
[HttpPost]
public ActionResult Index(FormCollection collection) //rename to PostWall
{
ViewBag.Message = "Welcome to Facebook App Demo!";
// Post to the wall..
try
{
if (Session["Facebooktoken"] != null)
{
string message = collection["txtPost"].ToString();
FacebookClient client = new FacebookClient(Session["Facebooktoken"].ToString());
dynamic result = client.Post(GroupId+"/feed", new
{
message = message
});
ViewBag.SaveMessage = "Successfuly Post on your wall : " + result.id;
}
else
{
return RedirectToAction("LogOn", "Account");
}
}
catch (Exception ex)
{
ModelState.AddModelError("", ex.Message);
}
return View();
}
public ActionResult About()
{
return View();
}
}
public class AccountController : Controller
{
//
// GET: /Account/
public ActionResult LogOn()
{
return View();
}
[HttpPost]
public ActionResult LogOn(LogOnModel model, string returnUrl)
{
var facebookAppId = "93199615018xxxx";
var facebookAppSecret = "2089ae4447877e7388500b844235xxxx";
var facebookRedirectUrl = "http://localhost:13301/";
//
var facebookScope = "email,publish_pages,publish_actions,manage_pages,user_managed_groups,user_hometown,user_website";
if (facebookAppId != null && facebookAppSecret != null && facebookRedirectUrl != null && facebookScope != null)
{
var url = string.Format(#"https://www.facebook.com/dialog/oauth/?client_id={0}&redirect_uri={1}&scope={2}", facebookAppId, facebookRedirectUrl, facebookScope);
Response.Redirect(url, true);
}
return this.RedirectToAction("Index", "Home");
}
}
Any clue on how to set up an testing environment for above functionality without the extra-round of establishing a fully fledged App that has to be reviewed by Facebook admins? I've looked on testing versions for Apps and Users, but no groups either.
Many thanks in advance
Darren, thanks for your considerations. It seems like due to my privacy restrictions I couldnt get any group info of my personal account. Either programmatically, nor manually in Facebooks Graph API Explorer.
It worked finally on an business (fan)'Page' profile by getting an 'long-lived' Page Access Token in facebooks Access Token Debuger.
Yes, user_managed_groups and publish_actions had been enabled.

Using Prime31 and Facebook GraphAPI to upload a Photo on a Facebook-Page

Using Prime31 i can successfully upload an image to my own wall calling
public void postPhoto(byte[] photoBytes){
Facebook.instance.postImage( photoBytes, "my message", completionHandlerUploadPhoto );
}
But now i want to post the same picture to an album of a Facebook-Page. I tried calling this function i've written:
public void postToFatFishPage(byte[] photoBytes){
Dictionary<string, object> arguments = new Dictionary<string, object>();
arguments.Add("access_token", FacebookAndroid.getAccessToken());
arguments.Add("message", "my message");
arguments.Add("image", photoBytes);
Facebook.instance.graphRequest("/"+facebookPageID+"/photos", HTTPVerb.POST, arguments, ( string error, object obj ) =>
{
Debug.Log ("In Callback postToFatFishPage");
// if we have an error we dont proceed any further
if( error != null ){
Debug.Log("Error posting Photo to FatFish FB-Page: " + error);
return;
}
Debug.Log("No error");
});
}
The Callback function says that there is no error but the Facebook Page i am posting to says there is an error by having no uploaded picture.
I am logging in with the following rights:
FacebookAndroid.loginWithPublishPermissions( new string[] { "email", "user_birthday" } );
Maybe i have to add more rights?
Hope Someone can help me!
EDIT
I also tried out to take an album_id instead of the page_id but neither of it works.
Theres is still no error... I printed out the dictionary of the callback:
{
[id] = <some long number>,
[post_id] = <some even longer number with a underline in center>,
}
I don't know what i did exactly but know it is magically working... (mondays...)
That's the function:
public void postToFatFishPage(byte[] photoBytes){
Dictionary<string, object> arguments = new Dictionary<string, object>();
arguments.Add("access_token", FacebookAndroid.getAccessToken());
arguments.Add("message, myMessage);
arguments.Add("image", photoBytes);
Facebook.instance.graphRequest("/"+pageID+"/photos/", HTTPVerb.POST, arguments, ( string error, object obj ) =>
{
// if we have an error we dont proceed any further
if( error != null ){
Debug.Log("Error posting Photo to FatFish FB-Page: " + error);
return;
}
Debug.Log("SUCCESS!");
});
}
I hope i there is someone i could help :)

How do I post to an application's wall using Fb C# Sdk?

I've been trying to post something to my application's timeline/feed/wall on Fb, for the better part of the day but I keep failing. This is getting frustrating.
What I'm doing is : I'm having a simple console C# app, that is trying to post something on the application's wall (a basic hello world!, for instance).
This snippet shows how I'm retrieving an access token :
private string _AccessToken;
public string AccessToken
{
get
{
if (string.IsNullOrEmpty(_AccessToken))
{
//_AccessToken = string.Format("{0}|{1}", Credentials.AppId, Credentials.AppSecret);
Logger.Debug("Attempting to retrieve the access token...");
dynamic result = ExecuteGet("oauth/access_token", new
{
client_id = Credentials.AppId, // my app id
client_secret = Credentials.AppSecret, // my app secret
grant_type = "client_credentials",
scope = "manage_pages,publish_actions,publish_stream"
}, false);
_AccessToken = result.access_token;
}
Logger.Debug("Operation succeeded, access token is : {0}", _AccessToken);
return _AccessToken;
}
}
private object ExecuteGet(string path, object parameters)
{
return ExecuteGet(path, parameters, true);
}
private object ExecuteGet(string path, object parameters, bool useAccessToken)
{
try
{
Logger.Debug("Executing GET : {0}", path);
var client = useAccessToken ? new FacebookClient(AccessToken) : new FacebookClient();
return client.Get(path, parameters);
}
catch (FacebookApiException ex)
{
Logger.Error("GET Operation failed : {0}", ex.Message);
throw;
}
}
And this is how I'm trying to actually post something :
public void PostToApplicationWall(string message)
{
string path = string.Format("/{0}/feed", Credentials.AppId);
IDictionary<string, object> parameters = new Dictionary<string, object>()
{
{ "description", "[DESCRIPTION] Facebook description..." },
{ "link", "http://tinyurl.org" },
{ "name", "[NAME] Facebook name..." },
{ "caption", "[CAPTION] Facebook caption..." },
{ "message", message }
};
dynamic result = ExecutePost(path, parameters);
}
private object ExecutePost(string path, object parameters)
{
try
{
Logger.Debug("Executing POST : {0}", path);
var client = new FacebookClient(AccessToken);
return client.Post(path, parameters);
}
catch (FacebookApiException ex)
{
Logger.Error("POST Operation failed : {0}", ex.Message);
throw;
}
}
Please note that ExecutePost() uses the AccessToken property, I've pasted in the beginning.
The message that I'm getting is : (OAuthException - #210) (#210) Subject must be a page
Please help, I have no idea what am I doing wrong.
Maciek, if you really just want to post to your own page, writing a standalone app may not be the easiest way to do this. Have you tried PowerShell and http://facebookpsmodule.codeplex.com? This module will take care of the permissioning for you, and let you do this operation with a simple script.
App profile pages are discontinued since Feburary 1st 2012. You have to create an app page. Read here.
Now, when you have an app page, you change your code like this:
string path = string.Format("/{0}/feed", Credentials.PageId);
OR
string path = string.Format("/{0}/feed", Credentials.PageUsername);
[EDIT]
For posting to a page, you need the page access token instead of app access token. Read here on how to get a page access token.

Windows Phone 7 Facebook Image Posting Issue

I know these facebook api stuffs are really became a pain in the ass, after from my longer searches on internet, I could only find a message post API to facebook. I just want to modify it for both message and image posting. Here is relevant code which posts a message to facebook.(Windows Phone 7)
private void PostToWall_Click(object sender, RoutedEventArgs e)
{
if (string.IsNullOrEmpty(txtMessage.Text))
{
MessageBox.Show("Enter message.");
return;
}
var fb = new FacebookClient(_accessToken);
fb.PostCompleted += (o, args) =>
{
if (args.Error != null)
{
Dispatcher.BeginInvoke(() => MessageBox.Show(args.Error.Message));
return;
}
var result = (IDictionary<string, object>)args.GetResultData();
_lastMessageId = (string)result["id"];
Dispatcher.BeginInvoke(() =>
{
MessageBox.Show("Message Posted successfully");
txtMessage.Text = string.Empty;
btnDeleteLastMessage.IsEnabled = true;
});
};
var parameters = new Dictionary<string, object>();
parameters["message"] = txtMessage.Text;
fb.PostAsync("me/feed", parameters);
}
and I have also found a image post code, but I could not integrate it into my code. I think methods are not appropriate with each other.
Here is image post code;
var photo = new WriteableBitmap(0, 0).FromResource("Background200x200.jpg");
FacebookClient app = new FacebookClient();
IDictionary<string, object> parameters = new Dictionary<string, object>();
parameters["access_token"] = _facebookAccessToken; //set in another method where I authenticate...
parameters["name"] = "my picture";
parameters["message"] = "this is a picture uploaded from my the facebook sdk";
var mediaObject = new FacebookMediaObject {
FileName = "Background200x200.jpg",
ContentType = "image/jpeg",
};
mediaObject.SetValue(photo.ToByteArray());
parameters["source"] = mediaObject;
app.ApiAsync(
UploadComplete,
null,
"https://graph.facebook.com/me/feed",
parameters,
HttpMethod.Post);
I just want to post an image with a message. And If you can give me a sample link which posts an image to facebook (I ve been seeking for a ready-coded image post application,that is, Visual studio solution file which I can compile it and XAP it, and run on my phone)
or If you can help me to evolve my message poster to image poster, I would be really pleasured.
THANKS

DotNetOpenAuth Claimed Identifier from Facebook is never the same

I'm using DotNetOpenAuth v3.5.0.10357 and each time a user authenticates against Facebook I get a different claimed identifier back. The token looks to be encrypted so I assume DNOA is somehow encrypting the token along with the expiry. Can anyone confirm this? Or am I using it wrong:
public ActionResult FacebookLogOn(string returnUrl)
{
IAuthorizationState authorization = m_FacebookClient.ProcessUserAuthorization();
if (authorization == null)
{
// Kick off authorization request
return new FacebookAuthenticationResult(m_FacebookClient, returnUrl);
}
else
{
// TODO: can we check response status codes to see if request was successful?
var baseTokenUrl = "https://graph.facebook.com/me?access_token=";
var requestUrl = String.Format("{0}{1}", baseTokenUrl, Uri.EscapeDataString(authorization.AccessToken));
var claimedIdentifier = String.Format("{0}{1}", baseTokenUrl, authorization.AccessToken.Split('|')[0]);
var request = WebRequest.Create(requestUrl);
using (var response = request.GetResponse())
{
using (var responseStream = response.GetResponseStream())
{
var graph = FacebookGraph.Deserialize(responseStream);
var token = RelyingPartyLogic.User.ProcessUserLogin(graph, claimedIdentifier);
this.FormsAuth.SignIn(token.ClaimedIdentifier, false);
}
}
return RedirectAfterLogin(returnUrl);
}
}
Here's the code for FacebookAuthenticationResult:
public class FacebookAuthenticationResult : ActionResult
{
private FacebookClient m_Client;
private OutgoingWebResponse m_Response;
public FacebookAuthenticationResult(FacebookClient client, string returnUrl)
{
m_Client = client;
var authorizationState = new AuthorizationState(new String[] { "email" });
if (!String.IsNullOrEmpty(returnUrl))
{
var currentUri = HttpContext.Current.Request.Url;
var path = HttpUtility.UrlDecode(returnUrl);
authorizationState.Callback = new Uri(String.Format("{0}?returnUrl={1}", currentUri.AbsoluteUri, path));
}
m_Response = m_Client.PrepareRequestUserAuthorization(authorizationState);
}
public FacebookAuthenticationResult(FacebookClient client) : this(client, null) { }
public override void ExecuteResult(ControllerContext context)
{
m_Response.Send();
}
}
Also, I am using the RelyingPartyLogic project included in the DNOA samples, but I added an overload for ProcessUserLogin that's specific to facebook:
public static AuthenticationToken ProcessUserLogin(FacebookGraph claim, string claimedIdentifier)
{
string name = claim.Name;
string email = claim.Email;
if (String.IsNullOrEmpty(name))
name = String.Format("{0} {1}", claim.FirstName, claim.LastName).TrimEnd();
return ProcessUserLogin(claimedIdentifier, "http://facebook.com", email, name, claim.Verified);
}
It looks as though FacebookClient inherits from WebServerClient but I looked for the source on GitHub and I don't see a branch or a tag related (or at least not labeled) with the corresponding v3.5 version.
Facebook does not support OpenID. Claimed Identifier is an OpenID term. Facebook uses OAuth 2.0, so you're mixing up OpenID and OAuth.
Facebook sends a different access token every time, which is normal for the OAuth protocol. You have to use the access token to query Facebook for the user id that is consistent on every visit.
I think you need to add the offline_access permission in the token request as well, see https://developers.facebook.com/docs/reference/api/permissions/