Jason's blog
We have so many needs in our life, but at the end of the day, all we need is...to be needed.

         近期参与了一些开发facebook相关应用的项目,由于国内访问困难,相关资料查找及测试都比较困难,起初只做一些简单的调用,比如要从手机上打开facebook的发送消息的页面,并把对应的参数传递过去。这个本应该是个很简单的工作,但由于我们对其并不熟悉,相关资料都查过好多。本想咨询做过facebook相关项目开发的iphone团队,可对方使用的是ios上的一个sdk,至于要打开哪个页面,就不知道了。当然,后来这些问题都解决了,我上一篇文章中有对具体方法的描述,但感觉就像一个外行在做开发,我觉得个人站长都应该对此很明白(这些内容甚至不需要使用facebook的api)。

        现在另一个项目是开发facebook上面的web app,开发web app需要注册成为facebook开发者,这个很简单,进入

              https://developers.facebook.com/

         网站自己注册就可以了,如果不是开发者,会提示要注册激活,美国人可以直接绑定手机号码激活,我们只好使用双币信用卡激活了,反正标着visa和万事达卡的信用卡都可以激活(我用了一个即将到期的万事达卡,现在还不知道到期后会不会让重新激活),激活并不会收费,放心激活就行了。

 

入门级javascript sdk:

          注册过程不详细写了,很简单,需要注意的是:

                      1、website项目中的站点url和domain两个项目是不需要http://开头的;而app on facebook的canvas URL,是需要写http的。而且这一段是实际上从facebook打开这个app时,嵌入的iframe的地址。

                      2、如果本机测试,可以直接使用localhost作为地址,真正上线的时候记得改回来就行。也可以用改host文件的方法随便指定一个域名,加端口访问也没问题,就是不能用ip地址,提交通不过。

          注册好了,就开始开发吧,我们首先不使用C#的sdk,直接使用facebook提供的javascript api:

                      1、创建一个静态页面,引入脚本

                             http://connect.facebook.net/en_US/all.js

                             除此之外,还要引用jquery,写脚本方便嘛;

                      2、另外需要在页面上方这么一个div:

                             <div id="fb-root">

                             如果不放,就会脚本报错。放哪儿都行,也不显示。但是要放在fb初始话的脚本前面。

                     3、写段脚本吧,这里我们有个登录按钮:

            FB.init({ appId: '{这里是appid}', status: true, cookie: true, xfbml: true });
            $("#FBLogin").click(function () {
                FB.login(function (response) {
                    if (response.session) {
                        // 登录成功
                        window.location = 'about.aspx'
                    } else {
                        //
                    }
                }, { perms: "publish_stream" });
            });

这里首先初始化了fb对象,需要appid,它在创建时自动生成。第二个呢注册了一个登录按钮的点击事件,点击后直接调用FB封装好的login方法,第一个参数是回调函数,第二个参数是一个json对象,这里注明了该app的访问权限是publish_stream,差不多是最小权限了吧。

       

            所有权限的资料和其他api的资料可以直接访问以下地址查找:

          https://developers.facebook.com/docs/

          刚入个门,其实后面的对照文档中的,就都可以了,比如fql:

FB.api({
    method: 'fql.query',
    query: 'SELECT name, pic FROM profile WHERE id=' + uid
}, function(response){
    fb_User.name = response[0].name;
    fb_User.pic = response[0].pic;
    …

});
这是访问用户配置表,返回用户名称和头像。

         graph api相比更加简单,先看例子

FB.api({path}, 'GET', {}, function(response){
        if (!response || response.error) {
            alert('Error occured');
        }
        else {
            …
        }
    })

          path就是对应访问内容的路径,比如访问个人资料,就填me,访问某视频的信息,可以直接填视频的id。很简单吧,回调函数中都是返回的json对象,书写也很便利。

          项目用到一半,除了登入退出外,也就用了这么两类的api,很简单吧。

  

Facebook C# SDK

         项目开始时查到过两个SDK,一个叫做Facebook C# SDK,更新的很快;另一个叫做Facebook toolkit什么的,从名字上看似乎是微软自己的帮助系列,代码也很庞大,但有半年多没有更新了。而据我所知,今年6月份facebook的api还有改动(突然某天代码失效,后来发现api改了,竟然不兼容!)。所以我们选择更新的比较快的这个。

        代码地址:

         http://facebooksdk.codeplex.com/

         仅支持vs2010,你可以下载了dll然后加载到项目的引用中去。今天我们介绍另外一种引用方式:

          1、在vs2010中,新建web站点(以次举例,也支持mvc、windowsphone),右键项目,选择 Add Library Package Reference,

                  Capture

           把最后那两个安装仅上就可以了。如果没有看到的话,可以从右侧搜索facebook就可以找到了。安装上之后,不仅对应的dll会被拷贝进了,web.config中也会生成对应的两段配置

          configSections段中增加了

          <section name="facebookSettings" type="Facebook.FacebookConfigurationSection" />

          configuration段中增加了

         <facebookSettings appId="{app id}" appSecret="{app secret}" />

         我们把我们申请到的appid和appsecret填入即可。

         前台的页面我们还是需要按照前面讲的javascript的方式进行编写,只是我们appid的位置可以这么写:

        <%: Facebook.FacebookApplication.Current.AppId %>

         到这里,第一步也算迈出去了。详细使用方法,我们举几个例子:

获取用户信息:

// Using dynamic (.Net 4.0 only)
var client = new FacebookClient();
dynamic me = client.Get("me");
string firstName = me.first_name;
string lastName = me.last_name;
string email = me.email;

// Using IDictionary<string, object> (.Net 3.5, .Net 4.0, WP7)
var client = new FacebookClient();
var me = (IDictionary<string,object>)client.Get("me");
string firstName = (string)me["first_name"];
string lastName = (string)me["last_name"];
string email = (string)me["email"];

   获取某一条post的详细信息

// Using dynamic (.Net 4.0 only)
var client = new FacebookClient("my_access_token");
dynamic result = client.Get("19292868552_118464504835613");
string id = result.id;
string fromName = result.from.name;
string fromCategory = result.from.category;
string message = result.message;
int likes = result.likes;
foreach (dynamic comment in result.comments.data) {
	string commentId = comment.id;
	string commentMessage = comment.message;
}

发布一条信息

var client = new FacebookClient("my_access_token");
dynamic parameters = new ExpandoObject();
parameters.message = "Check out this funny article";
parameters.link = "http://www.example.com/article.html";
parameters.picture = "http://www.example.com/article-thumbnail.jpg";
parameters.name = "Article Title";
parameters.caption = "Caption for the link";
parameters.description = "Longer description of the link";
parameters.actions = new {
	name = "View on Zombo",
	link = "http://www.zombo.com",
};
parameters.privacy = new {
	value = "ALL_FRIENDS",
};
parameters.targeting = new {
	countries = "US",
	regions = "6,53",
	locales = "6",
};
dynamic result = client.Post("me/feed", parameters);

访问ADS API

var client = new FacebookClient("my_access_token");

dynamic reportSpec = new ExpandoObject();
reportSpec.report_type = "perf";
reportSpec.summarize_by = "ad";
reportSpec.agg_time = "daily";
reportSpec.filter_obj_ids = new string[] { };
reportSpec.internal_columns = false;
reportSpec.time_start_offset = 172800;
reportSpec.time_stop_offset = 86400;

dynamic scheduleSpec = new ExpandoObject();
scheduleSpec.name = "test_schedule";
scheduleSpec.time_next_ref = DateTime.UtcNow.AddDays(1).ToString();
scheduleSpec.report_spec = reportSpec;
scheduleSpec.frequency = 1;
scheduleSpec.status = 1;
scheduleSpec.email = 1;

dynamic parameters = new ExpandoObject();
parameters.method = "ads.createAdreportSchedules";
parameters.account_id = 1234567891235;
parameters.schedule_specs = scheduleSpecs;
parameters.flags = 1; // Debug Mode


dynamic result = client.Post(parameters);

创建相册

  // create album
  dynamic albumDetails = new ExpandoObject();
  albumDetail.name = "test album";

  dynamic fbResult = fbApp.Post('/me/albums', albumDetails);
  var albumID = fbResult.id;
  uploadPhotos(albumId);

上传图片

        private void uploadPhoto(string albumID)
        {
            var fbUpl = new Facebook.FacebookMediaObject
            {
                FileName = @"Some.png",
                ContentType = "image/png"
            };
            var bytes = System.IO.File.ReadAllBytes(@"C:\somePath\" + fbUpl.FileName);
            fbUpl.SetValue(bytes);

            var photoDetails = new Dictionary<string, object>();
            photoDetails.Add("message", "test photo"); // this will appear on the wall
            photoDetails.Add("image", fbUpl); // the name of this parameter does not matter
            var fbResult = fbApp.Post(@"/" + albumID + @"/photos", photoDetails);
            var result = (IDictionary<string, object>)fbResult; // Or we could use dynamic.. only the photo "id"(s) come back
        }

上传视频

var fb = new FacebookClient("access_token");

dynamic parameters = new ExpandoObject();

parameters.source = new FacebookMediaObject { ContentType = "video/3gpp", FileName = "video.3gp" }.SetValue(File.ReadAllBytes(@"c:\video.3gp"));

parameters.title = "video title";

parameters.description = "video description";

dynamic result = fb.Post("/me/videos", parameters);

Console.WriteLine(result);

可获的进度条和可取消的使用方式

var mediaObject = new FacebookMediaObject

{

ContentType = "image/jpeg",

FileName = Path.GetFileName(_filename)

}

.SetValue(File.ReadAllBytes(_filename));

var fb = new FacebookClient(_accessToken);

fb.PostCompleted += fb_PostCompleted;

fb.PostAsync("/me/photos", new Dictionary<string, object> { { "source", mediaObject } });

 

fb.UploadProgressChanged += fb_UploadProgressChanged;

public void fb_UploadProgressChanged(object sender, FacebookUploadProgressChangedEventArgs e)

{

progressBar1.BeginInvoke(

new MethodInvoker(() =>

{

var totalBytesToSend = e.TotalBytesToSend;

var bytesSent = e.BytesSent;

var state = e.UserState;

progressBar1.Value = e.ProgressPercentage;

}));

}

 

 

public void fb_PostCompleted(object sender, FacebookApiEventArgs e)

{

if (e.Cancelled)

{

var cancellationError = e.Error;

MessageBox.Show("Upload cancelled");

}

else if (e.Error == null)

{

// upload successful.

MessageBox.Show(e.GetResultData().ToString());

}

else

{

// upload failed

MessageBox.Show(e.Error.Message);

}

}

   可以使用fb.CancelAsync()进行结束上传。好了就举这些例子吧,例子代码来源于作者博客。总体感觉使用还是比较方便的。

posted on 2011-08-19 17:18  Jason .Z  阅读(3052)  评论(3编辑  收藏  举报