이번 포스팅은 현재 국내에서 널리 쓰이고 있는 SNS 매체들(페이스북, 트위터, 다음요즘, 미투데이)에 대한 OAuth 인증 처리 및 글쓰기에 대한 내용으로, 우선 그 첫 번째 JSP를 통한 페이스북과의 연동을 다룹니다.
포함되는 내용은 다음과 같습니다.
1. 페이스북 OAuth 인증 처리
2. 페이스북에 포스팅 하기
3. 페이스북의 친구 목록 얻어오기
먼저 페이스북에 앱을 등록하고 앱키와 앱 시크릿 코드를 발급받습니다.
페이스북 앱 등록 URL : https://developers.facebook.com/apps
등록한 앱의 내용은 아래 그림과 같으며, 페이지 상단에서 App ID와 App Secret를 확인할 수 있습니다.
또한, 페이스북과 JSP를 통해 연동할 것이므로 웹사이트를 체크하고 도메인을 입력하였습니다.
1. 페이스북 OAuth 인증 처리
앱 등록을 완료하였으면, 아래와 같이 간단한 JSP 페이지를 작성합니다. (파일명 : facebook_step1.jsp)
<%@ page language="java" contentType="text/html; charset=EUC-KR" pageEncoding="EUC-KR"%> <% String appKey = "your app key"; String appSecret = "your app secret"; String url = "http://www.facebook.com/dialog/oauth?client_id="+ appKey+"&redirect_uri=http://www.hellowd.com/snslink/facebook_step2.jsp&scope=publish_stream,offline_access"; %> <!DOCTYPE html> <html lang="ko"> <head> <meta http-equiv="Content-Type" content="text/html; charset=EUC-KR"> <title>facebook</title> <script type="text/javascript"> function go() { window.location.href = '<%=url%>' } </script> </head> <body> <a href="#" onclick="go();">페이스북 OAuth 인증 시작 하기</a> </body> </html>
위 JSP 페이지를 통해 페이스북 OAuth 인증을 시작하면, 페이스북 로그인 다이얼로그로 이동하게되며 로그인 완료 후 앱의 접근을 수락하게할 수 있습니다.
페이스북 로그인 다이얼로그를 띄우는데 몇가지 사용된 몇가지 파라미터는 다음과 같습니다.
- client_id : 페이스북 앱키를 지정합니다.
- redirect_uri : OAuth 인증 완료 및 앱 접근 수락 후 호출되는 콜백 URL.
- scope : 페이스북 앱에서 사용자 계정으로의 접근권한을 명시.
그외 scope에 대한 자세한 내용은 아래 링크를 통해 확인할 수 있습니다.
* https://developers.facebook.com/docs/authentication/permissions/
다음으로 OAuth 인증 완료 및 앱 접근 수락 후 호출되는 콜백 URL 페이지 facebook_step2.jsp는 다음과 같습니다.
<%@ page language="java" contentType="text/html; charset=EUC-KR" pageEncoding="EUC-KR"%> <%@ page import="org.apache.commons.lang3.StringUtils"%> <%@ page import="org.apache.http.impl.client.BasicResponseHandler"%> <%@ page import="org.apache.http.impl.client.DefaultHttpClient"%> <%@ page import="org.apache.http.client.methods.HttpGet"%> <% String appKey = "your app key"; String appSecret = "your app secret";
String code = request.getParameter("code"); String errorReason = request.getParameter("error_reason"); String error = request.getParameter("error"); String errorDescription = request.getParameter("error_description"); String accesstoken = ""; String result = ""; if( StringUtils.isNotEmpty(code) ) { HttpGet get = new HttpGet("https://graph.facebook.com/oauth/access_token"+ "?client_id="+appKey+ "&client_secret="+appSecret+ "&redirect_uri=http://www.hellowd.com/snslink/facebook_step2.jsp" + "&code="+code); DefaultHttpClient http = new DefaultHttpClient(); result = http.execute(get, new BasicResponseHandler()); accesstoken = result.substring(result.indexOf("=")+1); } %> <!DOCTYPE html> <html lang="ko"> <head> <meta http-equiv="Content-Type" content="text/html; charset=EUC-KR"> <title>facebook</title> </head> <body> access token : <%= accesstoken %> </body> </html>
facebook_step1.jsp를 거쳐 콜백URL인 facebook_step2.jsp가 호출되면 페이스북 앱의 검증 값인 code가 넘어오게 됩니다. 이 코드를 사용하여 페이스북으로 access token를 요청하게 됩니다.
주의할 점은 앞서 facebook_step1.jsp에서 사용 된 redirect_uri를 동일하게 지정해야 하며, 값이 다르면 오류가 발생하게 됩니다.
위 과정을 마치면 페이스북의 다양한 정보에 접근가능한 access token을 획득할 수 있습니다.
페이스북 인증에 관한 다양한 정보는 아래 링크를 통해 확인할 수 있습니다.
* https://developers.facebook.com/docs/authentication/server-side/
2. 페이스북 담벼락에 포스팅 하기
1번 과정에서 얻은 access token을 가지고 사용자 담벼락에 글쓰기 기능을 수행할 수 있습니다.
과정을 좀더 쉽게 처리하기 위해 페이스북 API를 wrapping한 JAVA 오픈소스 도구 restfb를 사용하도록 하겠습니다.
restfb : http://restfb.com/
restfb를 사용하면 페이스북의 다양한 API를 보다 편리하게 사용할 수 있습니다. 다음 예제 코드는 페이스북 담벼락으로 링크와 이미지가 포함된 게시글을 남기는 기능을 수행합니다. (accesstoken 은 위 예제를 통해 얻은 값을 사용합니다.)
<%@ page language="java" contentType="text/html; charset=EUC-KR" pageEncoding="EUC-KR"%> <%@ page import="com.restfb.exception.FacebookOAuthException"%> <%@ page import="com.restfb.Parameter"%> <%@ page import="com.restfb.types.FacebookType"%> <%@ page import="com.restfb.DefaultFacebookClient"%> <% String accesstoken = "your access token"; DefaultFacebookClient fbClient = new DefaultFacebookClient(accesstoken); FacebookType publishMessageResponse = null; try { publishMessageResponse = fbClient.publish("me/feed", FacebookType.class, Parameter.with("message", "담벼락 포스팅 내용을 입력합니다."), Parameter.with("link", "http://www.mtong.co.kr"), Parameter.with("picture", "http://www.mtong.co.kr/files/product_spread/18.lyb1495.1327003470570.jpg"), Parameter.with("type", "link"), Parameter.with("name", "링크이름입니다."), Parameter.with("caption", "caption 입니다."), Parameter.with("description", "description 입니다.")); } catch(FacebookOAuthException e) { //error occur!! } %> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=EUC-KR"> <title>facebook</title> </head> <body> Publish ID : <%=publishMessageResponse.getId() %> </body> </html>
위 코드가 실행되면 아래 그림과 같이 메세지가 페이스북 담벼락에 포스팅 된 것을 확인할 수 있습니다.
3. 페이스북 친구 목록 얻어오기
2번 과정과 마찬가지로 restfb를 사용해 친구목록을 손쉽게 얻어올 수 있습니다.
<%@ page language="java" contentType="text/html; charset=EUC-KR" pageEncoding="EUC-KR"%> <%@ page import="com.restfb.exception.FacebookOAuthException"%> <%@ page import="com.restfb.Parameter"%> <%@ page import="com.restfb.types.FacebookType"%> <%@ page import="com.restfb.DefaultFacebookClient"%> <%@ page import="java.util.List"%> <%@ page import="com.restfb.types.User"%> <% String accesstoken = "your access token";
DefaultFacebookClient fbClient = new DefaultFacebookClient(accesstoken); List<User> friends = null; try { friends = fbClient.fetchConnection("me/friends", User.class).getData(); } catch(FacebookOAuthException e) { //error occur!! } %> <!DOCTYPE html> <html lang="ko"> <head> <meta http-equiv="Content-Type" content="text/html; charset=EUC-KR"> <title>facebook</title> </head> <body> 친구의 수 : <%=friends.size()%> </body> </html>
페이스북 연동에 대한 포스팅은 여기까지며, 다음에는 JSP를 통한 트위터 연동을 다뤄보겠습니다.
[SNS 서비스 연동하기 시리즈 1] 페이스북
[SNS 서비스 연동하기 시리즈 2] 트위터
[SNS 서비스 연동하기 시리즈 3] 다음요즘
[SNS 서비스 연동하기 시리즈 4] 미투데이
'프로그래밍 > WEB' 카테고리의 다른 글
| [SNS 서비스 연동하기 시리즈 1] 페이스북 (0) | 2012/03/29 |
|---|---|
| Google Maps JavaScript API 사용법 (0) | 2012/03/20 |
