I'm trying to write a windows service that will post to my Facebook Page with results when it runs.
I just downloaded Facebook C# SDK v6.0.10.0 and writing the windows application in .Net 4.0
I created a facebook application account and got the AppID and Secret code needed.
The end goal would be to have this windows service post on my facebook page wall as the page and not the application user.
I keep getting an error when I go to get the accounts for my facebook application.
string strAppID = "my app api id";
string strSecret = "my app secret code";
Facebook.FacebookClient fbClient = new Facebook.FacebookClient();
fbClient.AppId = strAppID;
fbClient.AppSecret = strSecret;
dynamic ac = fbClient.Get("oauth/access_token", new
{
client_id = strAppID,
client_secret = strSecret,
grant_type = "client_credentials"
});
string strAccessToken = String.Empty;
strAccessToken = ac.access_token;
if (!String.IsNullOrEmpty(strAccessToken))
{
fbClient = new Facebook.FacebookClient(strAccessToken);
fbClient.AccessToken = strAccessToken;
fbClient.AppId = strAppID;
fbClient.AppSecret = strSecret;
//Here is where it is bombing
dynamic fbAccounts = fbClient.Get("/me/accounts");
fbClient = new Facebook.FacebookClient(strAccessToken);
fbClient.AccessToken = strAccessToken;
fbClient.AppId = strAppID;
fbClient.AppSecret = strSecret;
dynamic me = fbClient.Get("**Name of the facebook page I am trying to post to**");
string strPageID = String.Empty;
strPageID = me.id;
string strPageAccessToken = String.Empty;
//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 == strPageID)
{
//When you find it, grab the associated access token and put it in the Dictionary to pass in the FB Post, then break out.
strPageAccessToken = account.access_token;
break;
}
}
try
{
fbClient.AccessToken = strPageAccessToken;
var args = new Dictionary<string, object>();
args["message"] = "Testing 123";
fbClient.Post("/" + strPageID + "/feed", args);
}
catch (Facebook.FacebookOAuthException ex)
{
// oauth exception occurred
}
catch (Facebook.FacebookApiLimitException ex)
{
// api limit exception occurred.
}
catch (Facebook.FacebookApiException ex)
{
// other general facebook api exception
}
catch (Exception ex)
{
// non-facebook exception such as no internet connection.
}
}
The error I am getting is on the line:
dynamic fbAccounts = fbClient.Get("/me/accounts");
(OAuthException - #2500) An active access token must be used to query information about the current user.
see here: (OAuthException - #2500) An active access token must be used to query information about the current user
you are getting access token for the APPLICATION, not for a user.
Therefore, "me" does not make sense. You should supply ID there -
either your user ID, or your app ID, or any other ID your app has
permissions for.
dynamic ac = fbClient.Get("oauth/access_token", new
{
client_id = strAppID,
client_secret = strSecret,
grant_type = "client_credentials"
});
The above code may not work for version 6.0.
OAuth 2.0 - exchange code for access token
FacebookClient supports parsing only json responses. Due to this
reason “oauth/access_token” token will not work when using
FacebookClient.Get(“oauth/access_token”). Instead you will need to use
a method in FacebookOAuthClient.
You can find more details here: http://blog.prabir.me/post/Facebook-CSharp-SDK-Making-Requests.aspx
Hope this helps.
Related
I am using TweetSharp to send tweets to users (currently testing it) however it keeps coming back with Bad Authentication Data
{"errors":[{"code":215,"message":"Bad Authentication data."}]}
I have checked my app settings and it has full read and write access. I have also tried to regenerate my consumer keys but still not luck.
here is my code
public ActionResult AccessToken()
{
string oauth_consumer_key = "<consumer key>";
string oauth_consumer_secret = "<consumer secret>";
var service = new TwitterService(oauth_consumer_key, oauth_consumer_secret);
// Now we need the Token and TokenSecret
OAuthRequestToken requestToken = service.GetRequestToken("http://localhost:37808/");
string authURL = service.GetAuthorizationUri(requestToken).ToString();
Process.Start(authURL);
SendTweetOptions options = new SendTweetOptions();
options.Status = "Hello there Twitter";
service.SendTweet(options);
var re = service.Response.Response;
return View();
}
Am I doing anything wrong?
Finally solved the issue and it works well. Based upon comments from Yort.
public ActionResult AccessToken()
{
// Step 1 - Retrieve an OAuth Request Token
TwitterService service = new TwitterService(ConfigurationManager.AppSettings["TwitterConsumerKey"], ConfigurationManager.AppSettings["TwitterConsumerSecret"]);
// This is the registered callback URL
OAuthRequestToken requestToken = service.GetRequestToken("http://localhost:37808/Twitter/OToken");
// Step 2 - Redirect to the OAuth Authorization URL
Uri uri = service.GetAuthorizationUri(requestToken);
return new RedirectResult(uri.ToString(), false /*permanent*/);
//return View();
}
public ActionResult OToken()
{
return View();
}
public ActionResult UserInfo(string oauth_token, string oauth_verifier)
{
var requestToken = new OAuthRequestToken { Token = oauth_token };
// Step 3 - Exchange the Request Token for an Access Token
TwitterService service = new TwitterService(ConfigurationManager.AppSettings["TwitterConsumerKey"],
ConfigurationManager.AppSettings["TwitterConsumerSecret"]);
OAuthAccessToken accessToken = service.GetAccessToken(requestToken, oauth_verifier);
// Step 4 - User authenticates using the Access Token
service.AuthenticateWith(accessToken.Token, accessToken.TokenSecret);
TwitterUser user = service.VerifyCredentials(new VerifyCredentialsOptions());
ViewBag.Message = string.Format("{0}", user.ScreenName);
// Step 5 - Send Tweet to User TimeLine
SendTweetOptions options = new SendTweetOptions();
string URL = "file:\\C:\\Users\\<User>\\Desktop\\test.jpg";
string path = new Uri(URL).LocalPath;
// Sending with Media
using (var stream = new FileStream(path, FileMode.Open))
{
service.SendTweetWithMedia(new SendTweetWithMediaOptions
{
Status = "<status>",
Images = new Dictionary<string, Stream> { { path, stream } }
});
}
var responseText = service.Response.StatusCode;
if (responseText.ToString() == "OK")
{
ViewBag.Message = "Tweet Successful";
}
else
{
ViewBag.Message = "Tweet Unsuccessful";
}
return View();
}
}
I don't believe you can send Tweets as just a consumer, the Tweets have to be "owned" by a user account. You need to register a Twitter account, then do the full oauth authentication process to get an access token (in addition to the consumer token), then reauthorise the TweetSharp service using both tokens.
Your code above nearly gets there (I think). After the Process.start call there needs to be logic to use the verifier returned in the browser (a number displayed after the user logs in) to complete the auth process and act as that user. At the moment, your code gets half way through that process but does not complete it, so when you try to tweet your TweetSharp service is only authed as the app and not the user.
The originalTweetSharp readme.md does include the missing bits of code. Step 3 needs the actual verifier returned in the browser after login:
// Step 3 - Exchange the Request Token for an Access Token
string verifier = "123456"; // <-- This is input into your application by your user
OAuthAccessToken access = service.GetAccessToken(requestToken, verifier);
// Step 4 - User authenticates using the Access Token
service.AuthenticateWith(access.Token, access.TokenSecret);
//Now your tweet call should work here.
It also looks like you're doing this in a web app on the server? In which case you're using entirely the wrong oauth flow (I believe). This one is designed for desktop apps, hence the call that starts a new browser process for the user to login with. I'm not entirely sure how the web flow works as I've never used it, but I believe you need to redirect the user to the authorisation url you receive, and the callback registered with Twitter should point back to your site. I think there is some kind of state parameter that can be passed back through the oauth flow so you can implement your own logic to pickup where you left off based on a session id or similar.
I worked on this subject before. You have to developer account before the send tweet because you need tokens and keys. It's my windows service project.
I wrote my tokens and key codes in App.config
<appSettings>
<add key="twitterAccessToken" value="*****"/>
<add key="twitterAccessTokenSecret" value="*****"/>
<add key="twitterConsumerKey" value="*****"/>
<add key="twitterConsumerSecret" value="*****"/>
public static void SendTweet()
{
try
{
GetPixelImageFile();
string key = ConfigurationSettings.AppSettings.Get("twitterConsumerKey");
string secret = ConfigurationSettings.AppSettings.Get("twitterConsumerSecret");
string token = ConfigurationSettings.AppSettings.Get("twitterAccessToken");
string tokenSecret = ConfigurationSettings.AppSettings.Get("twitterAccessTokenSecret");
string message = "Color, Colorful, Pixel, Art, PixelColouring, Follow";
var service = new TweetSharp.TwitterService(key, secret);
service.AuthenticateWith(token, tokenSecret);
using (var stream = new FileStream(#"C:\Images\Pixel.png", FileMode.Open))
{
var result = service.SendTweetWithMedia(new SendTweetWithMediaOptions
{
Status = message,
Images = new Dictionary<string, Stream> { { "john", stream } }
});
SendMail("SendTweet", (result == null ? "" : result.Text));
}
}
catch (Exception ex)
{
SendMail("SendTweet", ex.Message);
}
}
im very new with Facebook apps and read several threads for creating them, but I have some problems with it.
First of all what I want to do: I want to create a web application that is able to post pictures, text and links on a facebook page that is managed by me.
I used the Facebook C# SDK: here!
What I have:
string facebookPageId = "<my page id>";
string app_id = "<my app id>";
string app_secret = "<my app secret>";
string scope = "publish_stream,manage_pages";
var fb = new FacebookClient();
dynamic res = fb.Get("oauth/access_token", new
{
client_id = app_id,
client_secret = app_secret,
grant_type = "client_credentials"
});
var access_token = res.access_token;
dynamic messagePost = new ExpandoObject();
messagePost.access_token = access_token;
messagePost.link = "http://www.test.at";
messagePost.name = "Testbot";
messagePost.caption = "{*actor*} " + "hello this is a test";
messagePost.description = "[SOME_DESCRIPTION]";
FacebookClient app = new FacebookClient(access_token);
app.AppId = app_id;
app.AppSecret = app_secret;
try
{
var result = app.Post("/hrechttest" + "/feed", messagePost);
}
catch (Exception e)
{
}
Well the code runs without any exceptions but in the output window I get the following:
Exception thrown: 'Facebook.FacebookOAuthException' in Facebook.dll
The next problem is:
As I understood it you must link your facebook app with your facebook page, but when I want to do that I cant select the page:
So what I did wrong or missed?
publish_stream is deprecated since many years, publish_pages is the correct permission to post to a Page (as Page).
API reference: https://developers.facebook.com/docs/graph-api/reference/page/feed#publish
Make sure you are using a Page Token, not a User Token:
https://developers.facebook.com/docs/facebook-login/access-tokens
http://www.devils-heaven.com/facebook-access-tokens/
How to create Page Apps is explained in the docs too: https://developers.facebook.com/docs/pages/tabs
I am trying to post to my own status on Facebook using WinForms and the Facebook .NET SDK. I am using the code below to post an image. I get this error:
"The user hasn't authorized the application to perform this action"
I looked at similar questions but they deal with posting from a web app to other user's page which need a manual authorization on a confirmation page.
I am not finding where I grant myself this permission on Facebook. I might be missing a setting in the code too.
Any ideas?
private bool PostImage(string UserToken, string Status, string ImagePath)
{
try
{
FacebookClient fb = new FacebookClient(UserToken);
//for testing. id & name have values -----
dynamic me = fb.Get("me");
var id = me.id;
var name = me.name;
// ----------------------------------------
var imgstream = File.OpenRead(ImagePath);
dynamic response = fb.Post("/me/feed", new
{
message = Status,
file = new FacebookMediaStream
{
ContentType = "image/jpg",
FileName = Path.GetFileName(ImagePath)
}.SetValue(imgstream)
});
return true;
}
catch (Exception ex)
{
return false;
}
}
You are trying to post status on behalf of user means your application need to get permission from user using "publish_actions".
Refer : https://developers.facebook.com/docs/facebook-login/permissions/v2.5#reference-publish_actions
I'm using Facebook C# sdk with the code,
i'm trying to create a new score for a user
but i get this error:
(OAuthException) An active access token must be used to query information about the current user.
what am i missing?
protected void btnAddScore_Click(object sender, EventArgs e)
{
if (CanvasAuthorizer.Authorize())
{
var fb = new FacebookWebClient();
dynamic parameters = new ExpandoObject();
parameters.score = 77;
parameters.access_token = GetAppAccessToken();
try
{
dynamic id = fb.Post("me/scores", parameters);
lblPostMessageResult.Text = "Message posted successfully";
txtMessage.Text = string.Empty;
}
catch (FacebookApiException ex)
{
lblPostMessageResult.Text = ex.Message;
}
}
}
private string GetAppAccessToken()
{
var oauthClient = new FacebookOAuthClient
{
AppId = FacebookWebContext.Current.Settings.AppId,
AppSecret = FacebookWebContext.Current.Settings.AppSecret
};
dynamic result = oauthClient.GetApplicationAccessToken();
string appAccessToken = result.access_token;
return appAccessToken;
}
edit:
I got the answer form here:
http://facebooksdk.codeplex.com/discussions/279307
the new right code is:
if (CanvasAuthorizer.Authorize())
{
var fb = new FacebookClient(CanvasAuthorizer.FacebookWebRequest.AccessToken);
var oauthClient = new FacebookOAuthClient(FacebookApplication.Current);
dynamic parameters = new ExpandoObject();
parameters.score = 100;
dynamic ac = oauthClient.GetApplicationAccessToken();
parameters.access_token = ac.access_token;
dynamic result = fb.Post(CanvasAuthorizer.FacebookWebRequest.UserId + "/scores", parameters);
}
Answer:-
Actually for using SCORE Graph API you need the "Application access token" which is different than a normal access token
So if you want your task to be done GET an Application access token by using the following script.......
And then replace the generated application_access_token with old access_token, that's it
The below code is written in php try convert it in c# and then apply it
$APPLICATION_ID = "APP_ID";
$APPLICATION_SECRET = "APP_SECRET";
$token_url = "https://graph.facebook.com/oauth/access_token?" .
"client_id=" . $APPLICATION_ID .
"&client_secret=" . $APPLICATION_SECRET .
"&grant_type=client_credentials";
$app_token = file_get_contents($token_url);
After getting this application access token you can easily do this task.
When You Need An Application Access Token
You need to use a Facebook application access token when you have a process that acts on behalf of the application, rather than on behalf of a particular user. This happens when you access your Facebook Insights data for your app via the graph, and also when you want to create test Facebook users for your app.
Sadly, the documentation for this is buried in the authentication guide for the Facebook graph API.
Your application need to take "publish_actions" permission from user to update the score.
Refer to Create or update a score for a user section of the below documentation.
https://developers.facebook.com/docs/score/
I am having a problem retrieving the user's access token after he/she has authorized my Facebook application to access their information and post for them, etc... Facebook returns a code query string to my website, so I can receive the access token for the user. I use the following code to get the access code.
string AppKey = "[REMOVED]";
string AppSecret = "[REMOVED]";
var oAuth = new Facebook.FacebookOAuthClient();
oAuth.AppId = AppKey;
oAuth.AppSecret = AppSecret;
oAuth.RedirectUri = new Uri("http://www.mywebsite.com");
Label3.Text = Request.QueryString["code"];
try
{
var accessToken = oAuth.ExchangeCodeForAccessToken(Request.QueryString["code"]);
string accessTokenString = accessToken.ToString();
HttpCookie aCookie = new HttpCookie("MyWebsite_FBAccessToken");
aCookie.Value = accessTokenString;
Response.Cookies.Add(aCookie);
Response.Redirect("~/Process/ProcessToken.aspx");
}
catch (Facebook.FacebookOAuthException error)
{
Label2.Text = error.Message;
}
My code gets held up here:
var accessToken = oAuth.ExchangeCodeForAccessToken(Request.QueryString["code"]);
And I receive the following error.
(OAuthException) Error validating verification code.
Does this seem like there is a problem with my code, or does it look like there may be a setting problem with my Facebook application? I know my App ID and Secret are correct.