Retrieve access token from serverside code - c#

I am new to developing against Facebook. I need to be able to post to other people's walls from my website, which is c#.NET and asp.net. I've already registered a facebook app to do this.
When I press a button on my website, I want to share content to a list of my own users that have provided me with their facebook URLs. They will have granted the FB app permission to their wall.
There's not a lot of information on how to do this. I need to:
Retrieve a new accesstoken, server side, using Facebook SDK.
Given a facebook url, get a user's profile
Share a link to their wall.

i used php and javascript to connect FB SDK. i don't know it can implement to c#
you can get accessToken by FB.getLoginStatus
developers.facebook.com/docs/reference/javascript/FB.getLoginStatus/
you can get some permission for grant what you want by "scope" parameter (look about Graph API)
http://developers.facebook.com/docs/getting-started/graphapi/
share some text to wall(feed) see "Publishing" at Graph API
http://developers.facebook.com/docs/reference/api/publishing/
i hope it help you.
sorry for my English skill.

first download the nuget package or dll from https://github.com/barans/FacebookCsharpSdk
fill the appid and secret from www.facebook.com/developers
var config = new Dictionary<string, object>();
config.Add("appId", "3955.......");
config.Add("secret", "4c1d...............");
config.Add("fileUpload", true); //optional
FacebookClient client = new FacebookClient(config);
this code retrieves the access token
client.getAccessToken();
this code retrieves the current user information which is publicly available. you can replace me with a facebook id like "999999"
client.api("/me", "GET", null));
facebook does not allow server side wall posting to an arbitrary user. you can only post to the current user's wall and first you should ask publish_stream permission. after getting that this piece of code makes a wall post
request.Method = FacebookApiMethodType.POST;
request.Path = "/me/feed";
request.Params = new NameValueCollection();
request.Params.Add("link", "www.arcademonk.com");
request.Params.Add("message", "C# SDK Batch Request Messsage");
you can find the all documentation on github page. hope it helps.

Related

Getting null value for friends while retrieving data from Facebook

I am trying to get friends list from Facebook using Facebook C# SDK.
FacebookClient fb = new FacebookClient();
dynamic me = fb.Get("me");
But I am getting all other data from me except friends related(id,name..) data,
its always giving null value.
Does anyone know what is the Problem?
Yes, the "problem" is stated in the docs:
Friend list now only returns friends who also use your app: The list of friends returned via the /me/friends endpoint is now limited to the list of friends that have authorized your app.
See
https://developers.facebook.com/docs/apps/changelog#v2_0_login
FB has (somewhat) recently changed their API such that when you request the logged in user's friends, you only get those friends who are also using your FB application.
Unless you register your FB app as a game, you will not be able to see all of the logged in user's friends, only those who have also logged into your app, and have not disabled the option to show up in other people's friend lists.
Be aware that you can't simply lie that you are making a game, FB has to review your app before giving you persmissions to see the full friends list.

Youtube API V3 authentication. Uploading to shared account

I'm trying to update an existing Asp.Net application using C# to avoid the Youtube V2 API deprecation. The 1st challenge is figuring out how to authenticate using the new API.
This is how the application currently authenticates:
string developerKey = (My Developer Key here);
string username = (My username here);
string password = (My password here);
ytService = new YouTubeService("SampleApplication", developerKey);
ytService.setUserCredentials(username, password);
I've researched, and reviewed the V3 API examples, and they all use OAuth2 to Authenticate like this:
UserCredential credential;
using (var stream = new FileStream("client_secrets.json", FileMode.Open, FileAccess.Read))
{
credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
GoogleClientSecrets.Load(stream).Secrets,
// This OAuth 2.0 access scope allows an application to upload files to the
// authenticated user's YouTube channel, but doesn't allow other types of access.
new[] { YouTubeService.Scope.YoutubeUpload },
"user",
CancellationToken.None
);
}
However, that prompts the user to login to their own Google account, and for this application we want all uploaded videos to go into our account. Therefore I would like to continue using the Public API access if possible, and I can't find any examples of this for the V3 APIs.
I've also investigated OAuth2 Service Account, but for the life of me can not figure out how to authenticate using one of those.
Can you help point me in the right direction?
I faced a similar issue recently, except I was working with a shared Google Calendar instead of a Youtube account. What I ended up doing was adding an authorize button that only I could see, which was hooked up to the initial authorize request when clicked. It opened the popup from Google, I gave the permission from the shared account, and I stored the returned access token, refresh token, and expiration date in the database.
Then, whenever users need to view the shared calendar, I just have logic that says if the expiration date has passed, use the stored refresh token to request a new access token and reset the expiration date, then I use the access token to make my Google Calendar API call (getting the events list, in this case).
Unfortunately, V3 of the YouTube API does not support service accounts, and oAuth2 is the only authentication method.
One of the reasons behind this is to do away with having multiple individuals upload into a single account; the legal liability (for both YouTube and app developers) is too great. The only current alternative is the YouTube direct lite program (which has multiple clients ... see YouTube's Github page to find them), which gives you a simple management/admin pane for autogenerating a playlist based on users uploading videos into their own accounts (in other words, they upload the video through your app, to their account, but your account gets a record of it and manages what can/can't appear on the list).

Issue with posting on business page of facebook using c# sdk

I have read many many articles tonight and still do not understood what I shoud do to post on business page of facebook. Here is my code:
string token = getHtml("https://graph.facebook.com/oauth/access_token?client_id=clientID&client_secret=secretKey&grant_type=client_credentials");
token = token.Replace("access_token=", "");
FacebookClient fbClient = new FacebookClient(token);
var args = new Dictionary<string, object>();
args["message"] = "Testing 12qwe3";
fbClient.Post("/pageID/feed", args);
It always says app not authorized. How to authorize it? I read so many articles, but still not able to do it.
I am posting this after totally failing from researching many articles. Kindly let me know whats wrong?
----UPDATE
I did the first part, by making myself the manager page and then creating an app and then providing that app the ability to manage pages and publish etc...but again another issue when i do so even using the above code i still get the same error.But when i use the tools (GRAPH API EXPLORER) portion of facebook site and select this app and generate a token .I than use that directly in app and it posts fine. Kinldy let me know whats wrong!

Facebook C# SDK Fan Page Post From ASP.NET

I know this has been asked many times and I apologize if the answer is readily available but I have not been able to find the answer.
I'm using VS 2010 with the newest version of Facebook C# SDK. I installed it using the "Install-Package Facebook" command from my package manager in VS.
After spending quite a bit of time researching how to use the SDK, I am authenticating with FB through the Facebook Javascript SDK. Actually I followed the steps from the Getting Started Tutorial. And was quite successful in my endeavors. I now have a "Login" button on my aspx page, which brings up the login window and allows me to authenticate via that. I was also able to store my access token in a session variable and have it for use.
I have tested this by doing a Get on my FacebookClient object that I created with my access token and was able to retrieve data about the Fan Page.
So having said all this, in order to let you know that I have had some success. I was ready to start posting to the Fan Page via my web site and found this link Simplest way to post to a facebook fan page's wall with C#!
I thought - great! This is exactly what I need. After copying the code from this post, I am now getting an "Unknown Type" on the ExpandoObject.
For the sake of convenience, here is the code that I copied.
if (Session["AccessToken"] != null)
{
var accessToken = Session["AccessToken"].ToString();
dynamic messagePost = new ExpandoObject();
messagePost.access_token = "[YOUR_ACCESS_TOKEN]";
messagePost.picture = "[A_PICTURE]";
messagePost.link = "[SOME_LINK]";
messagePost.name = "[SOME_NAME]";
messagePost.caption = "{*actor*} " + "[YOUR_MESSAGE]"; //<---{*actor*} is the user (i.e.: Aaron)
messagePost.description = "[SOME_DESCRIPTION]";
FacebookClient app = new FacebookClient(accessToken);
app.Post("/" + [PAGE ID] + "/feed", messagePost);
}
So my questions are really about the ExpandoObject. Is this object still in the SDK? If so, what am I missing and if not, how should I be making this call?
And while I'm asking, is there something else I need to do when requesting the access token in order to get the proper permissions to post on the Fan Page? As stated above, I followed the Getting Started page on Facebook C# SDK Site to get my access token. The reason I ask is because throughout my research I have been coming across different posts talking about making sure you have the proper permissions in order to do different things in Facebook.
Any help is greatly appreciated,
Dan
I guess I just needed to do a little more poking around in StackOverflow to find my answer. I will go ahead and post it here for anyone else that might be having the same issue.
As it turns out with the latest version of Facebook C# SDK, the way to post anything is by using the FacebookClient object and then calling the Post method on that object. Pretty easy actually. Here is the code that I used.
if (Session["AccessToken"] != null)
{
var accessToken = Session["AccessToken"].ToString();
FacebookClient app = new FacebookClient(accessToken);
dynamic result = app.Post("/[ID]/feed", new Dictionary<string, object> { { "message", "This Post was made from my website" } });
}
Session["AccessToken"] is my authentication token that was obtained from the user logging into Facebook on the web page, and [ID] is the Id of my Fan Page.

Service Account Google Analytics OAuth AccessType = Offline C#

I've got credentials of an account with access to Google Analytics,
I'm looking to utilise the Analytics Core Reporting API http://code.google.com/apis/analytics/docs/gdata/home.html
I've found examples which use username/password calling setUserCredentials, but have seen comments this is less secure/has a low request limit (And doesn't exist in the lastest client).
Plus I've seem examples which use oauth, but require user interaction and grant access to the users google account.
However I'm looking to run a service which doesn't require any user interaction, and connects to a predefined google account (un-related to the user viewing it).
I can then store the results in a database, and end users can query the results from the database.
I've seen information about using AccessType = Offline when you first login, which then returns an access token and a refreshtoken.
http://code.google.com/apis/accounts/docs/OAuth2WebServer.html#offline
In my example though, the end user will never login to the application.
Could I have a seperate admin application which gets a refresh token, and stores the refresh token in the config/lookup table?
Then the main application can use the refresh token pulling from the config/lookup table, and get an access token to be able to query the Google Analytics account.
I'm looking for a C# example which uses AccessType = Offline, and seperates out the fetching of the refresh token and using the refresh token to get an access token to query the google analytics account.
Create your app https://code.google.com/apis/console/
For you App, turn on access to Google Analytics, and create an OAuth 2.0 client ID for your website.
Browse to:
https://accounts.google.com/o/oauth2/auth?response_type=code&client_id=YOUR_APP_ID.apps.googleusercontent.com&access_type=offline&scope=https://www.googleapis.com/auth/analytics.readonly&redirect_uri=HTTP://YOUR_CALL_BACK_URL
Having changed YOUR_APP_ID, YOUR_CALL_BACK_URL to the relevant values.
Important to include access_type=offline.
Press Grant Access, this will redirect to HTTP://YOUR_CALL_BACK_URL?code=THIS_IS_YOUR_CODE. Copy the code in the URL.
With the code, request the Refresh Token using CMD prompt.
curl -d "code=THIS_IS_YOUR_CODE&client_id=YOUR_APP_ID.apps.googleusercontent.com&client_secret=YOUR_APPS_SECRET_CODE&redirect_uri=HTTP://YOUR_CALL_BACK_URL&grant_type=authorization_code" https://accounts.google.com/o/oauth2/token
Having changed THIS_IS_YOUR_CODE, YOUR_APP_ID, YOUR_APPS_SECRET_CODE, YOUR_CALL_BACK_URL to the relevant values.
Record the refresh_token returned.
Download the latest version of the Core Reporting V3.0 .net libraries
http://code.google.com/p/google-api-dotnet-client/wiki/Downloads
There is a bug in the current version of Google.Apis.Analytics.v3.cs, to fix this copy the code in this file to your local solution (And don’t reference Google.Apis.Analytics.v3.bin)
http://code.google.com/p/google-api-dotnet-client/source/browse/Services/Google.Apis.Analytics.v3.cs?repo=samples&name=20111123-1.1.4344-beta
And change the property Dimensions from a List<system.string> to a string.
Or you'll get an error like me and this guy did http://www.evolutiadesign.co.uk/blog/using-the-google-analytics-api-with-c-shar/
You can then use your Refresh Token, to generate you an Access Token without user interaction, and use the Access Token to run a report against Google Analytics.
using System;
using DotNetOpenAuth.OAuth2;
using Google.Apis.Authentication.OAuth2;
using AnalyticsService = Google.Apis.Analytics.v3.AnalyticsService;
class Program
{
public static void Main()
{
var client = new WebServerClient(GoogleAuthenticationServer.Description, "YOUR_APP_ID.apps.googleusercontent.com", "YOUR_APPS_SECRET_CODE");
var auth = new OAuth2Authenticator<WebServerClient>(client, Authenticate);
var asv = new AnalyticsService(auth);
var request = asv.Report.Get("2012-02-20", "2012-01-01", "ga:visitors", "ga:YOUR_GOOGLE_ANALYTICS_ACCOUNT_ID");
request.Dimensions = "ga:pagePath";
request.Sort = "-ga:visitors";
request.MaxResults = 5;
var report = request.Fetch();
Console.ReadLine();
}
private static IAuthorizationState Authenticate(WebServerClient client)
{
IAuthorizationState state = new AuthorizationState(new string[]{}) { RefreshToken = "REFRESH_TOKEN" };
client.RefreshToken(state);
return state;
}
}
Great Answer Ian and it helped me to get going in the correct Direction more than any other answer I could find online. Something must have changed in the AnalyticsService object because the line:
var request = asv.Report.Get("2012-02-20", "2012-01-01", "ga:visitors", "ga:YOUR_GOOGLE_ANALYTICS_ACCOUNT_ID");
did not work for me and I had to use the following:
var request = asv.Data.Ga.Get("ga:YOUR_GOOGLE_ANALYTICS_ACCOUNT_ID", "2012-01-01", "2012-02-20", "ga:visitors");
Hopefully this will help others like your answer helped me. Thanks!
Ian's answer helped me a lot but I kept getting an error running the curl command. Did some research and found that the steps to get the access code and refresh token can be made easier by going to https://code.google.com/oauthplayground/ and checking your oAuth configuration settings. Top right of the page there is a settings button. selected "Use your own OAuth credentials". You can get your access code and request a refresh token all from here.
Hope this helps.
You can manually get a refresh token from the OAuth Playground.
If you are needing a refresh token for a Service Account as I was, make sure you
Click on the settings on the right.
Check Use your own OAuth credentials
Fill in your Client ID and Secret
Close the settings
Click the Refresh button on step 2
Then save the refresh token for use in your app

Categories