페이스북

웹페이지 페이스북 API 연동하기(3)

p-a-r-k 2014. 10. 22. 12:00
반응형

1_에서는 SDK를 로드하는법.

2_에서는 페이스북 앱생성 및 설정하는 부분.

3_에서는 초기화 후 페이스북 로그인하여 사용자의 정보를 알아오는 부분.


순서.

1.window.fbAsyncInit에 함수할당
2. SDK로드 완료
3.window.fbAsyncInit 호출
4. FB.init() 실행


//앱 아이디
var runAppID = "1000000000000";

function facebookReady() {
	 FB.init({
		appId: runAppID,
		status   : true,
		cookie   : true, // enable cookies to allow server to access session,
		xfbml    : true,
		oauth    : true, // enable OAuth 2.0
		version  : 'v2.0'
	});
}

$(document).ready(function(){
	if (window.FB) facebookReady();
	else window.fbAsyncInit = facebookReady;
});

소스는 이런식이다. 물론 이게 정석소스X
로드하는 방법은 여러가지가 있으니 편한대로.

이제 init이 되었으니 api를 사용할 수 있게됨. 버튼을하나 만들어서 로그인처리와 사용자 정보출력.

SCRIPT :
<script type="text/javascript">
	function fnLogChk(){
		FB.getLoginStatus(function(response) {
			if (response.status === 'connected') {
			  saveSession();
			}else{
				FB.login(function(r){
				  if (r.status == "connected"){
					 saveSession();
				  }
				});
			}
		});
	}

	function saveSession(){
		var f = document.form1;

		FB.api(
		'/me?fields=' + encodeURIComponent('id,name,permissions.limit(100)'),
		function(response) {            
			f.USR_ID.value = response.id;
			f.USR_NAME.value = response.name;
		});
	}
</script>

HTML : 
<form name="form1">
	<input type="text" name="USR_ID">
	<br>
	<input type="text" name="USR_NAME">
</form>

<button onClick="fnLogChk();">로그인</button>

단, 등록한 앱의 설정에서의 도메인과 파일 경로가 일치하지 않으면, 아래와같은 에러.
입력하신 URL은 해당 앱에서 허용되지 않습니다.: One or more of the given URLs is not allowed by the App's settings.
It must match the Website URL or Canvas URL, or the domain must be a subdomain of one of the App's domains.


설정에 맞게 제대로 했다면 로그인 후, 정보가 출력.



반응형