Facebook SDK for .NET: Uploading pics to a page from backend - c#

What I am looking to achieve.
I have a WPF application where in, I will be getting access to some pics generated on run time and I wanna post these pics to an album on FB Page(Think server to server interaction ). This process is supposed to be completely self reliant without any input from users. So I did some research and figured you gotta create an app to be able to do it. On further research the process seems to be as follows:
1) Using app secret and app id , get the app access token
2) Get the user access token
3) using this user access token, call {userId}/accounts and from the resulting JSON parse the page id and get the Page Access token.
Now I have successfully retrieved the App Access token and now I am not able to figure out how to get UserAccessToken without which I cant proceed to step 3.
I am using C# SDK for facebook and here is some code
Step 1.
var fbAccess = new FacebookClient();
dynamic resultAccess = fbAccess.Get("oauth/access_token", new
{
client_id = "XXXXXXXXX",
client_secret = "XXXXXXXXXXX",
grant_type = "client_credentials",
redirect_uri = "",
perms = "manage_pages, photo_upload, publish_stream"
});
String app_access_token = resultAccess["access_token"];
Step 2:
FacebookClient fbClient = new FacebookClient(app_access_token );
dynamic resultAccess = fbClient.Get("/{UserID}/accounts", new
{
client_id = "XXXXXXX",
client_secret = "XXXXXXXXXXXXXXXXX",
perms = "manage_pages, photo_upload, publish_stream"
});
The error I am getting is "A user access token is required to request this resource." I have already given the required permission to the app using Graph API Explorer.
Thanks in Advance

Related

How to integrate posting likes on particular a post in facebook using facebook c# sdk

I have used https://developers.facebook.com to generate like button. But this button is for only facebook pages to be liked. I want to implement functionality of posting likes on facebook post using facebook c# sdk. I write below code -
dynamic userTokenResult = client.Get("oauth/access_token", new
{
client_id = strAppID,
client_secret = strSecret,
grant_type = "client_credentials"
});
dynamic res = client.Post("me/og.likes", new
{
#object = "https://www.facebook.com/yourpagename/photos/photoid/?type=3&theater"
});
I am getting below error -
(OAuthException - #2500) An active access token must be used to query information about the current user.

Email Audit API - 403 Forbidden

I am trying to download a user's mailbox using the Email Audit API. I am getting a 403 Forbidden response to this code (the error occurs on the last line, the call to the UploadPublicKey method):
var certificate = new X509Certificate2(System.Web.HttpRuntime.AppDomainAppPath + "key.p12", "notasecret", X509KeyStorageFlags.Exportable);
ServiceAccountCredential credential = new ServiceAccountCredential(
new ServiceAccountCredential.Initializer(serviceAccountEmail)
{
Scopes = new[] { "https://apps-apis.google.com/a/feeds/compliance/audit/" }
}.FromCertificate(certificate));
credential.RequestAccessTokenAsync(System.Threading.CancellationToken.None).Wait();
DebugLabel.Text = credential.Token.AccessToken;
var requestFactory = new GDataRequestFactory("My App User Agent");
requestFactory.CustomHeaders.Add(string.Format("Authorization: Bearer {0}", credential.Token.AccessToken));
AuditService aserv = new AuditService(strOurDomain, "GoogleMailAudit");
aserv.RequestFactory = requestFactory;
aserv.UploadPublicKey(strPublicKey);
I have created the service account in the Developers Console and granted the Client ID access to https://apps-apis.google.com/a/feeds/compliance/audit/ in the Admin console.
Seems to me like the account should have all the permissions it needs, yet it doesn't. Any idea what I am missing?
OK, so I gave up on trying to make it work with a service account even though that is what Google's documentation would lead you to believe is the correct way to do it. After emailing Google support, I learned I could just use OAuth2 for the super user account that created the application on the developer's console.
So then I worked on getting an access token for offline access (a refresh token) by following the process outlined here:
Youtube API single-user scenario with OAuth (uploading videos)
and then taking that refresh token and using it with this code:
public static GOAuth2RequestFactory RefreshAuthenticate(){
OAuth2Parameters parameters = new OAuth2Parameters(){
RefreshToken = "<YourRefreshToken>",
AccessToken = "<AnyOfYourPreviousAccessTokens>",
ClientId = "<YourClientID>",
ClientSecret = "<YourClientSecret>",
Scope = "https://apps-apis.google.com/a/feeds/compliance/audit/",
AccessType = "offline",
TokenType = "refresh"
};
OAuthUtil.RefreshAccessToken(parameters);
return new GOAuth2RequestFactory(null, "<YourApplicationName>", parameters);
}
which is code from here https://stackoverflow.com/a/23528629/5215904 (Except I changed the second to last line... for whatever reason the code shared did not work until I made that change).
So there I was finally able to get myself an access token that would allow me access to the Email Audit API. From there everything was a breeze once I stopped trying to mess around with a service account.

Getting facebook access token in c#

var fb = new FacebookClient();
dynamic result = fb.Get("oauth/access_token", new
{
client_id = "MyAppId",
client_secret = "MyAppSecret",
redirect_uri = "http://www.facebook.com/connect/login_success.html",
code = "code"
});
fb.AccessToken = result.access_token;
I use this piece of code to get facebook access token. When I try to login with any account, there is no problem. However, if I try to post something on that account's wall, I get an error which is;
(OAuthException-#200)(#200) The user hasn't authorized the application
to perform this action.
Also I want to add that if I get the access token from graph api explorer in developers.facebook.com manually and use it in my code as access token, I can post.
P.S: I gave "publish_actions" permission to the account and nothing is changed.
Can you verify that your have requested permissions using /{user-id}/permissions ?
See https://developers.facebook.com/docs/facebook-login/permissions/v2.4 for details.

Posting to a Facebook page without logging in using C#

I've read a lot of posts about how to handle posting to FB without logging in - specifically in my instance to a managed page, some using the defunct "offline_access" method, others relating to tokens.
I've created a token from my graph API - https://developers.facebook.com/tools/explorer
I've also created a little test in some code e.g.
FacebookClient fb = new FacebookClient("Access_Token"]);
Dictionary<string, object> argList = new Dictionary<string, object>();
argList["message"] = "my message";
fb.Post("mypage/feed", argList);
This works perfectly as expected and posts to the page wall in question. If however I log out of Facebook, it doesn't work and in turn throws an error.
Facebook.FacebookOAuthException: (OAuthException - #190)
Error validating access token: This may be because the user logged out
I'm stuck about why this happens when I've set the permissions correctly in the https://developers.facebook.com/tools/explorer area e.g. "publish_stream", "manage_pages" etc.
I've even assigned the token to an app I've created too which still doesn't help.
Has anyone got an example in C# that illustrates how to post when you are not logged in?
Thanks in advance,
Deeds.
Its may be because of access token validation expired, if you have application Id and Secret key of which you used to generate access token, You can use the following code to extend the access token validation period upto 60 days .
public string exchange_access_token(string actoken)
{
var fb = new FacebookClient();
dynamic result = fb.Get("oauth/access_token", new
{
client_id = "xxxxxxxxx",
client_secret = "xxxxxxxxxxxx",
grant_type = "fb_exchange_token",
fb_exchange_token = actoken
});
return result;
}
But if you dont have application details you cant do this ...

c# - how to get user access token without login from facebook?

I want to get user access token(Graph API Explorer) from facebook without login
I tried with app access token but I am unable to get comments for the posts
Code is for app access token:
string appId = "APP_Id";
string appSecret = "APP_Secret";
var fb = new FacebookClient();
dynamic result = fb.Get("oauth/access_token", new
{
client_id = appId,
client_secret = appSecret,
grant_type = "client_credentials"
});
fb.AccessToken = result.access_token;
var accessToken = fb.AccessToken;
Any ideas? Thanks in advance.
You have to create a new instance of the FacebookClient with the Users AccessToken to get info about the User!
I think here is no way you get the Token without calling the FB.Login
From the API Documentation:
User Access Token – The user token is the most commonly used type of token. This kind of access token is needed any time the app calls
an API to read, modify or write a specific person's Facebook data on
their behalf. User access tokens are generally obtained via a login
dialog and require a person to permit your app to obtain one.

Categories

Resources