【问题标题】:how to post to facebook page wall from .NET如何从 .NET 发布到 Facebook 页面墙
【发布时间】:2011-11-10 13:53:18
【问题描述】:

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

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

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

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

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

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

【问题讨论】:

  • 您尝试过 Facebook SDK 吗?

标签: c# facebook facebook-graph-api facebook-c#-sdk access-token


【解决方案1】:

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

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

【讨论】:

  • 好的,我已经创建了新的 Facebook 应用程序。如何授予此应用的权限?
  • 嘿,看看developers.facebook.com/docs/reference/rest/comments.add Facebook 有 REST API 来添加 cmets。我希望这对你的场景有用
  • 抱歉,有什么意见?我不需要它。我想从桌面应用发布消息(带有图片和描述)到页面的墙上。
  • 使用 sdk 是一个很好的起点,但一个好的链接或一些代码示例肯定会有所帮助。
【解决方案2】:

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

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

【讨论】:

    【解决方案3】:

    您需要授予“publish_stream”权限。

    【讨论】:

    • 如何设置“publish_stream”权限?
    【解决方案4】:

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

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

    【讨论】:

      【解决方案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" });
                  }
              }
          }
      }
      

      【讨论】:

      • 您真的在上面的示例中编写了正确的 App_secret 吗?此信息应为最高机密
      • 如何根据用户选择发布数据?就像在这个例子中,你在消息变量中发布了一个静态字符串,如果你在 CheckAuthorization() 方法中使用该字符串,在第一次重定向代码后如何访问该字符串?
      【解决方案6】:
      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)
      {
      
      }
      }
      

      【讨论】:

        【解决方案7】:

        你可以使用 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 
                    }
        
                }
        }
        

        【讨论】:

          猜你喜欢
          • 2011-08-11
          • 2011-07-14
          • 2012-11-29
          • 1970-01-01
          • 1970-01-01
          • 2010-11-25
          • 1970-01-01
          • 1970-01-01
          • 2012-06-13
          相关资源
          最近更新 更多