> Hello World !!!

     

@syaku

jQuery Syaku Facebook API : 자바스크립트용 페이스북 API 연동

written by Seok Kyun. Choi. 최석균

jQuery 를 이용하여 페이스북 API 를 연동하기

우선 페이스북 API 를 사용하려면 페이스북에서 제공하는 앱을 생성해야 한다.
http://developers.facebook.com/docs/ 접속하여 앱을 생성한다.

아래의 소스는 로그인한 회원의 정보를 읽어오며, 포스트를 등록할 수 있는 기능의 소스이다.
그외 필요한 기능은 페이스북에서 제공하는 문서를 참조하면 쉽게 구현할 수 있다.

* 제가 최근 SNS 관련하여 개발을 하고 있습니다. 음... 상세한 설명까지는 힘들 것 같아요~
그래서 지우기는 아쉽고 해서 혹여나 도움이 될까하여 테스트로 만든 샘플 소스들을 마구잡이로 올려두고 있습니다.
설명이 부족하다고 해서 버럭하시지 말아주세요~

 자바스크립트 & HTML 소스

<html>
  <head>
  <title>jQuery Syaku Facebook API</title>

  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
  <script src="http://connect.facebook.net/ko_KR/all.js"></script>

  <script type="text/javascript">

    /**
     * jQuery Syaku Facebook API ver 1.0.0
     *
     * Copyright (c) Seok Kyun. Choi. 최석균
     * GNU Lesser General Public License
     * http://www.gnu.org/licenses/lgpl.html
     *
     * registered date 20111006
     * http://syaku.tistory.com
     */

    (function($) {

      $.sFacebook = {
        image_url : null,
        photo_id : null,
        me_uid : null,
        me_name : null,

        initialize : function(settings) {

          settings = jQuery.extend(true , {
            appId : '',
            cookie:true, 
            status:true,
            xfbml:true,
            image_url : 'http://graph.facebook.com/{image}/picture',
            me_photo_target : '#facebook-me-photo',
            me_name_target : '#facebook-me-name',
            facebook_close_target : '#facebook-close'

          }, settings);

          this.image_url = settings.image_url;
          this.me_photo_target = settings.me_photo_target;
          this.me_name_target = settings.me_name_target;
          this.facebook_close_target = settings.facebook_close_target;

          var obj = this;
          jQuery('body').append("<div id='fb-root'></div>");

          FB.init({ 
            appId : settings.appId,
            cookie : settings.cookie, 
            status : settings.status,
            xfbml : settings.xfbml
          });

          FB.Event.subscribe('auth.login', function (response) {
            // do something with response
            obj.reload();
          });

          FB.Event.subscribe('auth.logout', function (response) {
            // do something with response
            obj.reload();
          });

          obj.reload();
        },

        reload : function() {
          var obj = this;

          this.me_profile();
          FB.getLoginStatus(function (response) {
            
            if (response.session) {
              // logged in and connected user, someone you know
              jQuery(obj.facebook_close_target).show();
            } else {
              jQuery(obj.facebook_close_target).hide();
            }

          });
        },

        me_profile : function() {
          var obj = this;

          FB.getLoginStatus(function (response) {
            if (response.session) {
              FB.api('/me', function(user) {
                if(user != null) {
                  var image = obj.image_url.replace('{image}',user.id);
                  
                  obj.me_uid = user.id;
                  obj.me_name = user.name;

                  jQuery(obj.me_photo_target).attr("src",image);
                  jQuery(obj.me_name_target).text(obj.me_name);
                  
                }

              });

            } else {
              
              obj.me_uid = null;
              obj.me_name = null;
              jQuery(obj.me_photo_target).attr("src",'');
              jQuery(obj.me_name_target).empty();

            }

          });

        },

        login : function() {

          FB.getLoginStatus(function (response) {
            
            if (response.session) {
              obj.me_profile();
            } else {
              FB.login(function(response) { }, { perms:'user_website,email,offline_access,read_stream,publish_stream' });
            }

          });

        },

        logout : function() {
         FB.logout(function(response) { });
        },

        post_feed : function(target) {
          var text = jQuery(target).val();
          var text_count = new String(text); 
          if (text_count.length == 0) { alert("내용을 입력하세요."); jQuery(target).focus(); return; }

          var params = { 
            message : text,
            link : document.URL,
            name : document.title
          };

          FB.api('/me/feed', 'post', params, function(response) {
            if (!response || response.error) {
              alert('Error occured');
            } else {
              alert('Post ID: ' + response.id);
              document.reload();
            }
          });

        },

        select_user_name : function(user_id) {
          var query = FB.Data.query('select name, uid from user where uid={0}',user_id);
          query.wait(function(rows) {
            return rows[0].name;
          });
        }


      };

    })(jQuery);

  </script>

  </head>
    <body>
      <script type="text/javascript">
        jQuery(function() {
          
          jQuery.sFacebook.initialize({
            appId : '**************' // 페이스북 App Id 입력.
          });

        });

      </script>

      <input type="text" id="facebook-post-id" />

      <div><a href="javascript:jQuery.sFacebook.login();"><img src="facebook_32.png" /></a></div>
      <div>
      <span id="facebook-me-name"></span>
      <span id="facebook-close" style="display:none;"><a href="javascript:jQuery.sFacebook.logout();">연결끊기</a></span>
      </div>
      <div style="padding-top:5px;">
      <img src="" id="facebook-me-photo" width="50" height="50" />
      <textarea cols="0" rows="0" style="height:50px;width:500px;" id="sns-post-feed" ></textarea>
      <button type="button" onclick="jQuery.sFacebook.post_feed('#sns-post-feed');">글쓰기</button>
      </div>


    </body>
 </html>



posted syaku blog

Syaku Blog by Seok Kyun. Choi. 최석균.

http://syaku.tistory.com