자바스크립트로 fb API연동하여 로그인하기



그래프 API 탐색기 이용하기

url : https://developers.facebook.com/tools-and-support 



appid 에서 가져올 권한 선택추가 선택


default : id, name 

추가로 가져올 정보 : email






위 api 탐색기로 선 테스트 후 

아래처럼 javascript로 코드작성.

참고url : https://developers.facebook.com/docs/facebook-login/web#logindialog



<<html code>>


<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8" />
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <title>Page Title</title>
  <meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<!--
reference to : https://developers.facebook.com/tools-and-support
-->
<script>
window.fbAsyncInit = function() {
FB.init({
appId : '2028791704043595',
     cookie : true, // enable cookies to allow the server to access the session
xfbml : true, // parse social plugins on this page
version : 'v3.0' // use graph api version 2.8
});
    FB.getLoginStatus(function(response) {
statusChangeCallback(response);
});
};

(function(d, s, id){
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) {return;}
js = d.createElement(s); js.id = id;
js.src = "https://connect.facebook.net/en_US/sdk.js";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));

   /*
     콜백에 제공되는 response 개체에는 다음과 같은 여러 필드가 포함되어 있습니다.
    {
        status: 'connected',
        authResponse: {
            accessToken: '...',
            expiresIn:'...',
            signedRequest:'...',
            userID:'...'
        }
    }코드 복사
    status는 앱 사용자의 로그인 상태를 지정합니다. 상태는 다음 중 하나일 수 있습니다.
    connected - 사용자가 Facebook에 로그인하고 앱에 로그인했습니다.
    not_authorized - 사용자가 Facebook에는 로그인했지만 앱에는 로그인하지 않았습니다.
    unknown - 사용자가 Facebook에 로그인하지 않았으므로 사용자가 앱에 로그인했거나 FB.logout()이 호출되었는지 알 수 없어,
Facebook에 연결할 수 없습니다.
    connected 상태인 경우 authResponse가 포함되며 다음과 같이 구성되어 있습니다.
    accessToken - 앱 사용자의 액세스 토큰이 포함되어 있습니다.
    expiresIn - 토큰이 만료되어 갱신해야 하는 UNIX 시간을 표시합니다.
    signedRequest - 앱 사용자에 대한 정보를 포함하는 서명된 매개변수입니다.
    userID - 앱 사용자의 ID입니다.
    앱에서 앱 사용자의 로그인 상태를 알게 되면 다음 중 하나를 수행할 수 있습니다.
    사용자가 Facebook과 앱에 로그인한 경우 앱의 로그인된 환경으로 리디렉션됩니다.
    사용자가 앱에 로그인하지 않았거나 Facebook에 로그인하지 않은 경우 FB.login()을 사용하여 로그인 대화 상자에 메시지를
표시하거나 로그인 버튼을 표시합니다.
        */
   function statusChangeCallback(response) {
    
      console.log('statusChangeCallback');

      if (response.status === 'connected') {
        console.log(response.authResponse.accessToken);
        // Logged into your app and Facebook.
        testAPI();
      } else if (response.status === 'not_authorized') {
        document.getElementById('status').innerHTML = 'Please log ' + 'into this app.';
      } else {
        document.getElementById('status').innerHTML = 'Please log ' + 'into Facebook.';
      }

  }

function checkLoginState() {
FB.getLoginStatus(function(response) {
statusChangeCallback(response);
});
}
  
function testAPI() {
  console.log('Welcome! Fetching your information.... ');
  FB.api(
    '/me',
    {"fields":"id,name,email"},
    function(response) {
       // Insert your code here
      console.log('Successful login for: ' + response.name);

      document.getElementById('status').innerHTML = JSON.stringify(response);
    }
  );
}

function fblogout(){

  FB.logout(function(response) {
    window.location.reload();
  });
}

</script>

<fb:login-button
scope="public_profile,email"
onlogin="checkLoginState();">
</fb:login-button>

<input type="button" onclick="javascript:fblogout();" value ="로그아웃" />
<div id="status"/>

</body>
</html>


로그인페이지>>


로그인후 fb의 개인정보 받아 display



로그인은 잘 되나, 로그아웃은 아래와 같은 에러내용으로 console log를 찍고 로그아웃이 안되고 있음. 

유투브 동영상등 찾아보고 진행했지만 해결못함.


Refused to display 'https://www.facebook.com/home.php' in a frame because it set 'X-Frame-Options' to 'deny'.


'프로그래밍 > PHP' 카테고리의 다른 글

curl kakao open api사용하기  (0) 2018.08.05
php CURL 사용하기  (0) 2018.07.31
php 패스워드 암호화 bcript  (0) 2018.05.02
unlink(=delete) 메소드 이용하기  (0) 2018.04.22
directory entry 읽어 파일리스트업  (0) 2018.04.20

"H.I." : a Japanese friend who lives in Osaka. 



In this morning, I talked with "H.I." about daily lives using Facebook video messenger.

It’s the first time to use this video messenger.

We talked about these days events like ‘Cherry blossoms festivals’ and ‘Learning other languages’.

"H.I." loves to study Korean and talks with Korean people using Korean but there are not enough chances.

I suggest ‘Phone Speaking’ to him. We will talk via the internet protocol video once a week.

We can share languages such as English, Korean, Japanese.

OK, let’s try. How about Japanese? 

Do not be greedy!

'other Language > english essay' 카테고리의 다른 글

english dialogue scripts  (0) 2018.03.28

+ Recent posts