浅谈 facebook .net sdk 应用

今天看了一篇非常好的文章,就放在这里与大家分享一下,顺便也给自己留一份。这段时间一直在学习MVC,另外如果大家有什么好的建议或者学习的地方,也请告知一下,谢谢。

  这篇主要介绍如何应用facebook .net SDK,实现发帖、点赞、上传照片视频等功能,更多关于facebook API,请参考:https://developers.facebook.com

  1、注册facebook账号,并且注册facebook app,参考地址:https://developers.facebook.com/apps,注册了app之后,会得到一些此app的信息,

  这些信息都是要用到的。

2、注册好了App之后,开始新建解决方案(本例为asp.net mvc4 web app)

3、引入facebook .net sdk,下载地址:https://github.com/facebook-csharp-sdk/facebook-csharp-sdk,关于更多SDK文档地址:https://developers.facebook.com/docs/

除了直接下载之外,还能通过NuGet添加

4、安装完Facebook SDK,对web.config文件做点设置如下

5、一切准备就绪,现在开始使用SDK,首先登入授权,授权过程中有个scope参数,这里面是表示要授权的一些项

1 FacebookClient fbClient = new FacebookClient();
2         string appID = ConfigurationManager.AppSettings["AppID"];
3         string appSecret = ConfigurationManager.AppSettings["AppSecret"];
4         string redirectUri = ConfigurationManager.AppSettings["RedirectUri"];
View Code
 1 public ActionResult Login()
 2         {
 3             string loginUrl = "";
 4             dynamic loginResult = fbClient.GetLoginUrl(new
 5             {
 6                 client_id = appID,
 7                 redirect_uri = redirectUri,
 8                 display = "page",
 9                 scope = "email,publish_stream,read_stream"
10                 //scope = "email,publish_stream,read_stream,share_item,video_upload,photo_upload,create_note,user_friends,publish_actions,export_stream,status_update"                  
11             });
12             loginUrl = loginResult.ToString();
13             if (!string.IsNullOrEmpty(loginUrl))
14                 return Redirect(loginUrl);
15             else
16                 return Content("登录失败!");
17         }
View Code

 

 

6、登入成功之后会跳转到上文提到的redirect_uri地址,而且会传回一个code值,我们用传回来的code去换取access token(这个灰常重要)

 1 public ActionResult FBMain()
 2         {
 3             string code = Request.Params["code"];
 4             string accessToken = "";
 5             if (!string.IsNullOrEmpty(code))
 6             {
 7                 ///Get access token
 8                 dynamic tokenResult = fbClient.Get("/oauth/access_token", new
 9                 {
10                     client_id = appID,
11                     client_secret = appSecret,
12                     redirect_uri = redirectUri,
13                     code = code
14                 });
15                 accessToken = tokenResult.access_token.ToString();
16                 ViewBag.Message = "Get token successful!The token value:" + accessToken;
17             }
18             else
19             {
20                 ViewBag.Message = "faield to get token!";
21             }
22             return View();
23         }
View Code

 

7、拿到access token之后,就可以用它做很多事情了,例如发状态上传照片

 a.发状态

 1 /// <summary>
 2         ///Post a news feed
 3         /// </summary>
 4         /// <author>Johnny</author>
 5         /// <param name="status">the text message</param>
 6         /// <date>2013/10/25, 17:09:49</date>
 7         /// <returns>a posted ID</returns>
 8         public string Post(string status)
 9         {
10             string id = null;
11 
12             try
13             {
14                 if (!string.IsNullOrEmpty(accessToken))
15                 {
16                     FacebookClient fbClient = new FacebookClient(accessToken);
17                     dynamic postResult = fbClient.Post("/me/feed", new
18                     {
19                         message = status
20                     });
21                     id = postResult.id.ToString();
22                 }
23                 else
24                     errorMessage = ErrorTokenMessage;
25             }
26             catch (FacebookApiException fbex)
27             {
28                 errorMessage = fbex.Message;
29             }
30 
31             return id;
32         }
View Code

b.发链接

 1 /// <summary>
 2         ///share a feed
 3         /// </summary>
 4         /// <author>Johnny</author>
 5         /// <date>2013/10/29, 09:46:08</date>
 6         /// <param name="status">the text message</param>
 7         /// <param name="link">an valid link(eg: http://www.mojikan.com)</param>
 8         /// valid tools:https://developers.facebook.com/tools/debug
 9         /// <returns>return a post id</returns>
10         public string Share(string status, string link)
11         {
12             string shareID = null;
13             try
14             {
15                 if (!string.IsNullOrEmpty(accessToken))
16                 {
17                     FacebookClient fbClient = new FacebookClient(accessToken);
18                     dynamic shareResult = fbClient.Post("me/feed", new
19                      {
20                          message = status,
21                          link = link
22                      });
23                     shareID = shareResult.id;
24                 }
25                 else
26                     errorMessage = ErrorTokenMessage;
27             }
28             catch (FacebookApiException fbex)
29             {
30                 errorMessage = fbex.Message;
31             }
32             return shareID;
33         }
View Code

c.传照片

 1 /// <summary>
 2         ///upload picture
 3         /// </summary>
 4         /// <author>Johnny</author>
 5         /// <param name="status">the text message</param>
 6         /// <param name="path">the picture's path</param>
 7         /// <date>2013/10/31, 15:24:51</date>
 8         /// <returns>picture id & post id</returns>
 9         public string PostPicture(String status, String path)
10         {
11             string result = null;
12             try
13             {
14                 if (!string.IsNullOrEmpty(accessToken))
15                 {
16                     FacebookClient fbClient = new FacebookClient(accessToken);
17                     using (var stream = File.OpenRead(path))
18                     {
19                         dynamic pictureResult = fbClient.Post("me/photos",
20                                                      new
21                                                      {
22                                                          message = status,
23                                                          source = new FacebookMediaStream
24                                                          {
25                                                              ContentType = "image/jpg",
26                                                              FileName = Path.GetFileName(path)
27                                                          }.SetValue(stream)
28                                                      });
29                         if (pictureResult != null)
30                             result = pictureResult.ToString();
31                     }
32                 }
33                 else
34                     errorMessage = ErrorTokenMessage;
35             }
36             catch (FacebookApiException fbex)
37             {
38                 errorMessage = fbex.Message;
39             }
40             return result;
41         }
View Code

d.传视频

 1 /// <summary>
 2         ///upload video
 3         /// </summary>
 4         /// <author>Johnny</author>
 5         /// <param name="status">the text message</param>
 6         /// <param name="path">the video's path</param>
 7         /// <date>2013/10/31, 15:26:40</date>
 8         /// <returns>an video id</returns>
 9         //The aspect ratio of the video must be between 9x16 and 16x9, and the video cannot exceed 1024MB or 180 minutes in length.
10         public string PostVideo(String status, String path)
11         {
12             string result = null;
13             try
14             {
15                 if (!string.IsNullOrEmpty(accessToken))
16                 {
17                     FacebookClient fbClient = new FacebookClient(accessToken);
18                     Stream stream = File.OpenRead(path);
19                     FacebookMediaStream medStream = new FacebookMediaStream
20                                                            {
21                                                                ContentType = "video/mp4",
22                                                                FileName = Path.GetFileName(path)
23                                                            }.SetValue(stream);
24 
25                     dynamic videoResult = fbClient.Post("me/videos",
26                                                        new
27                                                        {
28                                                            description = status,
29                                                            source = medStream
30                                                        });
31                     if (videoResult != null)
32                         result = videoResult.ToString();
33                 }
34                 else
35                     errorMessage = ErrorTokenMessage;
36             }
37             catch (FacebookApiException fbex)
38             {
39                 errorMessage = fbex.Message;
40             }
41             return result;
42         }
View Code

e.点赞

 1 /// <summary>
 2         ///likes a news feed
 3         /// </summary>
 4         /// <author>Johnny</author>
 5         /// <param name="postID">a post id</param>
 6         /// <returns>return a bool value</returns>
 7         /// <date>2013/10/25, 18:35:51</date>
 8         public bool Like(string postID)
 9         {
10             bool result = false;
11             try
12             {
13                 if (!string.IsNullOrEmpty(accessToken))
14                 {
15                     FacebookClient fbClient = new FacebookClient(accessToken);
16                     dynamic likeResult = fbClient.Post("/" + postID + "/likes", new
17                     {
18                         //post_id = postID,
19                     });
20                     result = Convert.ToBoolean(likeResult);
21                 }
22                 else
23                     errorMessage = ErrorTokenMessage;
24             }
25             catch (FacebookApiException fbex)
26             {
27                 errorMessage = fbex.Message;
28             }
29             return result;
30         }
View Code

f.发送App邀请

 1 /// <summary>
 2         ///send a app request to the user.
 3         /// </summary>
 4         /// <author>Johnny</author>
 5         /// <param name="status">the request message</param>
 6         /// <returns>return app object ids & user ids</returns>
 7         /// <date>2013/10/28, 09:33:35</date>
 8         public string AppRequest(string userID, string status)
 9         {
10             string result = null;
11             try
12             {
13                 string appToken = this.GetAppAccessToken();
14                 if (!string.IsNullOrEmpty(appToken))
15                 {
16                     FacebookClient fbClient = new FacebookClient(appToken);
17                     dynamic requestResult = fbClient.Post(userID + "/apprequests", new
18                       {
19                           message = status
20                       });
21                     result = requestResult.ToString();
22                 }
23                 else
24                     errorMessage = ErrorTokenMessage;
25             }
26             catch (FacebookApiException fbex)
27             {
28                 errorMessage = fbex.Message;
29             }
30             return result;
31         }
32 
33         /// <summary>
34         ///Get an app access token
35         /// </summary>
36         /// <author>Johnny</author>
37         /// <date>2013/11/05, 11:52:37</date>
38         private string GetAppAccessToken()
39         {
40             string appToken = null;
41             try
42             {
43                 FacebookClient client = new FacebookClient();
44                 dynamic token = client.Get("/oauth/access_token", new
45                 {
46                     client_id = appID,
47                     client_secret = appSecret,
48                     grant_type = "client_credentials"
49                 });
50 
51                 appToken = token.access_token.ToString();
52             }
53             catch (FacebookApiException fbex)
54             {
55                 errorMessage = fbex.Message;
56             }
57             return appToken;
58         }
View Code

g.获取状态列表

  1 /// <summary>
  2         ///get current user's post list
  3         /// </summary>
  4         /// <author>Johnny</author>
  5         /// <returns>return post list</returns>
  6         /// <date>2013/10/30, 13:42:37</date>
  7         public List<Post> GetPostList()
  8         {
  9             List<Post> postList = null;
 10             try
 11             {
 12                 if (!string.IsNullOrEmpty(accessToken))
 13                 {
 14                     FacebookClient fbClient = new FacebookClient(accessToken);
 15                     dynamic postResult = (IDictionary<string, object>)fbClient.Get("/me/feed");
 16                     postList = new List<Post>();
 17                     postList = GeneralPostList(postResult);
 18                 }
 19                 else
 20                     errorMessage = ErrorTokenMessage;
 21             }
 22             catch (FacebookApiException fbex)
 23             {
 24                 errorMessage = fbex.Message;
 25             }
 26             return postList;
 27         }
 28 
 29 
 30         /// <summary>
 31         ///get one user's post list
 32         /// </summary>
 33         /// <param name="userID">user id</param>
 34         /// <returns>return post list</returns>
 35         /// <author>Johnny</author>
 36         /// <date>2013/11/06, 17:06:19</date>
 37         public List<Post> GetPostList(string userID)
 38         {
 39             List<Post> postList = null;
 40             try
 41             {
 42                 if (!string.IsNullOrEmpty(accessToken))
 43                 {
 44                     FacebookClient fbClient = new FacebookClient(accessToken);
 45                     postList = new List<Post>();
 46                     dynamic postResult = (IDictionary<string, object>)fbClient.Get("/" + userID + "/feed");
 47                     postList = GeneralPostList(postResult);
 48                 }
 49                 else
 50                     errorMessage = ErrorTokenMessage;
 51             }
 52             catch (FacebookApiException fbex)
 53             {
 54                 errorMessage = fbex.Message;
 55             }
 56             return postList;
 57         }
 58 
 59         private List<Post> GeneralPostList(dynamic postResult)
 60         {
 61             List<Post> postList = null;
 62             try
 63             {
 64                 postList = new List<Post>();
 65                 foreach (var item in postResult.data)
 66                 {
 67                     Dictionary<string, object>.KeyCollection keys = item.Keys;
 68                     Post post = new Post();
 69 
 70                     List<Action> actionList = new List<Action>();
 71                     dynamic actions = item.actions;
 72                     if (actions != null)
 73                     {
 74                         foreach (var ac in actions)
 75                         {
 76                             Action action = new Action();
 77                             action.link = ac.link.ToString();
 78                             action.name = ac.name.ToString();
 79 
 80                             actionList.Add(action);
 81                         }
 82                         post.Actions = actionList;
 83                     }
 84 
 85                     if (keys.Contains<string>("caption"))
 86                         post.Caption = item.caption.ToString();
 87                     if (keys.Contains<string>("created_time"))
 88                         post.CreatedTime = item.created_time.ToString();
 89                     if (keys.Contains<string>("description"))
 90                         post.Description = item.description.ToString();
 91 
 92                     if (keys.Contains<string>("from"))
 93                     {
 94                         FromUser fUser = new FromUser();
 95                         fUser.ID = item.from.id.ToString();
 96                         fUser.Name = item.from.name.ToString();
 97                         post.From = fUser;
 98                     }
 99 
100                     if (keys.Contains<string>("icon"))
101                         post.Icon = item.icon.ToString();
102 
103                     post.ID = item.id.ToString();
104 
105                     if (keys.Contains<string>("include_hidden"))
106                         post.IncludeHidden = item.include_hidden.ToString();
107 
108                     if (keys.Contains<string>("link"))
109                         post.Link = item.link.ToString();
110 
111                     if (keys.Contains<string>("message"))
112                         post.Message = item.message.ToString();
113 
114                     if (keys.Contains<string>("picture"))
115                         post.Picture = item.picture.ToString();
116 
117                     if (keys.Contains<string>("name"))
118                         post.Name = item.name.ToString();
119 
120                     if (keys.Contains<string>("object_id"))
121                         post.ObjectID = item.object_id.ToString();
122 
123                     if (keys.Contains<string>("privacy"))
124                         post.Privacy = item.privacy.ToString();
125 
126                     if (keys.Contains<string>("shares"))
127                         post.Shares = item.shares.ToString();
128 
129                     if (keys.Contains<string>("source"))
130                         post.Source = item.source.ToString();
131 
132                     if (keys.Contains<string>("status_type"))
133                         post.StatusType = item.status_type.ToString();
134 
135                     if (keys.Contains<string>("story"))
136                         post.Story = item.story.ToString();
137 
138                     if (keys.Contains<string>("type"))
139                         post.Type = item.type.ToString();
140 
141                     if (keys.Contains<string>("updated_time"))
142                         post.UpdatedTime = item.updated_time.ToString();
143 
144                     postList.Add(post);
145                 }
146             }
147             catch (FacebookApiException fbex)
148             {
149                 errorMessage = fbex.Message;
150             }
151             return postList;
152         }
View Code

h.获取个人用户信息和朋友信息

 1 /// <summary>
 2         ///Get the current user info
 3         /// </summary>
 4         /// <author>Johnny</author>
 5         /// <returns>return an UserInfo</returns>
 6         /// <date>2013/10/29, 13:36:07</date>
 7         public UserInfo GetUserInfo()
 8         {
 9             UserInfo userInfo = null;
10             try
11             {
12                 if (!string.IsNullOrEmpty(accessToken))
13                 {
14                     FacebookClient fbClient = new FacebookClient(accessToken);
15                     dynamic user = fbClient.Get("/me");
16                     Dictionary<string, object>.KeyCollection keys = user.Keys;
17                     userInfo = new UserInfo();
18                     userInfo.ID = user.id.ToString();
19                     if (keys.Contains<string>("name"))
20                         userInfo.Name = user.name.ToString();
21                     if (keys.Contains<string>("first_name"))
22                         userInfo.FirstName = user.first_name.ToString();
23                     if (keys.Contains<string>("last_name"))
24                         userInfo.LastName = user.last_name.ToString();
25                     if (keys.Contains<string>("username"))
26                         userInfo.UserName = user.username.ToString();
27                     if (keys.Contains<string>("link"))
28                         userInfo.Link = user.link.ToString();
29                     if (keys.Contains<string>("timezone"))
30                         userInfo.TimeZone = user.timezone.ToString();
31                     if (keys.Contains<string>("updated_time"))
32                         userInfo.UpdatedTime = Convert.ToDateTime(user.updated_time);
33                     if (keys.Contains<string>("verified"))
34                         userInfo.Verified = user.verified.ToString();
35                     if (keys.Contains<string>("gender"))
36                         userInfo.Gender = user.gender.ToString();
37                 }
38                 else
39                     errorMessage = ErrorTokenMessage;
40             }
41             catch (FacebookApiException fbex)
42             {
43                 errorMessage = fbex.Message;
44             }
45             return userInfo;
46         }
47 
48         /// <summary>
49         ///get friends info
50         /// </summary>
51         /// <author>Johnny</author>
52         /// <returns>return list of UserInfo</returns>
53         /// <date>2013/10/31, 15:57:40</date>
54         public List<UserInfo> GetFriendInfoList()
55         {
56             List<UserInfo> userList = null;
57             try
58             {
59                 if (!string.IsNullOrEmpty(accessToken))
60                 {
61                     FacebookClient fbClient = new FacebookClient(accessToken);
62                     dynamic friends = fbClient.Get("/me/friends");
63                     if (friends != null)
64                     {
65                         userList = new List<UserInfo>();
66                         foreach (dynamic item in friends.data)
67                         {
68                             UserInfo user = new UserInfo();
69                             user.ID = item.id.ToString();
70                             user.Name = item.name.ToString();
71 
72                             userList.Add(user);
73                         }
74                     }
75                 }
76                 else
77                     errorMessage = ErrorTokenMessage;
78             }
79             catch (FacebookApiException fbex)
80             {
81                 errorMessage = fbex.Message;
82             }
83             return userList;
84         }
View Code

希望这些也能让需要的人看到,对大家有所帮助。

 

posted @ 2013-11-14 15:23  妍珊  阅读(3021)  评论(4编辑  收藏  举报