Facebook API receive Wall posts - asp.net

At the moment I am working with the Facebook API and ASP.Net (MVC4).
Is it possible to post a certain message on my Facebook Wall and receive that message in my web application?
I already tried the next code, but it doesn't work:
Maybe somebody has a solution? (Also I don't want the posts of the news feed, but of my profile wall)
JsonObject fbJsonFeedObj = (JsonObject)fbApp.Get(" https://graph.facebook.com/me/home?fields=from,message,name,picture&access_token=" + token);
string str = fbApp.Get("/me/feed").ToString();
JObject obj = JObject.Parse(str);
JToken jUser = obj["data"];
int numb = jUser.Count();
//Get latest post
int id_post = 0;
string stringMsg = obj["data"][id_post]["likes"].ToString();
Update:
I just want a method that gets the latest posts of my personal FB wall. How to accomplish this?
Update 2:
Today I tried:
JsonObject fbJsonFeedObj = (JsonObject)fbApp.Get("
https://graph.facebook.com/" + FacebookModel.TestFacebookID +
"/feed?access_token=" + token);
With this code I can get the latest post, but how do I split it in a readable string? So I only get the UserId who send the post and the real (string) message?
Update 3:
At the moment I am using this code to get the wall posts:
var wall = (JsonObject)fbApp.Get("/me/feed");
But Visual Studio shows this error:
An active access token must be used to query information about the
current user.
I am using the next method to receive the accesstoken:
public static string GetAccessToken()
{
var fb = new FacebookClient();
dynamic result = fb.Get("oauth/access_token", new
{
client_id = FACEBOOK_APP_ID,
client_secret = FACEBOOK_SECRET,
grant_type = "client_credentials"
});
return result.access_token;
}
How to solve this problmen?

The initial problem is that you were using /home and not /feed.
/home - The user's news feed.
/feed - The user's wall.
https://developers.facebook.com/docs/reference/api/user/
You can split it the same way you did with the previous (/home) object
//Get latest post
int id_post = 0;
string stringPostId = obj["data"][id_post]["id"].ToString(); //Id of the post
string stringPostSender = obj["data"][id_post]["from"]["name"].ToString(); //Name of sender
string stringPostSenderId = obj["data"][id_post]["from"]["id"].ToString(); //ID of sender
Each object looks like this so you should be able to figure out how to drill down
{
"id": "5_11111111",
"to": {
"data": [
{
"name": "User A",
"id": "4"
}
]
},
"from": {
"name": "User B",
"id": "5"
},
"message": "This is a test message",
"created_time": "2013-10-04T23:01:42+0000"
}
Your last update is a common mistake many first time developers make.
An application access token should not be used for these calls. You must have a login flow to grant a user access token via OAuth by starting with
https://www.facebook.com/dialog/oauth?
client_id={app-id}
&redirect_uri={redirect-uri}
Please read in detail https://developers.facebook.com/docs/facebook-login/login-flow-for-web-no-jssdk/ for an explanation of the process.

Related

ASP.NET Web API IIS hosting REST Methods produces NULL in RethinkDB

I'm making a Web API for handle my Android app's HTTP requests and rethinkDB connection. But something wrong in IIS i think. It produces null values for my User identity when i send POST request to the API. My db is running on localhost.
My POST method is (there is no DB syntax errors.) =
public IHttpActionResult PostNewUserModel(StudentViewModel studentViewModel)
{
if (!ModelState.IsValid)
return BadRequest("Invalid data.");
var conn = connection();
var newStudentViewModel = new StudentViewModel
{
Id = studentViewModel.Id,
FirstName = studentViewModel.FirstName,
LastName = studentViewModel.LastName
};
R.Db(MYDBNAME).Table(MYTABLENAME).Insert(newStudentViewModel).Run(conn);
return Ok();
}
I POST'ed this entity =
{
"Id": 6,
"FirstName": "Nihat Can Doğamaz",
"LastName": "CANITIN"
}
But i see this entity in RethinkDB table like this =
{
"FirstName": null ,
"Id": 0 ,
"LastName": null
}
How to solve it ?
I solve the error. DB cannot recognize returned JSON format. It must be identified in POSTMAN. You must select JSON(application/json) Body format to write your JSON objects into your db.

Google Yolo doesn't return an access_token nor gender info

I'm implementing the one-tap signIn for my site.
With the normal Google SignIn, i can do this:
window.gapi.auth2.getAuthInstance().signIn()
.then((googleUser) => sendAccessTokenToServer(googleUser.getAuthResponse().access_token))
Thanks to access_token, on the server side I can do something like this and get profile informations like gender:
GoogleCredential.Builder()
.setTransport(httpTransport).setJsonFactory(jsonFactory)
.setClientSecrets(clientId, secret).setRequestInitializer((request -> {
HttpHeaders headers = request.getHeaders();
headers.setAuthorization("Bearer " + accessToken);
})).build();
But when using the googleyolo, with hint() or retrieve() i cannot get the access_token, but just the idToken:
googleyolo
.hint({
supportedAuthMethods: [googleUrl, 'googleyolo://id-and-password', scope],
supportedIdTokenProviders: [
{
uri: googleUrl,
clientId
}]
}).then(
(credential) => {
if (credential.idToken) {
sendidTokenToServer(credential.idToken);
}
}
But the problem is, when i do on server-side:
GoogleIdToken idToken = null;
try {
idToken = verifier.verify(accessToken);
} catch (Exception e) {
e.printStackTrace();
}
if (idToken != null) {
GoogleIdToken.Payload payload = idToken.getPayload();
// Print user identifier
String userId = payload.getSubject();
System.out.println("User ID: " + userId);
// Get profile information from payload
String email = payload.getEmail();
boolean emailVerified = Boolean.valueOf(payload.getEmailVerified());
String name = (String) payload.get("name");
String pictureUrl = (String) payload.get("picture");
String locale = (String) payload.get("locale");
String familyName = (String) payload.get("family_name");
String givenName = (String) payload.get("given_name");
I don't get informations like the gender.
Is it possible to get an access_token from googleyolo or getting the gender inside the idToken?
I'm the product manager at Google for this library. Accessing gender is not currently supported via the one-tap library. My suggestion would be show your own UI to collect gender info (could just be one more tap on M / F / other / skip, etc.), as you would have to anyway if this data were not available or user signed up manually. Not all Google users have gender info set or accessible via API anyway.

Can my ASP.Net Code get confirmation from sendgrid that an email has been sent?

I have this code that I am using in my application:
private async Task configSendGridasync(IdentityMessage message)
{
var myMessage = new SendGridMessage();
myMessage.AddTo(message.Destination);
myMessage.From = new System.Net.Mail.MailAddress(
"a#b.com", "AB Registration");
myMessage.Subject = message.Subject;
myMessage.Text = message.Body;
myMessage.Html = message.Body;
var credentials = new NetworkCredential(
ConfigurationManager.AppSettings["mailAccount"],
ConfigurationManager.AppSettings["mailPassword"]
);
// Create a Web transport for sending email.
var transportWeb = new Web(credentials);
// Send the email.
if (transportWeb != null)
{
await transportWeb.DeliverAsync(myMessage);
}
else
{
Trace.TraceError("Failed to create Web transport.");
await Task.FromResult(0);
}
}
It's called here:
public async Task<IHttpActionResult> Register(RegisterBindingModel model)
{
var user = new ApplicationUser()
{
Email = model.Email,
FirstName = model.FirstName,
LastName = model.LastName,
RoleId = (int)ERole.Student,
UserName = model.UserName
};
var result = await UserManager.CreateAsync(user, model.Password);
if (result.Succeeded)
{
var code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
var callbackUrl = model.Server +
"/index.html" +
"?load=confirmEmail" +
"&userId=" + user.Id +
"&code=" + HttpUtility.UrlEncode(code);
await UserManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking this link: link");
}
if (!result.Succeeded)
{
return GetErrorResult(result);
}
return Ok();
}
Is there any way I can get confirmation from sendgrid that the message has been sent or any other information?
Emails sent via the SendGrid web API are asynchronous, so to get a confirmation, you need to implement a webhook. The Event Webhook will post events of your choice to a URL that you define. In this case you are interested in the "delivered" event.
You'll need some code on your server to handle the incoming webhook and do any logic based on the results, such as logging delivered events. There are a few community-contributed libraries out there that let you easily create a webhook handler. I suggest sendgrid-webhooks, which is available on nuget.
Then take the incoming POST and hand it to the parser to get an object back.
Since you are using ASP.NET MVC, then you can use an [HttpPost] method inside of a controller to receive the POST data from SendGrid. Then you can parse it using sendgrid-webhooks.
From the sendgrid-webhooks readme:
var parser = new WebhookParser();
var events = parser.ParseEvents(json);
var webhookEvent = events[0];
//shared base properties
webhookEvent.EventType; //Enum - type of the event as enum
webhookEvent.Categories; //IList<string> - list of categories assigned ot the event
webhookEvent.TimeStamp; //DateTime - datetime of the event converted from unix time
webhookEvent.UniqueParameters; //IDictionary<string, string> - map of key-value unique parameters
//event specific properties
var clickEvent = webhookEvent as ClickEvent; //cast to the parent based on EventType
clickEvent.Url; //string - url on what the user has clicked
I work at SendGrid so please let me know if there's anything I can help with.
You will want to use Event Webhooks to get confirmation sent back to you to confirm the message has been delivered to the recipient.
You would need to setup a page to accept events from Sendgrid, such as:
https://yourdomain.com/email/hook which would accept JSON which you would then deal with however you want. The Json.NET documentation would be able to guide you with how to accept JSON and then turn it into an object you can use.
Example JSON you'd be POSTed:
{
"sg_message_id":"sendgrid_internal_message_id",
"email": "john.doe#sendgrid.com",
"timestamp": 1337197600,
"smtp-id": "<4FB4041F.6080505#sendgrid.com>",
"event": "delivered"
},
The events you can receive from SendGrid are: Processed, Dropped, Delivered, Deferred, Bounce, Open, Click, Spam Report, Unsubscribe, Group Unsubscribe, Group Resubscribe.
With all these options you could have a webhook to deal with Bounces such as get someone to find out the correct e-mail address for the user you tried to email.
I dont think SendGrid is set up to give a response. However, as a hack, you could BCC yourself (and therefore know at least email has gone out) by adding the following code to your configSendGridasync class
.
.
.
//this is your old code...
myMessage.Text=message.Body;
myMessage.Html = message.Body;
//Add this...
myMessage.AddBcc("yourEmail#domain.com");
Hope this helps!

how to skip facebook app permissions dialog

Here, I am trying to authenticate user via login and after that I want to skip permissions dialog. But I am unable to achieve this, as it always asking for permissions for app to the user. My intention is if user is not logged into the facebook he/she should be prompted for facebook login and then I will fetch public information by using method Get("/me"). Let me know what I am doing wrong here.
public string GetFBAccessToken(string strAppID, string strAppSecret, string strUrl)
{
// Declaring facebook client type
var vFB = new FacebookClient();
string strAccessTok = string.Empty;
try
{
if (!string.IsNullOrEmpty(strAppID) && !string.IsNullOrEmpty(strAppSecret) && !string.IsNullOrEmpty(strUrl))
{
// Getting login url for facebook
var loginUrl = vFB.GetLoginUrl(new
{
client_id = strAppID,
client_secret = strAppSecret,
redirect_uri = strUrl,
response_type = "code",
state = "returnUrl",
//scope = "",
display = "popup"
});
// Redirecting the page to login url
if (HttpContext.Current.Request.QueryString["code"] == null)
{
HttpContext.Current.Response.Redirect(loginUrl.AbsoluteUri);
}
// Fetching the access token from query string
if (HttpContext.Current.Request.QueryString["code"] != null)
{
dynamic result = vFB.Post("oauth/access_token", new
{
client_id = strAppID,
client_secret = strAppSecret,
redirect_uri = strUrl,
code = HttpContext.Current.Request.QueryString["code"]
});
// Getting access token and storing in a variable
strAccessTok = result.access_token;
}
}
return strAccessTok;
}
catch (Exception ex)
{
//if (HttpContext.Current.Request.QueryString["response_type"] == "code")
//{
// var fb = new FacebookClient();
// var details = fb.Get("/me");
//}
return strAccessTok;
}
}
Regardless to the platform/ language you are using; solution can be as follows.
check use's logged in status. https://developers.facebook.com/docs/reference/javascript/FB.getLoginStatus/
based on Response status, forcefully call your action (i.e. Log in, Get Permission or any additional action if user is already connected). For Log in check this reference document from FB. https://developers.facebook.com/docs/facebook-login/login-flow-for-web/
No. You cannot skip the Login Dialog.
In fact, it is really important for an APP owner to build a trust relationship with your users. I would recommend you to follow the Login Best Practices while authenticating the users using your APP.

Facebook authentication response parameters are wrong -> infinite request loop

I an new to the facebook API and after some work I encountered a problem.
First, I am using the facebook SDK for communication with the facebook APIs.
In my app settings I chose that the response of the OAuth dialog should be query string instead of URI fragment.
On my server I got the following code:
void Page_Load()
{
string url = Request.Url.AbsoluteUri;
Facebook.FacebookOAuthResult result = null;
if (!Facebook.FacebookOAuthResult.TryParse(url, out result))
{
string redirectUrl = PivotServer.Helpers.GetFacebookOAuthUrl();
Response.Redirect(redirectUrl);
}
}
And thats my helper method:
public static string GetFacebookOAuthUrl()
{
FacebookOAuthClient oauth = new FacebookOAuthClient
{
AppId = "149637255147166",
AppSecret = "xxx",
RedirectUri = new Uri("http://mydomain.com/")
};
var param = new Dictionary<string, object>
{
{ "response_type", "token" },
{ "display", "popup" }
};
Uri url = oauth.GetLoginUrl(param);
return url.AbsoluteUri;
}
I ran my page on a web server (IIS). When I open the page the first time I am asked to log in to facebook, which is alright, but then I ran into an infinity loop, because the Auth Token Parameter (from facebook) is an URI fragment instead if a query string (which I wanted (see picture above)).
The response URI looks like
http://mydomain.com/#access_token=AAACIGCNwLp4BAMccSoliF5EMGJm0NPldv5GpmBPIm9z7rRuSkiia7BM0uhEn1V88c8uOlWOfGc3C8sFC9tq90Ma0OwIm0tWLNU5BBAZDZD&expires_in=0&base_domain=mydomain.com
instead of
http://mydomain.com/?code=AAACIGCNwLp4BAMccSoliF5EMGJm0NPldv5GpmBPIm9z7rRuSkiia7BM0uhEn1V88c8uOlWOfGc3C8sFC9tq90Ma0OwIm0tWLNU5BBAZDZD&expires_in=0&base_domain=mydomain.com
Is that a bug from the OAuth API, or what am I doing very wrong here?
It's an issue with IE. Be sure to have a p3p header in each response from your server.
It has been too easy:
var param = new Dictionary<string, object>
{
{ "response_type", "code" }, // <--- "code" instead of "token"
{ "display", "popup" }
};

Resources