7

我已经创建了 Facebook 页面。我没有应用程序机密,也没有访问令牌。

我想从我的 .NET 桌面应用程序发布到此页面。我该怎么做?谁能帮忙,我在哪里可以获得访问令牌?

我应该创建一个新的 Facebook 应用程序吗?如果是,我如何授予此应用程序在页面墙上发布的权限?

UPD1:我没有网站。我需要将公司的新闻从 .NET 桌面应用程序发布到公司的 Facebook 页面。我所拥有的只是 Facebook 页面帐户的登录名/密码。

UPD2:我创建了 Facebook 应用程序。使用 AppID/SecretKey。我可以获得访问令牌。但是...如何授予发布到页面墙的权限?

(OAuthException) (#200) The user hasn't authorized the application to perform this action

4

7 回答 7

5

我创建了一个视频教程,展示了如何在此位置执行此操作:

http://www.markhagan.me/Samples/Grant-Access-And-Post-As-Facebook-User-ASPNet

您会注意到,在我的示例中,我同时要求“publish_stream”和“manage_pages”。这让您还可以在该用户是管理员的页面上发布。这是完整的代码:

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using Facebook;

namespace FBO
{
    public partial class facebooksync : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            CheckAuthorization();
        }

        private void CheckAuthorization()
        {
            string app_id = "374961455917802";
            string app_secret = "9153b340ee604f7917fd57c7ab08b3fa";
            string scope = "publish_stream,manage_pages";

            if (Request["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));
            }
            else
            {
                Dictionary<string, string> tokens = new Dictionary<string, string>();

                string url = 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 request = WebRequest.Create(url) as HttpWebRequest;

                using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
                {
                    StreamReader reader = new StreamReader(response.GetResponseStream());

                    string vals = reader.ReadToEnd();

                    foreach (string token in vals.Split('&'))
                    {
                        //meh.aspx?token1=steve&token2=jake&...
                        tokens.Add(token.Substring(0, token.IndexOf("=")),
                            token.Substring(token.IndexOf("=") + 1, token.Length - token.IndexOf("=") - 1));
                    }
                }

                string access_token = tokens["access_token"];

                var client = new FacebookClient(access_token);

                client.Post("/me/feed", new { message = "markhagan.me video tutorial" });
            }
        }
    }
}
于 2012-10-15T12:20:33.503 回答
3

您需要向用户询问 publish_stream 权限。为此,您需要将 publish_stream 添加到您发送到 Facebook 的 oAuth 请求的范围内。完成所有这一切的最简单方法是使用 facebooksdk for .net,您可以从 codeplex 获取它。有一些示例说明如何使用桌面应用程序执行此操作。

一旦您请求该权限并且用户授予它,您将收到一个访问令牌,您可以使用该令牌将其发布到您页面的墙上。如果您需要存储此权限,则可以存储访问令牌,尽管您可能需要在您的范围内请求 offline_access 权限才能获得不会过期的访问令牌。

于 2011-12-04T19:25:33.430 回答
2

您可以使用 https://www.nuget.org/packages/Microsoft.Owin.Security.Facebook/获取用户登录和权限,并 使用https://www.nuget.org/packages/Facebook.Client/ 发布到提要.

以下示例适用于 ASP.NET MVC 5:

public void ConfigureAuth(IAppBuilder app)
        {
            app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

            // Facebook 
            var facebookOptions = new FacebookAuthenticationOptions
            {
                AppId = "{get_it_from_dev_console}",
                AppSecret = "{get_it_from_dev_console}",
                BackchannelHttpHandler = new FacebookBackChannelHandler(),
                UserInformationEndpoint = "https://graph.facebook.com/v2.4/me?fields=id,name,email,first_name,last_name,location",
                Provider = new FacebookAuthenticationProvider
                {
                    OnAuthenticated = context =>
                    {
                        context.Identity.AddClaim(new Claim("FacebookAccessToken", context.AccessToken)); // user acces token needed for posting on the wall 
                        return Task.FromResult(true);
                    }
                }
            };
            facebookOptions.Scope.Add("email");
            facebookOptions.Scope.Add("publish_actions"); // permission needed for posting on the wall 
            facebookOptions.Scope.Add("publish_pages"); // permission needed for posting on the page
            app.UseFacebookAuthentication(facebookOptions);

            AntiForgeryConfig.UniqueClaimTypeIdentifier = ClaimTypes.NameIdentifier;
        }
    }

在回调中,您将获得用户访问令牌:

public ActionResult callback()
{
    // Here we skip all the error handling and null checking
    var auth = HttpContext.GetOwinContext().Authentication;
    var loginInfo = auth.GetExternalLoginInfo();
    var identityInfo = auth.GetExternalIdentity(DefaultAuthenticationTypes.ExternalCookie);

    var email = loginInfo.Email // klaatuveratanecto@gmail.com
    var name = loginInfo.ExternalIdentity.Name  // Klaatu Verata Necto
    var provider = loginInfo.Login.LoginProvider // Facebook | Google
     
    var fb_access_token = loginInfo.identityInfo.FindFirstValue("FacebookAccessToken");
    // Save this token to database, for the purpose of this example we will save it to Session.
    Session['fb_access_token'] = fb_access_token;
    // ...                   
}

然后您可以使用它发布到用户的提要或页面

public class postcontroller : basecontroller
{                      
        public ActionResult wall()
        {
            var client = new FacebookClient( Session['fb_access_token'] as string);
            var args = new Dictionary<string, object>();
            args["message"] = "Klaatu Verata N......(caugh, caugh)";
            
            try
            {
                client.Post("/me/feed", args); // post to users wall (feed)
                client.Post("/{page-id}/feed", args); // post to page feed
            }
            catch (Exception ex)
            {
                // Log if anything goes wrong 
            }

        }
}
于 2016-12-08T14:43:32.423 回答
1

您需要授予“publish_stream”权限。

于 2011-09-09T09:49:41.307 回答
0

可能最简单的方法是通过 Facebook PowerShell 模块, http: //facebookpsmodule.codeplex.com。这允许与 FacebookSDK 相同类型的操作,但通过 IT-Admin 脚本接口而不是面向开发人员的接口。

AFAIK 仍然存在 Facebook Graph API 的限制,您将无法使用 Facebook Graph API 发布对其他页面(例如@Microsoft)的引用。这将适用于 FacebookSDK、FacebookPSModule 以及基于 Facebook Graph API 构建的任何其他内容。

于 2011-09-06T16:06:43.227 回答
0

您将在https://developers.facebook.com/?ref=pf上获得有关如何创建 facebook 应用程序或将您的网站链接到 facebook 的信息。

您将能够在http://facebooksdk.codeplex.com/下载 facebook sdk 。该站点的文档部分给出了一些很好的示例。

于 2011-09-05T11:51:27.423 回答
0
public void PostImageOnPage()
{
string filename=string.Empty;
if(ModelState.IsValid)
{
//-------- save image in image/
if (System.Web.HttpContext.Current.Request.Files.Count > 0)
{
var file = System.Web.HttpContext.Current.Request.Files[0];
// fetching image                    
filename = Path.GetFileName(file.FileName);
filename = DateTime.Now.ToString("yyyyMMdd") + "_" + filename;
file.SaveAs(Server.MapPath("~/images/Advertisement/") + filename);
}
}
string Picture_Path = Server.MapPath("~/Images/" + "image3.jpg");
string message = "my message";
try
{
string PageAccessToken = "EAACEdEose0cBAAoWM3X";

// ————————create the FacebookClient object
FacebookClient facebookClient = new FacebookClient(PageAccessToken);

// ————————set the parameters
dynamic parameters = new ExpandoObject();
parameters.message = message;
parameters.Subject = "";
parameters.source = new FacebookMediaObject
{
ContentType = "image/jpeg",
FileName = Path.GetFileName(Picture_Path)
}.SetValue(System.IO.File.ReadAllBytes(Picture_Path));
// facebookClient.Post("/" + PageID + "/photos", parameters);// working for notification on user page
facebookClient.Post("me/photos", parameters);// woring using bingoapp access token not page in(image album) Post the image/picture to User wall   
}
catch (Exception ex)
{

}
}
于 2016-09-28T13:14:16.480 回答