This is a follow up to the topic: Passing the signed_request along with the AJAX call to an ActionMethod decorated with CanvasAuthorize
Since I couldn't get the signed_request to be anything other than null, I thought I'd authenticate the user on the client side, then send the access token to the server side (ASP.NET MVC) along with the AJAX call. Unfortunately, I cannot get that to work either! Here's my Javascript code (which I've got from the documentation):
function postOnFacebook(msg, itemLink, pic, itemTitle, signedReq) {
var siteUrl = 'http://www.localhost:2732';
var appID = 193005690721590;
if (window.location.hash.length == 0) {
var path = 'https://www.facebook.com/dialog/oauth?';
var queryParams = ['client_id=' + appID,
'redirect_uri=' + window.location,
'response_type=token',
'scope=offline_access'];
var query = queryParams.join('&');
var url = path + query;
window.open(url);
} else {
var accessToken = window.location.hash.substring(1);
var path = "https://graph.facebook.com/me?";
var queryParams = [accessToken];
var query = queryParams.join('&');
var url = path + query;
// use jsonp to call the graph
var script = document.createElement('script');
script.src = url;
document.body.appendChild(script);
}
$.ajax({
url: '/Facebook/Share',
data: {
'message': msg,
'link': siteUrl + itemLink,
'picture': siteUrl + pic,
'name' : itemTitle,
'accessToken': accessToken
},
type: 'get',
success: function(data) {
if(data.result == "success") {
alert("item was posted on facebook");
}
}
});
}
And this is my server-side code:
public ActionResult Share(string message, string link, string picture, string name, string accessToken)
{
if (FacebookWebContext.Current.Session == null)
return RedirectToAction("Login");
var fb = new FacebookWebClient(accessToken);
var postArgs = new Dictionary<string, string>();
postArgs["message"] = message;
postArgs["link"] = link;
postArgs["picture"] = picture;
postArgs["name"] = name;
fb.Post("/me/feed", postArgs);
return Json(new {result = "success"}, JsonRequestBehavior.AllowGet);
}
}
UPDATE:
I tried this but it did not work for me. When I click on the button for the first time, it redirects me to the FB login page and then returns me back to my website's home page. After that, all it does is redirect and then back to the home page right away. Nothing gets posted.
Any suggestions?