淺談 facebook .net sdk 應用

今天看了一篇很是好的文章,就放在這裏與你們分享一下,順便也給本身留一份。這段時間一直在學習MVC,另外若是你們有什麼好的建議或者學習的地方,也請告知一下,謝謝。git

  這篇主要介紹如何應用facebook .net SDK,實現發帖、點贊、上傳照片視頻等功能,更多關於facebook API,請參考:https://developers.facebook.comgithub

  一、註冊facebook帳號,而且註冊facebook app,參考地址:https://developers.facebook.com/apps,註冊了app以後,會獲得一些此app的信息,web

  這些信息都是要用到的。mvc

二、註冊好了App以後,開始新建解決方案(本例爲asp.net mvc4 web app)app

三、引入facebook .net sdk,下載地址:https://github.com/facebook-csharp-sdk/facebook-csharp-sdk,關於更多SDK文檔地址:https://developers.facebook.com/docs/asp.net

除了直接下載以外,還能經過NuGet添加ide

四、安裝完Facebook SDK,對web.config文件作點設置以下post

五、一切準備就緒,如今開始使用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

 

 

六、登入成功以後會跳轉到上文提到的redirect_uri地址,並且會傳回一個code值,咱們用傳回來的code去換取access token(這個灰常重要)this

 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

 

七、拿到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

但願這些也能讓須要的人看到,對你們有所幫助。

相關文章
相關標籤/搜索