Getting Facebook Auth Token Using FSharp - facebook

I am trying to get the OAuth token from facebook using the following code:
let applicationId = "12345"
let applicationSecret = "12345"
let tokenBuilder = new StringBuilder()
tokenBuilder.Append("https://graph.facebook.com/v2.3/oauth/access_token?")
tokenBuilder.Append("client_id=")
tokenBuilder.Append(applicationId)
tokenBuilder.Append("&redirect_uri=")
tokenBuilder.Append("https://www.facebook.com/connect/login_success.html")
tokenBuilder.Append("&client_secret=")
tokenBuilder.Append(applicationSecret)
let tokenUri = tokenBuilder.ToString()
let tokenClient = new WebClient()
let tokenResponse = tokenClient.UploadString(tokenUri,String.Empty)
When I run it, I get this:
System.Net.WebException: The remote server returned an error: (400)
Bad Request.
Can anyone tell me what I am doing wrong? There are a bunch of configurations that I can make for the application that I guessed like this:

Not exactly the answer to your question, but this is how you can get the OAuth2 bearer token using FacebookClient from Facebook SDK:
// nuget Facebook package
open Facebook
type Credentials() = // There are better ways around to make a POCO, anyways...
member __.client_id with get() = "...your facebook app id here"
member __.client_secret with get() = "...your facebook app secret here"
member __.grant_type with get() = "client_credentials"
let fb = FacebookClient()
let token = fb.Get("oauth/access_token", Credentials())
getting back into token something like:
seq [[access_token, 239907752864330+s3c5obp-fO7DoVX4pPiN69OdAS4]]

Related

Error validating verification code. Please make sure your redirect_uri is identical to the one you used in the OAuth dialog request

My facebook login url
https://graph.facebook.com/v2.3/oauth/access_token?client_id=1105783646200782&redirect_uri=http://petmilyapp.com/test3.php&client_secret=69389226fe79865b3ab557f17e8e54ad&code=AQCgR8S7oM2eZWQVP_U8ieBmPcEy_ztQ3LGbcYDsAGWnn0343kOyS6t6_n8AWGggUbF7ib9pU-q4Nr2QBewRMFLe_MROdzpgvhdYwRaFZlr6geC9pESjUrGGNHxEqkjwftVBbmGd4_QOkZAFNJnJQYeW8hvyHhfgiY-W02HTczpMa3PIIGL6OGO0qoRN8KWkBi84qMBNCQ_OF84u-r9kfeoYML9_BUVJf5LCuzIBYBsQmbrNHBwiYKKHyo3MaUC_k2WRirhFk1mSPfWwwihw3U04hIxYX_KG6qSwZ1wmlp3mhYMdP4FuA2VYIg8i7WwZQxyYzonoDyuH6ZuYq_Rb6qi6
response error
message: "Error validating verification code. Please make sure your redirect_uri is identical to the one you used in the OAuth dialog request"
question
What problem in my url?
All param is getted facebook dev (my app).
I know maybe its too late but I just wanted to comment. If you still having this issue, make sure that you have same FacebookCallBack method name everywhere. I mean, for instance I have an External Login function which returns ;
https://www.facebook.com/dialog/oauth?client_id=" + FB_APP_ID + "&redirect_uri=" + System.Net.WebUtility.UrlEncode(pageUrl + "account/**FacebookLoginCallback**?returnUrl=%2F").Replace("%3F", "&") + "&scope=email&enforce_https=1
and also I have a FacebookLoginCallback method which has exactly the same name with I have above. ("account/FacebookLoginCallback?....")
[HttpGet("**FacebookLoginCallback**")]
public async Task<IActionResult> **FacebookLoginCallback**(string code, string returnUrl)
{
try
{
var myUrl = new Uri(HttpContext.Request.GetDisplayUrl()).GetLeftPart(UriPartial.Authority);
var pageUrl = new UriBuilder(myUrl);
var result = (IDictionary<string, object>)fb.Get("oauth/access_token", new
{
client_id = FB_APP_ID,
client_secret = FB_APP_SECRET,
redirect_uri = pageUrl.Uri.AbsoluteUri.TrimEnd('/') + Url.Action("**FacebookLoginCallback**", "Account", new { returnUrl = returnUrl }),
code = code
});
}
......
}
Please double check your variable/function names if you have those in your url.
Happy Coding
First, both redirect_uri paramaters to authorize and access_token must match.

Can't post on my own business time line. Error says. The user hasn't authorized the application to perform this action

I have a problem when trying to post on my own business time line on facebook.
I get an error that says:
"(OAuthException)(#200) The user hasn't authorized the application to perform this action"
I think this has to do with the scope "publish_actions" in somehow but how can I authorize this publish_actions permission exactly?
I have looked everywhere in my account under "https://developers.facebook.com"
I have put my App for review but I cant add "publish_actions" as a permission for Facebook to review because on this permission there is a message which says: "It looks like you haven't made any API requests to access content with the publish_actions permission in the last 30 days"
But how can I use this permission without having the permission??
I would be very greatful for help if I am on the right track and what I am missing out?
Thank you!
try
{
String appID = "12345";
String appSecret = "123456";
String accessToken = "123|1234_a-b";
String clientToken = "1234567";
String pageID = "123456789";
Facebook.FacebookClient client = new Facebook.FacebookClient(accessToken);
var dicParams = new Dictionary<string, object>();
dicParams["message"] = "Hello on the time line message!";
dicParams["caption"] = string.Empty;
dicParams["description"] = string.Empty;
dicParams["name"] = "Some Name";
dicParams["req_perms"] = "publish_stream,manage_pages,status_update,publish_actions";
dicParams["scope"] = "publish_stream,manage_pages,status_update,publish_actions";
dicParams["access_token"] = accessToken;
var publishResponse = client.Post("/" + pageID + "/feed", dicParams);
MessageBox.Show("You posted on the timeline successfully!");
}
catch (Exception ex)
{ MessageBox.Show(ex.ToString()); }
Attempt 2:
I was looking at the facebook documentation and found an URL which seems relevant to post a message on the business page timeline:
POST graph.facebook.com/{user-id}/feed?message={message}&access_token={access-token}
I have tried to put it down in code like below but again, I receive the same error message:
(OAuthException)(#200) The user hasn't authorized the application to perform this action
Question is what I do wrong. Do I need to get any other access token with "publish_action" permission?. If that is the case I can't figure out how to get such token?
String appID = "12345";
String appSecret = "123456";
String accessToken = "123|1234_a-b";
String clientToken = "1234567";
String pageID = "123456789";
String message = "Hello World";
String requestUrl = "https://graph.facebook.com/" + pageID + "/feed?message=" + message + "&access_token=" + accessToken;
RestSharp.RestClient rc = new RestSharp.RestClient();
RestSharp.RestRequest request = new RestSharp.RestRequest(requestUrl, RestSharp.Method.POST);
request.AddHeader("Content-Type", "application/json");
request.AddHeader("x-li-format", "json");
request.RequestFormat = RestSharp.DataFormat.Json;
RestSharp.RestResponse restResponse = (RestSharp.RestResponse)rc.Execute(request);
RestSharp.ResponseStatus responseStatus = restResponse.ResponseStatus;
//"(OAuthException)(#200) The user hasn't authorized the application to perform this action"
MessageBox.Show(restResponse.Content.ToString());
I have found a solution which works. This code do post a "Message" to the timeline.
Question This code works for my business page. I also like to post on my personal page for friends. So tried to change the pageID to the the ID which is my personal page: (pageID = "987654321") but still it posts on my business page.
I wonder if I need to get a page token specifically for the personal page as well?
If that is the case, I wonder how this token can be achieved?
/*********************************************************************************************************************************************************************/
//STEPS!!! to get a non-expiring page access token:
//1. access the following URL and note the returned access token within the browser's address bar:
//https://www.facebook.com/dialog/oauth?client_id=APP_ID&redirect_uri=REDIRECT_URI&scope=manage_pages,publish_actions&response_type=token
//2. access the following URL and within the returned data find the desired page's name and note the access token:
//https://graph.facebook.com/me/accounts?access_token=ACCESS_TOKEN_RETURNED_FROM_STEP_1
//3. access the following URL and note the returned access token:
//https://graph.facebook.com/oauth/access_token?client_id=APP_ID&client_secret=APP_SECRET&grant_type=fb_exchange_token&fb_exchange_token=PAGES_ACCESS_TOKEN_FROM_STEP_2
//use the Access Token Debugger to ensure your access token's profile ID matches the desired page's ID and it never expires
String newaccesstoken = "aaaaaaaaaaaabbbbbbbbbbbbbbccccccccccccccddddddddddddddddddd";
/*********************************************************************************************************************************************************************/
String appID = "12345";
String appSecret = "123456";
String accessToken = "123|1234_a-b";
String clientToken = "1234567";
String pageID = "123456789"; //Business page
//String pageID = "987654321"; //Personal page
String redirectURI = "http://example.com";
String message = "Hello Facebook";
String imageURL = "http://example.com/images/example-image.png";
String link = "http://example.co";
String caption = "example";
//Post a message to the time line
String requestUrl = "https://graph.facebook.com/" + pageID + "/feed?message=" + message + "&url=" + imageURL +
"&access_token=" + newaccesstoken;
RestSharp.RestClient rc = new RestSharp.RestClient();
RestSharp.RestRequest request = new RestSharp.RestRequest(requestUrl, RestSharp.Method.POST);
request.AddHeader("Content-Type", "application/json");
request.AddHeader("x-li-format", "json");
request.RequestFormat = RestSharp.DataFormat.Json;
RestSharp.RestResponse restResponse = (RestSharp.RestResponse)rc.Execute(request);
RestSharp.ResponseStatus responseStatus = restResponse.ResponseStatus;
MessageBox.Show(restResponse.Content.ToString() + "," + responseStatus.ToString());

Delete Wall Post on page as page C# SDK

I want to delete the post as page.
I already have access token of the admin user and access token from the page.
My Code:
var fbClient = new FacebookClient { AccessToken = getPageAccessToken() };
dynamic parameters = new ExpandoObject();
parameters.id = postId;
fbClient.Delete(m_GroupId + "/feed",parameters);
I get the following error:
{"error":
{
"type":"OAuthException",
"message":"Invalid token: \"PAGE_ID\". An ID has already been specified."
}
}
I replaced the page id above with PAGE_ID
use the page access token and pass the post id as the path for Delete method.
var fb = new FacebookClient("pageAccessToken");
fb.Delete(postId);
I don't know the C# SDK, but from the look of it you're setting the ID twice, once with parameters.id and again with m_GroupID

Integrate yahoo, Google and openid through android and iPhone application?

I am designing an app for iPhone and android in which I have to integrate facebook, twitter, yahoo, gmail, openId. I had integrated facebook and twitter, but how to go for yahoo, gmail and openId? How to login these through app and get the user information?
Please do show me a way to implement this. Any tutorial may help.
Thanks.
To integrate gmail may this url's help you
Google's documentation
Introduction about integrating gmail with iphone
Examples to integrate with iphone
Api's for integrating blogger,google analytics etc
For yahoo you can use this
String YAHOO_RESOURCE_URL = "http://social.yahooapis.com/v1/me/guid/profile?fomat=xml";
String CALLBACK_URL = "oauth://testApp";
String YAHOO_REQUEST_TOKEN_URL = "https://api.login.yahoo.com/oauth/v2/get_request_token";
String YAHOO_ACCESS_TOKEN_URL = "https://api.login.yahoo.com/oauth/v2/get_token";
String YAHOO_AUTHORIZE_URL = "https://api.login.yahoo.com/oauth/v2/request_auth";
// Oauth consumer and provider.
CommonsHttpOAuthConsumer consumer = new CommonsHttpOAuthConsumer(Constants.YAHOO_CONSUMER_KEY, Constants.YAHOO_CONSUMER_SERECT_KEY);
OAuthProvider provider = new CommonsHttpOAuthProvider(YAHOO_REQUEST_TOKEN_URL , YAHOO_ACCESS_TOKEN_URL, YAHOO_AUTHORIZE_URL);
provider.setOAuth10a(true);
// First retrive request token.
String authUrl = provider.retrieveRequestToken(consumer, CALLBACK_URL);
String yahooToken = consumer.getToken();
String yahooTokenSecret = consumer.getTokenSecret();
Open the authUrl in android web browser, this will launch login page, then after login will ask for permissions, accepting the permissions will return in your app using callback url.
Now,
In onResume
Uri uri = this.getIntent().getData();
if (uri != null && uri.toString().startsWith(CALLBACK_URL)) {
String oauthToken = uri.getQueryParameter(oauth.signpost.OAuth.OAUTH_TOKEN);
String oauthVerifier = uri.getQueryParameter(oauth.signpost.OAuth.OAUTH_VERIFIER);
consumer = new CommonsHttpOAuthConsumer(Constants.YAHOO_CONSUMER_KEY, Constants.YAHOO_CONSUMER_SERECT_KEY);
consumer.setTokenWithSecret(yahooToken, yahooTokenSecret);
provider = new CommonsHttpOAuthProvider(YAHOO_REQUEST_TOKEN_URL, YAHOO_ACCESS_TOKEN_URL, YAHOO_AUTHORIZE_URL);
provider.setOAuth10a(true);
// Now retrive access token
provider.retrieveAccessToken(consumer, oauthVerifier);
String token = consumer.getToken();
String tokenSecret = consumer.getTokenSecret();
consumer.setTokenWithSecret(token, tokenSecret);
// Get the GUID from this.
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet request = new HttpGet("http://social.yahooapis.com/v1/me/guid?format=json");
consumer.sign(request);
HttpResponse response = httpClient.execute(request);
Parse the response to get GUID.
// Now use the GUID to get profile info.
DefaultHttpClient httpClient = new DefaultHttpClient();
String strUrl = "http://social.yahooapis.com/v1/user/"+ strGUID +"/profile?format=json";
HttpGet request = new HttpGet(strUrl);
consumer.sign(request);
HttpResponse response = httpClient.execute(request);
Parse the response and njoy :)

Using Facebook Requests 2.0 with the C# SDK

I am trying to update the bookmark count field with the SDK but have not had any success yet.
Can somebody tell me what classes I need to instantiate to do something similar to the following link:
http://developers.facebook.com/blog/post/464
Note:
The link demonstrates how to set the bookmark count and delete it. I would like to be able to do the same with the SDK, any help would be appreciated.
To do this, first you need to get you app's access token:
private string GetAppAccessToken() {
var fbSettings = FacebookWebContext.Current.Settings;
var accessTokenUrl = String.Format("{0}oauth/access_token?client_id={1}&client_secret={2}&grant_type=client_credentials",
"https://graph.facebook.com/", fbSettings.AppId, fbSettings.AppSecret);
// the response is in the form: access_token=foo
var accessTokenKeyValue = HttpHelpers.HttpGetRequest(accessTokenUrl);
return accessTokenKeyValue.Split('=')[1];
}
A couple of things to note about the method above:
I'm using the .Net HttpWebRequest instead of the Facebook C# SDK to grab the app access_token because (as of version 5.011 RC1) the SDK throws a SerializationException. It seems that the SDK is expecting a JSON response from Facebook, but Facebook returns the access token in the form: access_token=some_value (which is not valid JSON).
HttpHelpers.HttpGetRequest simply uses .Net's HttpWebRequest. You can just as well use WebClient, but whatever you choose, you ultimately want to make this http request:
GET https://graph.facebook.com/oauth/access_token?client_id=YOUR_APP_ID&client_secret=YOUR_APP_SECRET&grant_type=client_credentials HTTP/1.1
Host: graph.facebook.com
Now that you have a method to retrieve the app access_token, you can generate an app request as follows (here I use the Facebook C# SDK):
public string GenerateAppRequest(string fbUserId) {
var appAccessToken = GetAppAccessToken();
var client = new FacebookClient(appAccessToken);
dynamic parameters = new ExpandoObject();
parameters.message = "Test: Action is required";
parameters.data = "Custom Data Here";
string id = client.Post(String.Format("{0}/apprequests", fbUserId), parameters);
return id;
}
Similarly, you can retrieve all of a user's app requests as follows:
Note: you probably don't want to return "dynamic", but I used it here for simplicity.
public dynamic GetAppRequests(string fbUserId) {
var appAccessToken = GetAppAccessToken();
var client = new FacebookClient(appAccessToken);
dynamic result = client.Get(String.Format("{0}/apprequests", fbUserId));
return result;
}
I hope this helps.