应用facebook .net sdk
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都能开。
应用facebook .net sdk的更多相关文章
- 浅谈 facebook .net sdk 应用
今天看了一篇非常好的文章,就放在这里与大家分享一下,顺便也给自己留一份.这段时间一直在学习MVC,另外如果大家有什么好的建议或者学习的地方,也请告知一下,谢谢. 这篇主要介绍如何应用facebook ...
- 使用Facebook的SDK判斷來訪者是否已經按讃并成為本站粉絲團的成員
今天公司裡要做活動,其中有一項活動內容是要求來訪者按一下facebook粉絲團的讃,按了讃之後贈送現金.Facebook被墻大家眾所周知,在百度搜了一下發現因為被墻的原因導致國內涉及到Facebook ...
- facebook .net sdk 应用
浅谈 facebook .net sdk 应用 今天看了一篇非常好的文章,就放在这里与大家分享一下,顺便也给自己留一份.这段时间一直在学习MVC,另外如果大家有什么好的建议或者学习的地方,也请告知 ...
- 零基础图文傻瓜教程接入Facebook的sdk
零基础图文傻瓜教程接入Facebook的sdk 本人视频教程系类 iOS中CALayer的使用 0. 先解决你的 VPN FQ上外网问题,亲,解决这一步才能进行后续操作^_^. 1. 点击右侧链接 ...
- 手游服务器端接入facebook的SDK
手游如果支持facebook登录,就要接入facebook的登录SDK.刚好工作中自己做了这一块的接入功能现在记录分享下来提供一个参考. 当前只是接入了登录这个功能,先简单的说说接入facebook登 ...
- 在Android上实现使用Facebook登录(基于Facebook SDK 3.5)
准备工作: 1. Facebook帐号,国内开发者需要一个vpn帐号(网页可以浏览,手机可以访问) 2. 使用Facebook的SDK做应用需要一个Key Hashes值. 2 ...
- 分享前端Facebook及Twitter第三方登录
最近公司要求做海外的第三方登录:目前只做了Facebook和Twitter;国内百度到的信息太少VPN FQ百度+Google了很久终于弄好了.但是做第三方登录基本上都有个特点就是引入必须的js,设置 ...
- Android Facebook和Twitter分享
1. 背景 在年初的时候,公司的项目有个新的需求,在英文版的应用中加入Facebook和Twitter分享功能. 2. 完成情况 由于这个项目比较急,所以开发这个功能从预研到接入总共耗时一周.后来,在 ...
- Facebook
Facebook登录为iOS Facebook的SDK为iOS提供了各种登录的经验,你的应用程序可以使用它来 验证一个人.这份文件包括了所有你需要知道,以落实Facebook登录在你的iOS应用程 ...
随机推荐
- 2014年最新的辛星html、css教程打包公布了,免积分,纯PDF(还有PHP奥)
首先说一下,这个教程是我的全部的博客的精华,我整理了两天之后才做出的这个pdf文档,累死我了,以下免积分给大家,希望大家可以不吝指正,提出它的一些不足什么的,谢谢啦: 以下就是它的下载地址了:2014 ...
- 从头开始学JavaScript 笔记(一)——基础中的基础
原文:从头开始学JavaScript 笔记(一)--基础中的基础 概要:javascript的组成. 各个组成部分的作用 . 一.javascript的组成 javascript ECMASc ...
- JavaWeb显示器
本文研究的总结.欢迎转载,但请注明出处:http://blog.csdn.net/pistolove/article/details/44310967 A:监听器的定义 专门用于其它对象身上 ...
- 如此高效通用的分页存储过程是带有sql注入漏洞的
原文:如此高效通用的分页存储过程是带有sql注入漏洞的 在google中搜索“分页存储过程”会出来好多结果,是大家常用的分页存储过程,今天我却要说它是有漏洞的,而且漏洞无法通过修改存储过程进行补救,如 ...
- C#中实现WebBrowser控件的HTML源代码读写
原文:C#中实现WebBrowser控件的HTML源代码读写 C#中实现WebBrowser控件的HTML源代码读写http://www.blogcn.com/user8/flier_lu/index ...
- iOS开发的一些奇巧淫技2
能不能只用一个pan手势来代替UISwipegesture的各个方向? - (void)pan:(UIPanGestureRecognizer *)sender { typedef NS_ENUM(N ...
- ultraEdit-32 PHP/HTML智能提示
原文 ultraEdit-32 PHP/HTML智能提示 高级–>配置–>编辑器–>自动完成–>勾选自动显示……选项,在下面输入框中输入你要求输出多个字符才出现提示,比如 ec ...
- c语言发挥帕斯卡三角
我们已经确定了帕斯卡三角的规则,下面是我的代码,非常实用哦! !! #include<stdio.h> void main() { int i,j,n,k; sca ...
- 《java系统性能优化》--2.高速缓存
上一节.简介了怎样发现性能瓶颈.从这节開始.我会和大家分享我在项目中做的一些性能调优工作.这个系列没有什么顺序可言,认为什么重要.就说说什么. 这节.我们聊缓存. 最開始接触缓存这个词,是学习硬件知识 ...
- POJ 3390 Print Words in Lines(DP)
Print Words in Lines Time Limit: 1000MS Memory Limit: 65536K Total Submissions: 1624 Accepted: 864 D ...