我正在尝试使用c#MVC在Facebook中获取页面数据。即使我提供了manage_pages权限(Scope),但在运行我的代码时它也不会显示任何页面。这是页面列表显示0
的位置string Accounts = "/me/accounts";
JSONObject pageData = api.Get(Accounts);
var data = pageData.Dictionary["data"];
List<JSONObject> pageList = data.Array.ToList<JSONObject>();
ViewBag.pageList = pageList;
以下是我尝试的代码
public ActionResult returnfromfb()
{
string app_id = "AppID";
string app_secret = "AppSecret";
string scope = "manage_pages,publish_stream,status_update,user_about_me,user_hometown,user_location,email,offline_access";
string code = Request.QueryString["code"];
if (code == null)
{
Response.Redirect(string.Format("https://graph.facebook.com/oauth/authorize?client_id={0}&redirect_uri={1}&scope={2}",
app_id, Request.Url.AbsoluteUri, scope));
}
string AccessToken = "";
try
{
if (code != null)
{
string str = string.Format("https://graph.facebook.com/oauth/access_token?client_id={0}&redirect_uri={1}&scope={2}&code={3}&client_secret={4}",
app_id, Request.Url.AbsoluteUri, scope, Request["code"].ToString(), app_secret);
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(str);
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
byte[] Param = Request.BinaryRead(System.Web.HttpContext.Current.Request.ContentLength);
string strRequest = System.Text.Encoding.ASCII.GetString(Param);
req.ContentLength = strRequest.Length;
StreamWriter streamOut = new StreamWriter(req.GetRequestStream(), System.Text.Encoding.ASCII);
streamOut.Write(strRequest);
streamOut.Close();
StreamReader streamIn = new StreamReader(req.GetResponse().GetResponseStream());
string strResponse = streamIn.ReadToEnd();
if (strResponse.Contains("&expires"))
strResponse = strResponse.Substring(0, strResponse.IndexOf("&expires"));
AccessToken = strResponse.Replace("access_token=", "");
streamIn.Close();
}
Facebook.FacebookAPI api = new Facebook.FacebookAPI(AccessToken);
string requestEmail = "/me";
JSONObject fbemail = api.Get(requestEmail);
try
{
ViewBag.Email = fbemail.Dictionary["email"].String;
}
catch (Exception ex)
{
//errorLog.setError(ex, "LoginController.SaveFacebookData");
}
string Accounts = "/me/accounts";
JSONObject pageData = api.Get(Accounts);
var data = pageData.Dictionary["data"];
List<JSONObject> pageList = data.Array.ToList<JSONObject>();
ViewBag.pageList = pageList;
foreach (var page in pageList)
{
try
{
var id = page.Dictionary["id"].String;
string request = id;
JSONObject fbobject = api.Get(request);
try
{
ViewBag.BusinessName = fbobject.Dictionary["name"].String;
ViewBag.Address = fbobject.Dictionary["location"].ToDisplayableString();
ViewBag.PhoneNumber = fbobject.Dictionary["phone"].String;
}
catch (Exception ex)
{
//errorLog.setError(ex, "LoginController.SaveFacebookData");
}
}
catch (Exception ex)
{
//errorLog.setError(ex, "LoginController.SaveFacebookData");
}
}
答案 0 :(得分:0)
I have Finally managed to get the desired result using #Remodal.js
<head>
<link rel="stylesheet" href="@Url.Content("~/Content/jquery.remodal.css")">
</head>
<body>
<script type="text/javascript" src="@Url.Content("~/Scripts/Home/jquery.remodal.js")"></script>
<div class="remodal" id="page-selector-remodal" data-remodal-id="pageselector">
<p>Please select a facebook page Share </p>
<div id="page-name-container">
<select id="page-name" class="form-control">
</select>
</div>
<a class="remodal-confirm" id="facebookPageSelectSubmit" href="#">OK</a>
<a class="remodal-cancel" id="remodal-cancel" href="#">CANCEL</a>
</div>
<div data-remodal-id="modal-status">
<p id="modal-status-content">
The Account you have selected does not have Email.
</p>
<br>
<a class="remodal-confirm" href="#">OK</a>
</div>
<script type="text/javascript>
(function (d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) return;
js = d.createElement(s);
js.id = id;
js.src = "//connect.facebook.net/en_US/sdk.js";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
window.fbAsyncInit = function () {
FB.init({
appId: 'YOUR APP ID',
cookie: true, // enable cookies to allow the server to access
// the session
xfbml: true, // parse social plugins on this page
version: 'v2.2' // use version 2.1
});
};
var pageSelector = $('[data-remodal-id=pageselector]').remodal();
var modalstatus = $('[data-remodal-id=modal-status]').remodal();
function statusChangeCallback(response) {
if (response.status === 'connected') {
// Logged into your app and Facebook.
//testAPI();
} else if (response.status === 'not_authorized') {
// The person is logged into Facebook, but not your app.
$("#modal-status-content").empty().html(response.status);
modalstatus.open();
}
else {
$("#modal-status-content").empty().html(response.status);
modalstatus.open();
// The person is not logged into Facebook, so we're not sure if
// they are logged into this app or not.
document.getElementById('status').innerHTML = 'Please log ' +
'into Facebook.';
}
}
function FacebookHandler() {
FB.login(function (result) {
if (result != null && result.authResponse != null && result.authResponse != undefined) {
facebookPageData = result;
FB.api('/me/accounts', function (accountsResult) {
if (accountsResult != null && accountsResult.data.length != 0) {
//open the remodal here
pageSelector.open();
facebookAccountsData = accountsResult;
var data = accountsResult['data'];
if (data != null) {
for (var i = 0; i < data.length; i++) {
$("#page-name").append('<option value="' + data[i].id + '">' + data[i].name + '</option>');
}
}
unblockUI('body');
$("#flip-container, #feature-container, #branding-container, #intro-arrow-container, #share-container, #copyright-text-container").hide();
$("body").css("padding-right", "0");
}
else {
$("#modal-status-content").empty().html("The Account you have selected does not have any facebook page,<br />Post to Wall.");
modalstatus.open();
pageSelector.open();
unblockUI('body');
}
});
}
else {
$("#modal-status-content").empty().html("Unable to retrieve your details from facebook, try again after sometime.");
modalstatus.open();
unblockUI('body');
}
}, { scope: 'manage_pages, publish_stream' });
}
$("#facebookPageSelectSubmit").on("click", function () {
var facebookpageId = $("#page-name option:selected").val();
if (facebookpageId != null) {
FB.api('/' + facebookpageId, function (identity) {
if (identity != null) {
FB.api('/' + facebookpageId, { fields: 'access_token' }, function (resp) {
if (resp.access_token != null) {
//Get the "resp"(Data) here
}
else {
}
});
}
else {
}
});
}
else {
}
});
</script>
//Finally call the "FacebookHandler()" function on click
</body>