65.9K
CodeProject 正在变化。 阅读更多。
Home

使用 Graph API 发布 Facebook 墙帖子

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.85/5 (16投票s)

2013 年 3 月 30 日

CPOL

3分钟阅读

viewsIcon

153581

downloadIcon

9424

引言

我们可以很容易地将 Graph API 与我们的 .net 项目集成,并轻松地在 Facebook 墙上发布我们的状态。不仅可以发布状态,还可以轻松地在 Facebook 墙上分享图片、视频和链接。在这篇文章中,我将详细介绍注册 Facebook 应用程序的步骤,并使用 C#、MVC3 和 Visual Studio 2010 发布到您自己的 Facebook 墙。

背景

Graph API 是检索数据或发布到 Facebook 的主要方式。它使开发人员能够读取和写入 Facebook 数据。现在我将逐步讨论如何注册 Facebook 应用程序,以及如何发布到您自己的 Facebook 墙。

步骤 1:首先,您需要登录到 Facebook 开发者站点,然后从工具栏中选择应用程序,然后选择+创建新应用

步骤 2:输入应用程序名称、应用程序命名空间和应用程序的网络托管。应用程序命名空间和网络托管不是强制性的。

创建您的应用程序后,您将获得应用程序 ID应用程序密钥,这些信息将需要在 Facebook 墙上发布您的状态。 

步骤 3:创建您的应用程序后,您必须输入站点 URL,如果您展开使用 Facebook 登录的网站菜单,您可以看到它。在站点 URL 中,您必须输入应用程序的主页 URL。此外,您还必须输入 Canvas URL安全 Canvas URL,否则您的应用程序将无法正常工作。通常,您可以为 Canvas URL 输入此 URL "http://www.veenx.com/fb/ApplicationFactory/app/73725/",为 安全 Canvas URL 输入 "https://www.veenx.com/fb/ApplicationFactory/app/73725/"。

Facebook 应用程序注册已完成,现在您可以开始构建您的应用程序以在 Facebook 墙上发布状态,为此您必须遵循一些步骤。

首先,您必须创建一个项目并添加 FB.Graph 库作为引用,您可以编写一个类来设置 Facebook 对象,设置权限等等。

代码如下所示

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using ImpactWorks.FBGraph.Connector;
using ImpactWorks.FBGraph.Core;

namespace PostToFacebookWall
{
    public class Authentication
    {
        public Facebook FacebookAuth()
        {
            //Setting up the facebook object
            Facebook facebook = new Facebook(); 
            facebook.AppID = "xxxxxxxxxxxx";
            facebook.Secret = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
            facebook.CallBackURL = "https://:1846/PostStatus/Success/";
            
            //Setting up the permissions
            List permissions = new List() {
                FBPermissions.user_about_me, // to read about me               
                FBPermissions.user_events,
                FBPermissions.user_status,
                FBPermissions.read_stream,
                FBPermissions.friends_events,
                FBPermissions.publish_stream
            };

            //Pass the permissions object to facebook instance
            facebook.Permissions = permissions;
            return facebook;
        }
    }
}

现在您必须在控制器文件夹中添加一个 PostStatusController,并且可以在 PostStatusController 中编写 Index、Success 和 PostStatus 操作方法,当您运行应用程序时,Index 操作方法返回视图页面。当您单击“发布状态”按钮时,会触发 PostStatus 操作方法,该方法创建 authLink URL 并返回 authLink URL。此外,authLink URL 包含一些信息,需要重定向到特定用户的身份验证位置。如果您授予权限,则会自动将您的应用程序重定向到加密值,您必须将该值保存在您的应用程序中才能获取 AccesToken,并且此 AccessToken 需要在您的 Facebook 墙上发布状态。使用“Request.QueryString ["code"];”语法可以获取加密值。当重定向您的应用程序时,会触发 Success 操作方法,因为您在 CallBackURL 中指定了此操作。因此,Success 操作最终会将您的状态发布到您自己的 Facebook 墙上。

下面给出了 PostStatusController 的代码场景。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ImpactWorks.FBGraph.Connector;
using ImpactWorks.FBGraph.Core;
using ImpactWorks.FBGraph.Interfaces;

namespace PostToFacebookWall.Controllers
{
    public class PostStatusController : Controller
    {
        //
        // GET: /PostStatus/

        public ActionResult Index()
        {
            return View();
        }

        Authentication auth = new Authentication();
        public ActionResult Success()
        {
            if (Request.QueryString["code"] != null)
            {
                string Code = Request.QueryString["code"];
                Session["facebookQueryStringValue"] = Code;
            }
            if (Session["facebookQueryStringValue"] != null)
            {
                Facebook facebook = auth.FacebookAuth();
                facebook.GetAccessToken(Session["facebookQueryStringValue"].ToString());
                FBUser currentUser = facebook.GetLoggedInUserInfo();
                IFeedPost FBpost = new FeedPost();
                if (Session["postStatus"].ToString() != "")
                {
                    FBpost.Message = Session["postStatus"].ToString();
                    facebook.PostToWall(currentUser.id.GetValueOrDefault(), FBpost);
                }
            }
            return View();
        }

        public JsonResult PostStatus(string msg)
        {
            Session["postStatus"] = msg;


            Facebook facebook = auth.FacebookAuth();
            if (Session["facebookQueryStringValue"] == null)
            {
                string authLink = facebook.GetAuthorizationLink();
                return Json(authLink);
            }

            if (Session["facebookQueryStringValue"] != null)
            {               
                facebook.GetAccessToken(Session["facebookQueryStringValue"].ToString());
                FBUser currentUser = facebook.GetLoggedInUserInfo();                
                IFeedPost FBpost = new FeedPost();
                if (Session["postStatus"].ToString() != "")
                {
                    FBpost.Message = Session["postStatus"].ToString();
                    facebook.PostToWall(currentUser.id.GetValueOrDefault(), FBpost);
                }
            }
            return Json("No"); 
        }
    }
}

现在您必须添加一个视图页面,您可以在其中放置您的 html。视图页面将如下所示

@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}


@using (Html.BeginForm())
{ 
    
Message
<label style="font-style: italic; color: Gray;"> Write your status</label>
@Html.TextArea("txtPostStatus", new { maxlength = 100, style = "height:100px;width:500px;" })
<input id="btnPost" type="button" value="Post Status" onclick="PostStatus();" />
}

您必须将一些 jQuery 添加到您的视图页面,我已经编写了这些 jQuery 用于调用 PostStatus 方法并显示弹出窗口。代码如下所示

<script type="text/javascript">

    function PostStatus() {
        var msg = $('#txtPostStatus').val();   

        if (msg != '') {
            $.ajax({
                url: '/PostStatus/PostStatus',
                type: 'POST',
                data: { msg: msg },
                success: function (authLink) {
                    if (authLink != 'No') {
                        window.open(authLink, 'title', 'width=660,height=500,status=no,scrollbars=yes,toolbar=0,menubar=no,resizable=yes,top=60,left=320');
                    }
                }
            });
        }
        else {
            alert('please write your message.');
        }
    }  
</script>

编写了一些 jQuery 用于从 PostStatusController 进行 Ajax 调用 PostStatus 方法,并且如果从 PostStatusController 成功返回 authLink,则将 Facebook 登录页面显示为弹出窗口。


对于链接、图像和视频共享,您只需在 Success 操作方法中添加一些代码。代码如下所示

链接分享

FBpost.Action = new FBAction { Name = "test link", Link = "http://blog.impact-works.com/" };
                FBpost.Caption = "Test Image Share";
                 FBpost.Description = "Test Image Desc";
                FBpost.ImageUrl = "http://www.theadway.com/wall.jpg";
                FBpost.Message = "Check out test post";
                FBpost.Name = "Test Post";
                FBpost.Url = "http://blog.impact-works.com";
 
                var postID = facebook.PostToWall(currentUser.id.GetValueOrDefault(), FBpost);

视频分享

FBpost.Url = "http://www.youtube.com/watch?v=hmxgM3sXqDs";
  FBpost.Message = "Sharing a Youtube video";
 
var postId =   facebook.PostToWall(currentUser.id.GetValueOrDefault(), FBpost);

Image Share:

FBpost.Caption = "Image Share";
 
                FBpost.ImageUrl = "http://www.theadway.com/wall.jpg";
 
                FBpost.Name = "Great Image";
                FBpost.Url = "http://www.theadway.com/wall.jpg";
 
              var postId =   facebook.PostToWall(currentUser.id.GetValueOrDefault(), FBpost);

结论

希望您能够将此用于您的应用程序,并且它将使您更容易制作这种类型的应用程序。有关更多信息,我建议您访问 Facebook 文档

© . All rights reserved.