1.本博客主要介绍如何应用facebook .net SDK,实现发帖、点赞、上传照片视频等功能,更多关于facebook API,请参考:https://developers.facebook.com
2.注册facebook账号,并且注册facebook app,参考地址:https://developers.facebook.com/apps,注册了app之后,会得到一些此app的信息,
这些信息都是要用到的。
3.注册好了App之后,开始新建解决方案(本例为asp.net mvc4 web app)
4.引入facebook .net sdk,下载地址:https://github.com/facebook-csharp-sdk/facebook-csharp-sdk,关于更多SDK文档地址:https://developers.facebook.com/docs/
除了直接下载之外,还能通过NuGet添加
5.安装完Facebook SDK,对web.config文件做点设置如下
6.一切准备就绪,现在开始使用SDK,首先登入授权,授权过程中有个scope参数,这里面是表示要授权的一些项
FacebookClient fbClient = new FacebookClient(); string appID = ConfigurationManager.AppSettings["AppID"]; string appSecret = ConfigurationManager.AppSettings["AppSecret"]; string redirectUri = ConfigurationManager.AppSettings["RedirectUri"];
public ActionResult Login() { string loginUrl = ""; dynamic loginResult = fbClient.GetLoginUrl(new { client_id = appID, redirect_uri = redirectUri, display = "page", scope = "email,publish_stream,read_stream" //scope = "email,publish_stream,read_stream,share_item,video_upload,photo_upload,create_note,user_friends,publish_actions,export_stream,status_update" }); loginUrl = loginResult.ToString(); if (!string.IsNullOrEmpty(loginUrl)) return Redirect(loginUrl); else return Content("Login failed!"); }
7.登入成功之后会跳转到上文提到的redirect_uri地址,而且会传回一个code值,我们用传回来的code去换取access token(这个灰常重要)
public ActionResult FBMain() { string code = Request.Params["code"]; string accessToken = ""; if (!string.IsNullOrEmpty(code)) { ///Get access token dynamic tokenResult = fbClient.Get("/oauth/access_token", new { client_id = appID, client_secret = appSecret, redirect_uri = redirectUri, code = code }); accessToken = tokenResult.access_token.ToString(); ViewBag.Message = "Get token successful!The token value:" + accessToken; } else { ViewBag.Message = "faield to get token!"; } return View(); }
8.拿到access token之后,就可以用它做很多事情了,例如发状态上传照片
a.发状态
/// <summary> ///Post a news feed /// </summary> /// <author>Johnny</author> /// <param name="status">the text message</param> /// <date>2013/10/25, 17:09:49</date> /// <returns>a posted ID</returns> public string Post(string status) { string id = null; try { if (!string.IsNullOrEmpty(accessToken)) { FacebookClient fbClient = new FacebookClient(accessToken); dynamic postResult = fbClient.Post("/me/feed", new { message = status }); id = postResult.id.ToString(); } else errorMessage = ErrorTokenMessage; } catch (FacebookApiException fbex) { errorMessage = fbex.Message; } return id; }
b.发链接
/// <summary> ///share a feed /// </summary> /// <author>Johnny</author> /// <date>2013/10/29, 09:46:08</date> /// <param name="status">the text message</param> /// <param name="link">an valid link(eg: http://www.mojikan.com)</param> /// valid tools:https://developers.facebook.com/tools/debug /// <returns>return a post id</returns> public string Share(string status, string link) { string shareID = null; try { if (!string.IsNullOrEmpty(accessToken)) { FacebookClient fbClient = new FacebookClient(accessToken); dynamic shareResult = fbClient.Post("me/feed", new { message = status, link = link }); shareID = shareResult.id; } else errorMessage = ErrorTokenMessage; } catch (FacebookApiException fbex) { errorMessage = fbex.Message; } return shareID; }
c.传照片
/// <summary> ///upload picture /// </summary> /// <author>Johnny</author> /// <param name="status">the text message</param> /// <param name="path">the picture's path</param> /// <date>2013/10/31, 15:24:51</date> /// <returns>picture id & post id</returns> public string PostPicture(String status, String path) { string result = null; try { if (!string.IsNullOrEmpty(accessToken)) { FacebookClient fbClient = new FacebookClient(accessToken); using (var stream = File.OpenRead(path)) { dynamic pictureResult = fbClient.Post("me/photos", new { message = status, source = new FacebookMediaStream { ContentType = "image/jpg", FileName = Path.GetFileName(path) }.SetValue(stream) }); if (pictureResult != null) result = pictureResult.ToString(); } } else errorMessage = ErrorTokenMessage; } catch (FacebookApiException fbex) { errorMessage = fbex.Message; } return result; }
d.传视频
/// <summary> ///upload video /// </summary> /// <author>Johnny</author> /// <param name="status">the text message</param> /// <param name="path">the video's path</param> /// <date>2013/10/31, 15:26:40</date> /// <returns>an video id</returns> //The aspect ratio of the video must be between 9x16 and 16x9, and the video cannot exceed 1024MB or 180 minutes in length. public string PostVideo(String status, String path) { string result = null; try { if (!string.IsNullOrEmpty(accessToken)) { FacebookClient fbClient = new FacebookClient(accessToken); Stream stream = File.OpenRead(path); FacebookMediaStream medStream = new FacebookMediaStream { ContentType = "video/mp4", FileName = Path.GetFileName(path) }.SetValue(stream); dynamic videoResult = fbClient.Post("me/videos", new { description = status, source = medStream }); if (videoResult != null) result = videoResult.ToString(); } else errorMessage = ErrorTokenMessage; } catch (FacebookApiException fbex) { errorMessage = fbex.Message; } return result; }
e.点赞
/// <summary> ///likes a news feed /// </summary> /// <author>Johnny</author> /// <param name="postID">a post id</param> /// <returns>return a bool value</returns> /// <date>2013/10/25, 18:35:51</date> public bool Like(string postID) { bool result = false; try { if (!string.IsNullOrEmpty(accessToken)) { FacebookClient fbClient = new FacebookClient(accessToken); dynamic likeResult = fbClient.Post("/" + postID + "/likes", new { //post_id = postID, }); result = Convert.ToBoolean(likeResult); } else errorMessage = ErrorTokenMessage; } catch (FacebookApiException fbex) { errorMessage = fbex.Message; } return result; }
f.发送App邀请
/// <summary> ///send a app request to the user. /// </summary> /// <author>Johnny</author> /// <param name="status">the request message</param> /// <returns>return app object ids & user ids</returns> /// <date>2013/10/28, 09:33:35</date> public string AppRequest(string userID, string status) { string result = null; try { string appToken = this.GetAppAccessToken(); if (!string.IsNullOrEmpty(appToken)) { FacebookClient fbClient = new FacebookClient(appToken); dynamic requestResult = fbClient.Post(userID + "/apprequests", new { message = status }); result = requestResult.ToString(); } else errorMessage = ErrorTokenMessage; } catch (FacebookApiException fbex) { errorMessage = fbex.Message; } return result; } /// <summary> ///Get an app access token /// </summary> /// <author>Johnny</author> /// <date>2013/11/05, 11:52:37</date> private string GetAppAccessToken() { string appToken = null; try { FacebookClient client = new FacebookClient(); dynamic token = client.Get("/oauth/access_token", new { client_id = appID, client_secret = appSecret, grant_type = "client_credentials" }); appToken = token.access_token.ToString(); } catch (FacebookApiException fbex) { errorMessage = fbex.Message; } return appToken; }
g.获取状态列表
/// <summary> ///get current user's post list /// </summary> /// <author>Johnny</author> /// <returns>return post list</returns> /// <date>2013/10/30, 13:42:37</date> public List<Post> GetPostList() { List<Post> postList = null; try { if (!string.IsNullOrEmpty(accessToken)) { FacebookClient fbClient = new FacebookClient(accessToken); dynamic postResult = (IDictionary<string, object>)fbClient.Get("/me/feed"); postList = new List<Post>(); postList = GeneralPostList(postResult); } else errorMessage = ErrorTokenMessage; } catch (FacebookApiException fbex) { errorMessage = fbex.Message; } return postList; } /// <summary> ///get one user's post list /// </summary> /// <param name="userID">user id</param> /// <returns>return post list</returns> /// <author>Johnny</author> /// <date>2013/11/06, 17:06:19</date> public List<Post> GetPostList(string userID) { List<Post> postList = null; try { if (!string.IsNullOrEmpty(accessToken)) { FacebookClient fbClient = new FacebookClient(accessToken); postList = new List<Post>(); dynamic postResult = (IDictionary<string, object>)fbClient.Get("/" + userID + "/feed"); postList = GeneralPostList(postResult); } else errorMessage = ErrorTokenMessage; } catch (FacebookApiException fbex) { errorMessage = fbex.Message; } return postList; } private List<Post> GeneralPostList(dynamic postResult) { List<Post> postList = null; try { postList = new List<Post>(); foreach (var item in postResult.data) { Dictionary<string, object>.KeyCollection keys = item.Keys; Post post = new Post(); List<Action> actionList = new List<Action>(); dynamic actions = item.actions; if (actions != null) { foreach (var ac in actions) { Action action = new Action(); action.link = ac.link.ToString(); action.name = ac.name.ToString(); actionList.Add(action); } post.Actions = actionList; } if (keys.Contains<string>("caption")) post.Caption = item.caption.ToString(); if (keys.Contains<string>("created_time")) post.CreatedTime = item.created_time.ToString(); if (keys.Contains<string>("description")) post.Description = item.description.ToString(); if (keys.Contains<string>("from")) { FromUser fUser = new FromUser(); fUser.ID = item.from.id.ToString(); fUser.Name = item.from.name.ToString(); post.From = fUser; } if (keys.Contains<string>("icon")) post.Icon = item.icon.ToString(); post.ID = item.id.ToString(); if (keys.Contains<string>("include_hidden")) post.IncludeHidden = item.include_hidden.ToString(); if (keys.Contains<string>("link")) post.Link = item.link.ToString(); if (keys.Contains<string>("message")) post.Message = item.message.ToString(); if (keys.Contains<string>("picture")) post.Picture = item.picture.ToString(); if (keys.Contains<string>("name")) post.Name = item.name.ToString(); if (keys.Contains<string>("object_id")) post.ObjectID = item.object_id.ToString(); if (keys.Contains<string>("privacy")) post.Privacy = item.privacy.ToString(); if (keys.Contains<string>("shares")) post.Shares = item.shares.ToString(); if (keys.Contains<string>("source")) post.Source = item.source.ToString(); if (keys.Contains<string>("status_type")) post.StatusType = item.status_type.ToString(); if (keys.Contains<string>("story")) post.Story = item.story.ToString(); if (keys.Contains<string>("type")) post.Type = item.type.ToString(); if (keys.Contains<string>("updated_time")) post.UpdatedTime = item.updated_time.ToString(); postList.Add(post); } } catch (FacebookApiException fbex) { errorMessage = fbex.Message; } return postList; }
h.获取个人用户信息和朋友信息
/// <summary> ///Get the current user info /// </summary> /// <author>Johnny</author> /// <returns>return an UserInfo</returns> /// <date>2013/10/29, 13:36:07</date> public UserInfo GetUserInfo() { UserInfo userInfo = null; try { if (!string.IsNullOrEmpty(accessToken)) { FacebookClient fbClient = new FacebookClient(accessToken); dynamic user = fbClient.Get("/me"); Dictionary<string, object>.KeyCollection keys = user.Keys; userInfo = new UserInfo(); userInfo.ID = user.id.ToString(); if (keys.Contains<string>("name")) userInfo.Name = user.name.ToString(); if (keys.Contains<string>("first_name")) userInfo.FirstName = user.first_name.ToString(); if (keys.Contains<string>("last_name")) userInfo.LastName = user.last_name.ToString(); if (keys.Contains<string>("username")) userInfo.UserName = user.username.ToString(); if (keys.Contains<string>("link")) userInfo.Link = user.link.ToString(); if (keys.Contains<string>("timezone")) userInfo.TimeZone = user.timezone.ToString(); if (keys.Contains<string>("updated_time")) userInfo.UpdatedTime = Convert.ToDateTime(user.updated_time); if (keys.Contains<string>("verified")) userInfo.Verified = user.verified.ToString(); if (keys.Contains<string>("gender")) userInfo.Gender = user.gender.ToString(); } else errorMessage = ErrorTokenMessage; } catch (FacebookApiException fbex) { errorMessage = fbex.Message; } return userInfo; } /// <summary> ///get friends info /// </summary> /// <author>Johnny</author> /// <returns>return list of UserInfo</returns> /// <date>2013/10/31, 15:57:40</date> public List<UserInfo> GetFriendInfoList() { List<UserInfo> userList = null; try { if (!string.IsNullOrEmpty(accessToken)) { FacebookClient fbClient = new FacebookClient(accessToken); dynamic friends = fbClient.Get("/me/friends"); if (friends != null) { userList = new List<UserInfo>(); foreach (dynamic item in friends.data) { UserInfo user = new UserInfo(); user.ID = item.id.ToString(); user.Name = item.name.ToString(); userList.Add(user); } } } else errorMessage = ErrorTokenMessage; } catch (FacebookApiException fbex) { errorMessage = fbex.Message; } return userList; }
以上就是一些常用的API。
关于facebook翻墙,请参考这里进行设置,http://www.i7086.com/gugeyingyonggoagentrangninziyoufangwenwangluotuwenjiaocheng
如设置成功,可以通过谷歌浏览器顺利打开facebook网站,关于证书导入:http://jingyan.baidu.com/article/ca00d56caf98d3e99eebcf16.html
配置好了goagent,打开它,然后用谷歌浏览器就可以顺利打开facebook,youtobe等网站了,如果要通过IE打开,则改一下设置就行了,谷歌和IE都能开。