如何从 .NET 发布到 Facebook 页面墙

发布于 2024-12-02 21:15:52 字数 401 浏览 3 评论 0原文

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

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

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

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

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

(OAuthException) (#200) 用户尚未授权应用程序执行此操作

I've created Facebook page.
I have no application secret and no access token.

I want to post to this page from my .NET desktop application.
How can I do it? Can anyone help please, where can I get access token for this?

Should I create a new Facebook Application? If yes, how can I grant permissions to this application to post on page's wall?

UPD1:
I have no website.
I need to post company's news from .NET desktop application to company's Facebook page.
All I have is Login/Password for Facebook Page Account.

UPD2:
I've created Facebook Application. With AppID/SecretKey. I can get access token. But...
How can I grant permissions to post to page's wall?

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

听风吹 2024-12-09 21:15:52

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

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

您会注意到,在我的示例中,我要求两者“发布流”和“管理页面”。这样您还可以在该用户是管理员的页面上发帖。这是完整的代码:

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" });
            }
        }
    }
}

I have created a video tutorial showing how to do this at this location:

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

You will notice that, in my example, I am asking for both "publish_stream" and "manage_pages". This let's you also post on pages of which that users is an admin. Here is the full code:

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" });
            }
        }
    }
}
木緿 2024-12-09 21:15:52

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

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

You need to ask the user for the publish_stream permission. In order to do this you need to add publish_stream to the scope in the oAuth request you send to Facebook. The easiest way to do all of this is to use the facebooksdk for .net which you can grab from codeplex. There are some examples there of how to do this with a desktop app.

Once you ask for that permission and the user grants it you will receive an access token which you can use to post to your page's wall. If you need to store this permission you can store the access token although you might need to ask for offline_access permission in your scope in order to have an access token that doesn't expire.

木格 2024-12-09 21:15:52

您可以使用
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 // [email protected]
    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 
            }

        }
}

You can use
https://www.nuget.org/packages/Microsoft.Owin.Security.Facebook/ to obtain users login and permission and
https://www.nuget.org/packages/Facebook.Client/
to post to feeds.

Below example is for 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;
        }
    }

On the callback you get user access token:

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 // [email protected]
    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;
    // ...                   
}

Which then you can use to post to user's feed or page

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 
            }

        }
}
调妓 2024-12-09 21:15:52

您需要授予“publish_stream”权限。

You need to grant the permission "publish_stream".

罪#恶を代价 2024-12-09 21:15:52

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

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

Possibly the easiest way to do this is via Facebook PowerShell Module, http://facebookpsmodule.codeplex.com. This allows the same sort of operations as FacebookSDK, but via an IT-Admin scripting interface rather than a developer-oriented interface.

AFAIK there is still a limitation of Facebook Graph API that you will not be able to post references to other pages (e.g. @Microsoft) using the Facebook Graph API. This will apply to FacebookSDK, FacebookPSModule, and anything else built over Facebook Graph API.

追我者格杀勿论 2024-12-09 21:15:52

You will get information on how to create a facebook app or link your website to facebook on https://developers.facebook.com/?ref=pf.

You will be able to download facebook sdk at http://facebooksdk.codeplex.com/. There are some good example given in the document section of the site.

画骨成沙 2024-12-09 21:15:52
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)
{

}
}
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)
{

}
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文