Facebook API get public profile wall posts - c#

I'm making a small widget in c# to get the posts from a public facebook page/profile.
I believe you have to get a access token each time you make a request to the api?
I'm confused as to which access token I need and what url request string to use.
This is what I'm using currently but it brings back an unexpected looking key.
access_token=112121212121212|NxG_8djeufhfywhduEjaeU4J-lh4
(I've typed in random characters as an example of the structure).
string response = "https://graph.facebook.com/oauth/access_token?client_id=" + facebook_AppID + "&client_secret=" + facebook_AppSecret + "&grant_type=client_credentials";
string accesstoken = RequestResponse(response);
Then when I use that code to get the posts from a wall, using:
string urlGetFeed = "https://graph.facebook.com/thepagename?fields=access_token=" + accesstoken2 + ",posts.fields(message,picture)";
I get a ERROR : The remote server returned an error: (400) Bad Request. Error.

For the feed of a Facebook Page, you only need an App Access Token, which is easy to get:
APP-ID|APP-SECRET
For example:
string urlGetFeed = "https://graph.facebook.com/thepagename/feed?access_token=" + [app-id] + "|" + [app-secret];
Also, the Access Token is not a value of "fields", it´s a separate parameter.

The URL you should use is this:
https://graph.facebook.com/[THE_FACEBOOK_ID]/[WHAT_YOU_WANT]?access_token=[YOUR_ACCESS_TOKEN]&limit=[THE_LIMIT]
The first part access the Facebook graph.
The second part is the Facebook Id that you want.
The third part is the thing that you want from the Facebook Id that you entered (posts, feed, activities, etc). Here you must be sure that the Access Token has the permissions for what you want to get.
The fourth part is the Access Token that you get and the limit (if you don't set the limit the default limit from Facebook will be used).
Beware of the access token that you-re getting with the first line of code that you posted. That line will give you a short live access token. You should interchange the short live access token here:
https://graph.facebook.com/oauth/access_token?client_id=[YUOR_CLIENT_ID]&client_secret=[YOURCLIENT_SECRET]&grant_type=fb_exchange_token&fb_exchange_token=[THE_SHORT_LIVE_ACCESS_TOKEN]
EDIT:
What you should do is to include the FB Connect script:
<script type='text/javascript' src='http://connect.facebook.net/en_US/all.js#xfbml=1'</script>
and then use this function to take the user to the FB login (if it's not logged in) and then to the authorize page:
function createAccessToken()
{
FB.init({appId: '[YOUR APP ID]', status: true, cookie: true});
FB.login(function(response)
{
if (response.status == 'connected')
{
if (response.authResponse.accessToken)
{
var token = response.authResponse.accessToken;
}
else
{
alert('You must grant the permissions for this plugin or will not work.');
}
}
else
{
alert('You must be logged in to Facebook to grant permissions.');
}
}, { scope: 'read_stream' }); }
The token variable inside that function will contain the short lived access token to exchange for the long lived one here:
https://graph.facebook.com/oauth/access_token?client_id=[YOUR_CLIENT_ID]&client_secret=[YOURCLIENT_SECRET]&grant_type=fb_exchange_token&fb_exchange_token=[token]
Once you get that token go here to get what you want:
https://graph.facebook.com/[THE_FACEBOOK_ID]/[WHAT_YOU_WANT]?access_token=[YOUR_ACCESS_TOKEN]&limit=[THE_LIMIT]

Related

How do i get the access token from the reques

I'm using account linking on amazon and I've managed to configure it to send my user's acessToken by a Json. I looked in the amazon documentation and it says that I can find the token in context.System.user.accessToken but I can't find this path in my code, could you help me? I guess i need to make an interceptor to get this request and the token, but i have no idea how.
JSON Input with acessToken
Token path
Within the handle function of your intentHandler, the argument handlerInput contains the access token. It is sent for each request:
const { accessToken } = handlerInput.requestEnvelope.context.System.user;
You can also have it within the user's session:
const { accessToken } = handlerInput.requestEnvelope.session.user;
The accessToken field does not appear if null
More detail about Alexa requests in the documentation

How to immediately get id token from google play services Unity Plugin

I'm using https://github.com/playgameservices/play-games-plugin-for-unity plugin to sign in user with his google account , and then i want to get Id Token and send it to my server and register an account for this user in my own database.this is my code to get Id token :
PlayGamesPlatform.Instance.Authenticate(success =>
{
if (success)
{
Debug.Log("Id Token :");
Debug.LogFormat("{0}", PlayGamesPlatform.Instance.GetIdToken());
Debug.Log("End Of Id Token");
}
});
The problem is the first time it prints just empty string , when i call this for the second time (or a moment later) it prints the token. I want to get token immediately or with a callback to make sure that token is recieved .
How to make sure that token is recieved? is there any callback for this?
Thanks
They changed the plugin in new version and now
PlayGamesPlatform.Instance.GetIdToken(Callback)
has a callback function.
If you want to identify a user on your own web service it would be better to use the server auth code. Send this to your server and get the user identity via jwt from google.
GooglePlayGames.OurUtils.PlayGamesHelperObject.RunOnGameThread(() => {
PlayGamesPlatform.Instance.GetServerAuthCode((CommonStatusCodes status, string code) =>
{
Debug.Log("Status: " + status.ToString());
Debug.Log("Code: " + code);
});
});

Getting access token for google+ with requested permissions

I have been using google+ APIs for C# in my desktop application.I have to access the friends list of the google+ user.
I have been obtaining access token by extracting it from browser title.
It works fine for the following permissions(all grouped and asked at same time) and returns the authentication code in browser title(success=authcode).
"https://www.googleapis.com/auth/plus.me
"https://www.googleapis.com/auth/youtube",
"https://www.googleapis.com/auth/youtube.upload"
But when i changed the permission to obtain the friends list,
"https://www.googleapis.com/auth/plus.login
it's not returning the desired auth code ,it just returns success authuser=0&promt...
By the way I can't listen on local web server.
How to obtain the access token by using the above permission?
I just checked this and the success string in the window title is in fact different when you are using the plus.login scope. The code that is returned in the string is still valid though. The following code shows one way you could extract the authorization code from the window title string:
string pollActiveWindowForAuthCode(int sleepTime){
string activeTitle = GetActiveWindowTitle();
while (!activeTitle.StartsWith("Success"))
{
activeTitle = GetActiveWindowTitle();
Thread.Sleep(sleepTime);
}
// strip to start of auth code
string trimToAuthCode = activeTitle.Substring(activeTitle.LastIndexOf("=") + 1);
// trim the " - Google Chrome" text
return trimToAuthCode.Substring(0, trimToAuthCode.IndexOf(' '));
}
I have uploaded a more comprehensive demo to my GitHub:
csharp-gplus-wpf

C# Facebook SDK - How to use web forms to server side authorize canvas application

There are lots of sample applications in MVC but the current project I'm working on requires that I use web forms.
I can authorize the application using the javascript method but I want to use server side. Below is what I started with on the page.load
dynamic parameters = new ExpandoObject();
parameters.client_id = AppId;
parameters.client_secret = appSecret;
parameters.response_type = "code";
//parameters.state = state;
parameters.redirect_uri = "http://fb.local/page.aspx";
// The requested response: an access token (token), an authorization code (code), or both (code token).
parameters.response_type = "token";
// list of additional display modes can be found at http://developers.facebook.com/docs/reference/dialogs/#display
//parameters.display = "popup";
// add the 'scope' parameter only if we have extendedPermissions.
if (!string.IsNullOrWhiteSpace(ExtendedPermissions))
parameters.scope = ExtendedPermissions;
// generate the login url
var fb = new FacebookClient();
var loginUrl = fb.GetLoginUrl(parameters);
Response.Redirect(loginUrl.AbsoluteUri, true);
I can authorize but I'm not able to get the access token from the URL.
On the next page I can view source and see the access token in the url bar but I'm not sure how to go about getting it into the code. once I have the token, I'm all set.
page.aspx#access_token=AAACrxQhmdpY
I used to this code on my page load and works, its not a very clean code, but you may figure out how to change it for your best use. so the algorithm is that when the page loads you redirect the user to Facebook authentication page using response.redirect to a string that contains three parameters:your app ID(appid), what permissions you are asking your user(scope), where you want Facebook to redirect the user after authorization, and a parameter as state which i guess it should be a random number. so after the user authorized your application he/she will be redirected to your page, with a request URL that contains the same state you prepared Facebook with(and you can use to identify who which request was which if there are many requests i guess) and also a new "code" parameter which you pass on to Facebook to obtain access token, you can use Facebook c# sdk to obtain the access token.in my code there is a line that says "if code is not null, go to alireza" and alireza is a line tag after the response.redirect code, this is because you dont want the process to be repeated all over and over (and of course probably the browser show an error).
int intstate;
string strstate;
string redirecturltofb;
string scope;
string appid;
code = Request.QueryString["code"];
if (!String.IsNullOrWhiteSpace(code))
{
goto alireza;
}
appid = "424047057656831";
scope = "user_about_me,user_activities,user_groups,email,publish_stream,user_birthday";
intstate = 45;
strstate = Convert.ToString(intstate);
redirecturltofb = "https://www.facebook.com/dialog/oauth?client_id=" + appid + "&redirect_uri=http://test5-2.apphb.com/&scope=" + scope + "&state=" + strstate;
Response.Redirect(redirecturltofb);
You have to use Javascript SDK to get access token back to code behind.
Use FB.Init as in http://csharpsdk.org/docs/web/getting-started
and do post back on certain conditions to get the access token.
Thank you,
Dharmendra

Facebook access token only valid for user that created the facebook application

I have some JavaScript that logs in a Facebook user and saves the access token to a database:
window.fbAsyncInit = function () {
FB.init({
appId: '<%=FaceBookApplicationId() %>',
status: false, // check login status
cookie: true,
oauth: true
});
};
function facebookLogin() {
FB.login(function(response) {
if (response.authResponse) {
__doPostBack('__Page', 'FacebookDeliveryButton: ' + JSON.stringify(response.authResponse));
} else {
console.log('User cancelled login or did not fully authorize.');
}
}, { scope: 'offline_access,read_stream,publish_stream,user_photos' });
}
A button click fires facebookLogin() which logs in a facebook user, getting a facebook session that includes an access token, which I JSON serialize and post to the server. The server then saves this access token to the database table FacebookDeliveryQueue.
I have a Windows service running that periodically queries the FacebookDeliveryQueue table and attempts to post on a user's wall using the access token we saved earlier:
IQueryable<FacebookDeliveryQueue> toSend = objectContext.FacebookDeliveryQueues.Where(p => !p.IsDelivered);
foreach (FacebookDeliveryQueue facebookDeliveryQueueItem in toSend)
{
string facebookAccessToken = facebookDeliveryQueueItem.Cart.FacebookAccessToken;
string facebookRecipientId = facebookDeliveryQueueItem.Cart.FacebookRecipientId;
var client = new FacebookClient(facebookAccessToken);
dynamic parameters = new ExpandoObject();
parameters.message = facebookDeliveryQueueItem.Cart.CustomMessageBody;
client.Post(facebookRecipientId + "/feed", parameters);
}
My problem is, this ONLY works with access tokens from the user that created the facebook application. E.g.
Success:
I, the creator of this application, log in and pick one of my friends to send a message to, this info is saved to the database, the service runs, my message is posted to my friend's wall.
Failure:
I log in on my dummy test account (approving the app permissions on this account), pick one of my dummy test account's friend, this info is saved to the database, the service runs and throws an invalid access token error.
Any ideas why?
Update: Switched to Oauth login -- no change. Still getting "(OAuthException) Invalid access token signature." when attempting to post to friend's wall.
Looks like you're using facebook's old login methods, which they recently just turned off, so your old access tokens aren't valid anymore? And your javascript isn't generating the right kind of token. Read the latest version of the FB.login documentation for more info on what changes you need to make. Specifically,
pass oauth: true to the FB.init call
check for response.authResponse instead of response.session now.
Also, check that your app isn't in "sandbox mode". Go to the app settings page and click on "advanced". Sandbox mode makes it so that only developers can use the app.
The persistence to the database was silently trimming the access token to 75 characters, which in the case of my own user, was enough (small user id because it's an old account) -- but five characters too short in the case of my test account which has a very large user id.
Woops.

Categories

Resources