본문 바로가기

잡다한이야기

Facebook API - 4. C# API 이용

반응형
이 문서는 페이스북(Facebook)에서 제공되어지는 API를 이용하여 내 어플리케이션을 만드는 과정을 설명하고자 합니다.
그 과정에서 이 문서는 아래 전체 과정 중에 4번째 과정인 C# API 이용에 해당합니다.



원래는 설 이후에 작성했었어야 했는데 학업으로 인해 이제야 작성하네요...

우선 쉽게 개발하기 위해서 C#에서 쉽게 Facebook를 사용할 수 있게 하는 DLL를 사용하도록 합니다.

Facebook C# SDK 5.0.8 (BETA)
http://facebooksdk.codeplex.com/releases/view/63226

위 파일 내에는 Facebook API를 쉽게 쓸수 있게 하는 코드와 예제가 있습니다만,
위에 것 말고 저는 Facebook을 이용할 수 있는 다른 프로그램을 이용해서 진행합니다.

https://github.com/facebook/csharp-sdk/tree/master/facebook

위 사이트에 접속하면 [Downloads] 버튼을 이용해 facebook-csharp-sdk-52cf249.zip 파일을 받을 수 있습니다.
압축파일을 풀면 예제와 API 코드가 있습니다만, 여기서 사용할 것은 FacebookAPI.dll 파일입니다.
위치는 \facebook\bin\Debug\FacebookAPI.dll 입니다.



이쯤 해서 저번 2단계에서 확보한 앱정보를 다시 한번 확인해 봅니다.


위 정보에 추가로

■ access_code
2.xzYu_Fxwjy9ppJougJZlZA__.3600.1301580000-100000482185025|R0dva8NtyCOkboV1V99mRHKIN1E

■ access_token
161677497215358|2.xzYu_Fxwjy9ppJougJZlZA__.3600.1301580000-100000482185025|zyUd5YPIGQA4fdHhY3kt6R0g9Tw&expires=7048



Microsoft Visual Studio 2008 → New Project → Visual C# → Windows → Windows Forms Application으로 프로젝트를
프로젝트를 생성하고 위에서 확보한 FacebookAPI.dll 를 References에 추가합니다.


화면 디자인은 아래와 같습니다.


상단에는 Button control을 3개 두었고
중단에는 WebBrowser control를 두었고
하단에는 TextBox control를 배치하였습니다.

그리고 각각 Button 컨트롤은 clieck event를
WebBrowser 컨트롤은 DocumentCompleted event를 메서드와 이벤트핸들로 연결하였습니다.

FacebookAPI를 사용하기 위해 코드 내에 추가를 하고 정보를 담을 변수를 설정해서 별도로 관리합니다.
001.using System;
002.using System;
003.using System.Collections.Generic;
004.using System.ComponentModel;
005.using System.Data;
006.using System.Drawing;
007.using System.Linq;
008.using System.Text;
009.using System.Windows.Forms;
010.
011.using Facebook;
012.
013.namespace Facebook_test
014.{
015. public partial class Form1 : Form
016. {
017. private Facebook.FacebookAPI fbAPI;
018.
019. private string app_id = @"161677497215358";
020. private string app_apikey = @"99d112a71d7dbd65c7de8201a9136d38";
021. private string app_secretcode = @"cf6548162f98a1f257094b36a5f510fa";
022.
023. private string app_access_code = "";
024. private string app_access_token = "";
025.
026. private string CurrStep;
027.
028. public Form1()
029. {
030. InitializeComponent();
031. mfnSHowValues();
032. }
033.
034. private void button1_Click(object sender, EventArgs e)
035. {
036. CurrStep = "Step1_1";
037. string strUrl = "https://graph.facebook.com/oauth/authorize?client_id=" + this.app_id +
039. "&scope=user_about_me,friends_about_me,user_birthday,friends_birthday," +
040. "user_education_history,friends_education_history,user_groups,friends_groups," +
041. "user_hometown,friends_hometown,user_interests,friends_interests," +
042. "user_likes,friends_likes,read_friendlists,manage_friendlists," +
043. "read_stream,ads_management,read_requests,read_stream";
044. webBrowser1.Navigate(strUrl);
045. }
046.
047. private void button2_Click(object sender, EventArgs e)
048. {
049. CurrStep = "Step1_2";
050. string strUrl = "https://graph.facebook.com/oauth/access_token?client_id=" + this.app_id +
052. "&client_secret=" + this.app_secretcode +
053. "&code=" + this.app_access_code;
054. webBrowser1.Navigate(strUrl);
055. }
056.
057. private void button3_Click(object sender, EventArgs e)
058. {
059. string id = "me"; // 자기 자신을 가리킵니다.
060. this.textBox1.Text = "";
061.
062. this.fbAPI = new Facebook.FacebookAPI();
063. if (fbAPI == null) return;
064. JSONObject me = fbAPI.Get("/" + id + "?access_token=" + this.app_access_token);
065.
066. foreach (string k in me.Dictionary.Keys)
067. {
068. JSONObject j = me.Dictionary[k];
069. this.textBox1.Text += j.String + "\r\n";
070. }
071. }
072.
073. private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
074. {
075. if (CurrStep == "Step1_1")
076. {
077. string strQuery = this.webBrowser1.Url.Query;
078.
079. if (strQuery.Substring(0, 6) == "?code=")
080. {
081. this.app_access_code = strQuery.Substring(6, strQuery.Length - 6);
082. mfnSHowValues();
083. }
084. }
085. else if (CurrStep == "Step1_2")
086. {
087. HtmlElementCollection hec = this.webBrowser1.Document.GetElementsByTagName("PRE");
088. String strQuery = hec[0].InnerText;
089.
090. if (strQuery.Substring(0, 13) == "access_token=")
091. {
092. this.app_access_token = strQuery.Substring(13, strQuery.Length - 13);
093.
094. mfnSHowValues();
095. }
096. }
097. }
098.
099. private void mfnSHowValues()
100. {
101. this.textBox1.Text = "app_id = " + this.app_id + "\r\n" +
102. "app_apikey = " + this.app_apikey + "\r\n" +
103. "app_secretcode = " + app_secretcode + "\r\n" +
104. "app_access_code = " + app_access_code + "\r\n" +
105. "app_access_token = " + app_access_token + "\r\n";
106. }
107. }
108.}
위와 같이 코딩을 하였고, 정상적으로 컴파일 되었을 때 실행화면은 아래와 같습니다.



처음 실행한 화면입니다. 현재 가지고 있는 값의 목록을 Textbox에 보여주고 있습니다.
물론 페이스북 자동 로그인이 되어있지 않다면 로그인 메세지가 뜰 것입니다.
이후 현제 테스트 중인 앱에 대한 권한을 요구한다는 메세지가 뜨며 [허가하기]버튼을 누르면 아래와 같이
정상적으로 작동합니다. 최소 한번 [허가하기]버튼을 눌렀다면 이후 로그인 메세지만 뜹니다.
물론 자동 로그인 여부까지 체크한다면 바로 아래 과정으로 진행됩니다.



두번째로 [Get access_code] 버튼을 눌러 access_code를 받았습니다.



세번째로 [Get access_token] 버튼을 눌러 access_token를 받았습니다.



마지막으로 [Get myprofile] 버튼을 눌러 현재 로그인 한 사용자의 기본 정보를 가져옵니다.
이것은 웹브라우저에서
https://graph.facebook.com/me?access_token=161677497215358|2.xzYu_Fxwjy9ppJougJZlZA__.3600.1301580000-100000482185025|zyUd5YPIGQA4fdHhY3kt6R0g9Tw&expires=7048
이렇게 입력하여 아래와 같이 JSON 형식의 데이터를 받는 것과 같습니다.


물론 위 과정에서 처음부터 this.app_access_token 에 전에 확보한 값을 넣어 둔다면
[Get access_code]와 [Get access_token]버튼을 누르지 않고 진행이 가능합니다.

그리고 만약 특정 사용자의 likes 정보를 가져오고 싶다면
fbAPI.Get 메소드를 호출하는 부분에서 아래와 같이 변경하시면 됩니다.
fbAPI.Get("/" + id + "/likes" + "?access_token=" + this.app_access_token);

물론 현재 사용자의 friends 정보를 가져올 수도 있습니다.
fbAPI.Get("/" + id + "/friends" + "?access_token=" + this.app_access_token);

그 외에 필요한 정보는 API document를 참조 바랍니다. (http://developers.facebook.com/docs/)

그리고 코드 중간에 나온 JSONObject 의 경우 내부적으로 Dictionary 객체로 관리되며 그 내부에서도
JSONObject 로 하위로 관리 됩니다. (설명이...;;; 뭐 이리 부실...)

뭐 결국 최종적으로 코드를 최소한으로 축소했기 때문에 내용을 이해 하셨을 것이라 생각되며(무책임;;;)

그대신 현재 예제 코드를 첨부하였으니 보시고 하려는 작업에 작게나마 보탬이 되었으면 싶습니다.
물론 사용하던 facebook 의 예제용 앱은 이제서야 삭제합니다. ^^

 

Facebook_test.zip

 

 

 

 

/////////////http://redcarrot.tistory.com/59 /////////원본입니다.

반응형