DevEnjoy

One Step Closer

facebook

facebook sdk 회원정보 연동 예제

2014년 2월 5일 by YongPwi 18 Comments

일전에 facebook sdk 연동 작업할때 작성해둔 예제인데,,,

결국 제품 오픈은 올해로 미뤄져서 묻혀버린 코드가,,,

오늘 지인과 이야기 하다가 필요하단 이야기를 듣고 문뜩 생각나서 정리해둔다,,,

작년 꽤나 삽질했던 기억이 있는데,,,지금도 동작할지는 모르겠다,,,

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
    <script language="javascript">
        // 페이스북 SDK 초기화
        window.fbAsyncInit = function () {
            FB.init({
                appId: ''    // Website with Facebook Login 사이트 : 일단 test 용으로 용퓌 계정상에서 app 생성
                , status: true   // check login status
                , cookie: true   // enable cookies to allow the server to access the session
                , xfbml: true    // parse XFBML
                //,oauth: true
            });
        };

        // 페이스북 SDK(js) 로딩 (페이지 로딩 속도 향상을 위해 사용)
        (function (d) {
            var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0];
            if (d.getElementById(id)) {
                return;
            }
            js = d.createElement('script');
            js.id = id;
            js.async = true;
            //js.src = "//connect.facebook.net/en_US/all.js";
            js.src = "http://connect.facebook.net/ko_KR/all.js";
            ref.parentNode.insertBefore(js, ref);
        }(document));

        // 페이스북 계정으로 회원 가입
        function facebookRegist() {
            // 페이스북 로그인 상태 체크
            FB.getLoginStatus(function (response) {

                if (response.status == "connected") {
                    // 페이스북 로그인 YES! and 앱 허가 YES!
                    handleFacebookRegist(response);
                } else if (response.status == "not_authorized") {
                    // 페이스북 로그인 YES! but 앱 허가 NO!
                    FB.login(function (response) {
                                handleFacebookRegist(response);
                            },
                            {scope: 'publish_stream, email, user_birthday, user_likes, publish_actions, read_stream'});
                } else {    // 페이스북 로그아웃 상태.
                    FB.login(function (response) {
                                handleFacebookRegist(response);
                            },
                            {scope: 'publish_stream, email, user_birthday, user_likes, publish_actions, read_stream'});
                }
            });
        }

        // 회원가입 핸들러
        function handleFacebookRegist(response) {

            var accessToken = response.authResponse.accessToken;
            var userId, userName, fbId, userBirth;

            FB.api('/me', function (user) {
                userId = user.email;    // 페이스북 email
                userName = user.name;   // 페이스북 name
                fbId = user.id;         // 페이스북 id
                userBirth = user.birthday;  // 페이스북 생일 : mm/dd/yyyy
                alert(userId);
                alert(userName);
                alert(userBirth);
                $('input[name=fbAccessToken]').val(accessToken);
                return;
                $.ajax({
                    type: "post",
                    url: "ajax 로 호출할 url",
                    dataType: "jsonp",
                    jsonp: "callback",
                    data: {
                        userId: userId
                    },
                    beforeSend: function () {
                        $('#ajax_load_indicator').fadeIn('fast');
                    },
                    success: function (data) {
                        if (data.result == true) {
                            alert("이미 가입이 되어있습니다.");
                            return;
                        } else {
                            if (confirm("Facebook 계정으로 가입하시겠습니까?\n\rFacebook 계정으로 가입시 추가정보를 입력하셔야 합니다.")) {
                                //var $form = $("<form></form>");
                                //$form.attr("action","페이스북에서 받은 정보를 post로 넘길 url");
                                //$form.attr("method","post");
                                //$form.appendTo("body");
                                //$form.append("<input type="hidden" name="userName" value=""+ userName +"">");
                                //$form.append("<input type="hidden" name="userId" value=""+ userId +"">");
                                //$form.append("<input type="hidden" name="fbId" value=""+ fbId +"">");
                                //$form.append("<input type="hidden" name="userBirth" value=""+ userBirth +"">");    // mm/dd/yyyy 형식으로 받음.(짤라서 쓰던가 하믄 됨.)
                                //$form.submit();
                            }
                            return;
                        }
                    },
                    error: function (data, status, err) {
                        alert("서버와의 통신이 실패했습니다.");
                        alert(err)
                        return;
                    },
                    complete: function () {
                        $('#ajax_load_indicator').fadeOut();
                    }
                });
            });
        }

        function fbNesFeedPost(){
            //자동 포스팅 시키기
            FB.api('/me/feed','post',
                    {
                        //method: 'feed',  //feed 로 올림
                        //name: '테스트',  // 링크가 걸리는 이름
                        //link: '클릭하면 넘어갈 주소',  // 링크 주소
                        //picture: '사진 주소',  // 사진
                        //caption: 'caption',  //
                        //description: 'description',  // 컨텐츠
                        message: '연동테스트' // 텍스트박스 안의 글자
                    },
                    function(response){
                        if(!response || response.error){
                            FB.login(function(response) {  // 자동 글 등록 실패시 권한 부여하는 창을 띄움
                                        Log.info('FB.login callback', response);
                                        if (response.status === 'connected') {Log.info('User is logged in');}
                                        else {Log.info('User is logged out');}
                                    },
                                    {scope: 'read_stream,publish_stream'}
                            );
                            //alert("facebook 권한 허가를 누르신 후 \n다시 눌러주십시오.");
                        }else{
                            alert("글 등록 성공");  //자동 글 등록 성공시
                        }
                    });
        }


    </script>
</head>
<body>
<form name="fbForm" method="post">
    <input type="text" name="fbAccessToken" value="">
    <input type="button" value="Facebook 연동" onclick="facebookRegist();">
    <input type="button" value="Facebook newsfeed연동" onclick="fbNesFeedPost();">
    <input type="text" name="message">
</form>
</body>
</html>
Posted in: Javascript, Programing Tagged: facebook

Calendar

4월 2021
일 월 화 수 목 금 토
« 4월    
 123
45678910
11121314151617
18192021222324
252627282930  

Recent Posts

  • ubuntu bastion 설정
  • Spring Boot properties 암호화
  • Git Repository Bitbucket과 Issue Tracker Redmine 연동 설정
  • Spring Security 동일 session 제어
  • Spring @Mock, @Mockbean, @InjectMock

Recent Comments

  • pzotov (Ubuntu 14.04에서 Sonarqube 6.7.1 service 등록)
  • cours de theatre paris (AWS ELB와 Auto Scaling 연동, nginx)
  • bayern munich (IntelliJ EAP Font rendering)
  • camiseta del chelsea (OS X에서 APP 아이콘 변경)
  • cheap football shirts replica (jQuery Ajax에서 json Array 직렬화)

Copyright © [the-year] [site-link].

Powered by [wp-link] and [theme-link].