본문 바로가기

Facebook

Facebook 번역 - 2. tutorial





삘과 의역으로 범벅된 장담하기 힘든 번역 2탄


원본 :  Canvas Tutorial 



 
Canvas Tutorial

이 문서는 여러분의 앱 페북에 올리고 페이스 북 크롬 내에서 실행하는 핵심 단계를 안내함.
 

  1. 당신의앱만들기 
  2. 응용프로그램 구성
  3. 권한부여
  4. Social Channels : Feed, Requests 와 Game stories
  5. 캔버스 성능
  6. 어도비 플래시 개발자를 위한 특별 고려사항
  7. 샘플 및 다음 단계

앱만들기

Developer App 를 방문하여 시작.
이전에 응용프로그램을 생성하지 않은 경우 응용프로그램(이하 앱)을 추가할것인지 묻는 메세지가 나타남.

이후 새로운 앱을 만들 수 있음.



페이스북에 앱을 만들기 위해선 당신의 페이스북 계정을 인증받아야 함.
계정인증에 대한 자세한 내용을 볼려면 여기를 클릭

앱구성

페이스북의 앱은 Canvas 페이지의 Canvas section에 로드 됨.
Canvas 는 말그대로 님의 앱을 실행하는 페이스북의 빈 캔버스임.
 HTML, 자바스크립트, CSS  구성된 당신의 앱이 포함되어있는 Canvas URL을 캔버스에 채워 제공한다.


사용자가 캔버스 페이지를 요청할때 우리는
 Canvas URL을 해당페이지의 iframe에 로드하여 표준페이스북 안에서 보여지게 된다.

예를 들어 http://www.example.com/canvas 에서 사용가능한 웹 앱이 있다고 가정하자.
이건 당신의 
Canvas URL 이다.

당신의 앱을 페이스북에 설정할때 당신은 캔버스페이지 이름을 
지정 해야하고 
그 이름은
https://apps.facebook.com/ 주소 뒤에 추가된다.

당신은 앱 네임스페이스 필드에 값을 입력하여 이 캔버스페이지 이름을 지정할 수 있다.

이 예제에서 우리는 캔버스 페이지이름으로 your_app 을 사용한다.
사용자가 브라우저에서 http://apps.facebook.com/your_app 으로 이동하면
그들은 페이스북내부에 로드된 http://www.example.com/canvas 컨텐츠를 볼 수 있다.

 
일단 페이스북 앱을 만들고 "App on Facebook(Facebook 캔버스앱)" 섹션을 선택한 뒤 캔버스와 보안 Canvas URL을 지정한다.
 


당신이 만든 앱은 페이스북의 context에 로드되기 때문에 사용자인터페이스를 디자인 할때 당신은 특정크기의 제약을 인식하고 있어야 한다.

당신은  Dev App 의 Advanced 탭에서  iframe 의 크기에 대한 설정을 관리 할 수 있다.


Canvas Width 

당신은 당신의 캔버스 폭을  760 고정픽셀을 가지는 기본설정인 "Fixed (760px)"  로 설정할 수 있다. 
당신은 또한 iframe 폭을 100%로 설정하는 의미인 "Fluid" 로 설정할 수 있다.
당신의 콘텐츠는 유저가 변화시킨 너비에 맞춰 왼쪽 정렬되어 채워진다. 

Canvas Height

높이는 "Fulid" 가 기본 설정이며 이는 iframe의 높이를 100%로 하고 컨텐츠 페이지의 높이를 초과하면 스크롤 막대를 보여주는걸 의미한다.

당신은 또한 "Settalbe" 로 높이를 설정 할 수 있다.

이 경우 높이는 기본인 800픽셀이다. 당신은 당신의 콘텐의 맞게 메서드를 호출하여 ifame의 높이를 변경 할 수있다. 

컨텐츠의 높이를 변화시킬때 적절하게 일치하도록 iframe의 높이를 조정하는 'Auto-resize' 기능을 활성화 시키기 위하여  FB.Canvas.setAutoResize()  메서드 또한 호출 할 수 있다.

이러한 메서드는 오직 Cannas Height를
 Settable  로 설정했을 때 가능하다.

당신의 앱 캔버스를 Fluid 로 어떻게 구현하는가 를 알려면 여기를 참고



권한부여

개인화된 사용자 경험을 창조하기 위해 페이스북은 사용자의 앱정보를 전송한다.

이정보는  base64url  로 인코딩된 JSON 개체를 포함한 signed_request 매개변수로 HTTP POST 를 방식을 통해
Canvas URL로 전달된다.

사용자가 처음 당신의 앱에 접속하면  signed_request 매개변수는 사용자의 제한된 정보만 포함하고 있다.
 

NameDescription
user A JSON array containing the locale string, country string and the age object (containing the min and max numbers of the age range) for the current user.
algorithm A JSON string containing the mechanism used to sign the request.
issued_at A JSON number containing the Unix timestamp when the request was signed.

기본적으로 해당앱에서 사용할 수 있는 모든 사용자 정보(사용자의 페이스북 id와 같은)에 접속하기 위해서는
사용자가 앱을 승인해야 한다.

우리는 페이스북의 앱의 승인을 위해 당신이  OAuth Dialog  를 사용하는것을 권장한다.

다음과 같은 URL로 사용자의 브라우저를 대화상자를 호출하는 주소로 보낼 수 있다.

(YOUR_APP_ID 와 YOUR_CANVAS_PAGE 를   Developer App  에서 찾아서 올바른 값으로 입력)

https://www.facebook.com/dialog/oauth?
     client_id=YOUR_APP_ID&redirect_uri=YOUR_CANVAS_PAGE
Canvas Auth

기본적으로 사용자에게  페이스북에서 기본적으로 사용할 정보에 접근하는 앱을 승인하도록 요청한다.
만약 당신의 앱이 기본정보보다 많은 것을 필요로 한다면 당신은 사용자에게 특정 권한을 요청해야 한다.
그것은 OAuth 대화요청 다음에  scope 매개변수를 추가하여 콤바로 구분한 목록을 넣어 실행할 수 있다.
다음예제는 사용자의 이메일 주소에 접근하고 뉴스패드를 요청하는 방법을 보여줌.


https://www.facebook.com/dialog/oauth?client_id=YOUR_APP_ID
     &redirect_uri=YOUR_CANVAS_PAGE&scope=email,read_stream

Canvas Perms

사용가능한 권한의 전체목록은 우리의  permissions reference 에 있다.
님의 앱이 요청한 권한 수와 그것을 승인한 유저의 수는 반비례 한다. 

원한는 권한의 수가 많을 경우 승인할 사용자는 낮아질 것이다.그러니  우리는 당신의 앱에서 필요한 권한만을 요청하는것을 권장한다.


만약 Don't allow 를 사용자가 누른다면 당신의 앱은 권한을 가질 수 없다.
OAuth 대화상자는 사용자의 브라우저를 redirect_uri 매개변수로 지정된 곳으로 에러 정보와 함께 이동시킨다. 

http://YOUR_CANVAS_PAGE?error_reason=user_denied&
     error=access_denied&error_description=The+user+denied+your+request.

만약 사용자가 승인(허가) 한다면 당신의 앱은 권한을 가진다.
OAuth 대화상자는 사용자의 브라우저를  redirect_uri 매개변수로 지정된 곳으로 이동시킨다.  
사용자가 님의 앱을 승인 하고나면  signed_request 매개변수는 후속요청에 다음의 정보를 포함한다.

NameDescription
user A JSON array containing the locale string, country string and the age object (containing the min and maxnumbers of the age range) for the current user.
algorithm A JSON string containing the mechanism used to sign the request.
issued_at A JSON number containing the Unix timestamp when the request was signed.
user_id A JSON string containing the Facebook user identifier (UID) of the current user.
oauth_token A JSON string that you can pass to the Graph API or the Legacy REST API.
expires A JSON number containing the Unix timestamp when the oauth_token expires.

아래의 php 예제는 signed_request 매개변수를 엑세스하고 사용자가 응용프로그램을 승인하라는 메세지를 표시하는 방법을 보여준다

<?php 

     $app_id = "YOUR_APP_ID";

     $canvas_page = "YOUR_CANVAS_PAGE_URL";

     $auth_url = "https://www.facebook.com/dialog/oauth?client_id=" 
            . $app_id . "&redirect_uri=" . urlencode($canvas_page);

     $signed_request = $_REQUEST["signed_request"];

     list($encoded_sig, $payload) = explode('.', $signed_request, 2); 

     $data = json_decode(base64_decode(strtr($payload, '-_', '+/')), true);

     if (empty($data["user_id"])) {
            echo("<script> top.location.href='" . $auth_url . "'</script>");
     } else {
            echo ("Welcome User: " . $data["user_id"]);
     } 
 ?>


당신은 우리의  
서명요청 레퍼런스 가이드로 서명을 확인하는 방법을 포함하여 signed_request 에대해 더 배울 수 있다.

JavaScript SDK  와 PHP SDK  같은 여러 SDK에서 인증 및 권한 부여하는건 누워서 떡먹기.


사용자가 앱을 승인한 후에는 프로필 정보 뿐만 아니라 친구데이터에에도 접속하여 
Graph API 사용 할 수 있다.

Social Channels

페이스북 플랫폼은 당신의 앱을 유저의 친구들과 공유하기 위한  여러가지 방법을 제공한다 .
우리는 이것을  Social Channels 이라 부른다. 당신의 앱은 사용자의 뉴스피드 직접 게시하기, 친구들에게 요청보내기나
자동채널등을 활용할 수 있다.

Feed

뉴스피드는 사용자가 페이스북에 로그인시 바로 표시되고 이것은 페이스북의 근본적인 사용자 경험을 만들어 낸다.
당신의 앱은  Feed Dialog 를 사용하여 사용자의 뉴스피드에 게시 할 수 있다.
다음예제는 페이지 내에서 이 대화 상자를 표시하는 방법을 보여줌.

<?php 

         $app_id = "YOUR_APP_ID";

         $canvas_page = "YOUR_CANVAS_PAGE_URL";

         $message = "Apps on Facebook.com are cool!";

         $feed_url = "https://www.facebook.com/dialog/feed?app_id=" 
                . $app_id . "&redirect_uri=" . urlencode($canvas_page)
                . "&message=" . $message;

         if (empty($_REQUEST["post_id"])) {
            echo("<script> top.location.href='" . $feed_url . "'</script>");
         } else {
            echo ("Feed Post Id: " . $_REQUEST["post_id"]);
         }
?>

Canvas Perms

Requests

요청은 사용자가 앱에 그들의 친구를 초대하거나 선물을 수락하는 구체적인 조치를 취하거나 작업을 완료할 수 있도록
할성화 하는 좋은 방법이다.
당신의 앱은   Request Dialog 를 이용하여 요청을 보낼 수 있다.

다음 예제는 캔버스 페이지 내에서 이 대화 상자를 표시하는 방법을 보여준다.

<?php 

         $app_id = "YOUR_APP_ID";

         $canvas_page = "YOUR_CANVAS_PAGE_URL";

         $message = "Would you like to join me in this great app?";

         $requests_url = "https://www.facebook.com/dialog/apprequests?app_id=" 
                . $app_id . "&redirect_uri=" . urlencode($canvas_page)
                . "&message=" . $message;

         if (empty($_REQUEST["request_ids"])) {
            echo("<script> top.location.href='" . $requests_url . "'</script>");
         } else {
            echo "Request Ids: ";
            print_r($_REQUEST["request_ids"]);
         }
?>


Canvas Perms


만약 당신이 앱에서 직접 유저에게 요청을 보내는것을 원하는 경우 

당신은 User Graph object 의 apprequest에 연결하여 요청을 게시한다.

 


<?php 

  $app_id = YOUR_APP_ID;
  $app_secret = YOUR_APP_SECRET;

  $token_url = "https://graph.facebook.com/oauth/access_token?" .
    "client_id=" . $app_id .
    "&client_secret=" . $app_secret .
    "&grant_type=client_credentials";

  $app_access_token = file_get_contents($token_url);

  $user_id = THE_CURRENT_USER_ID;

  $apprequest_url ="https://graph.facebook.com/" .
    $user_id .
    "/apprequests?message='INSERT_UT8_STRING_MSG'" . 
    "&data='INSERT_STRING_DATA'&"  .   
    $app_access_token . "&method=post";

  $result = file_get_contents($apprequest_url);
  echo("App Request sent?", $result);
?>


 
message 매개변수는 요청에 대한 설명하는 UTF-8 문자열이다.

data  매개변수는 앱이 요청을 처리하기 위하여 관련데이터를 저장하는 데 사용할 수 있는 문자열이다. 

발송되면 사용자가 받은 새요청은 당신의 앱 bookmark  에 카운터 되어 보여지고
적당한 Dashboard. 다음에 카운터가 증가한다. (뭔소리지)
(Once sent, new requests a user has received are visible as a counter on your application's bookmark and it also increments the counter next to the appropriate Dashboard.)

만약 여러사용자에게 앱에서 생성된 요청을 보내고 싶다면
 ids 매개변수(Graph API 의 Selection 를 참고) 를 사용하여 쉼표로 구분된 사용자의  ids를 입력하면 된다.

POST https://graph.facebook.com/apprequests?ids=user_id1,user_id2
     &message=Hello&access_token=APP ACCESS TOKEN

우리의 채널에 대한 자세한 내용은  Social Channels 을 참고

Publishing game stories


게임 개발자들은 게임을 좀더 흥미진진하게 만들기 위해 유저의 업적, 유저의친구들에게 점수 전달  같은 게임 스토리를 게시할 수 있다.

scores  와  achievements.  를 게시하는 방법을 좀 더 배워보자
넌   게임의 점수와 성취도를 어떻게 게시하면 되나염 에서 좀 더 상세한 내용을 볼 수 있다.

다음은 성취를 설정하는데 있어 사용할 수 있는 간단한 html 코드이다.

   <html xmlns="http://www.w3.org/1999/xhtml" xmlns:og="http://ogp.me/ns#">
     <head>
       <title>ACHIEVEMENT_TITLE
       <meta property="og:type" content="game.achievement"/>
       <meta property="og:url" content="URL_FOR_THIS_PAGE"/>
       <meta property="og:title" content="ACHIEVEMENT_TITLE"/>
       <meta property="og:description" content="ACHIEVEMENT_DESCRIPTON"/>
       <meta property="og:image" content="URL_FOR_ACHIEVEMENT_IMAGE"/>
       <meta property="game:points" content="POINTS_FOR_ACHIEVEMENT"/>
       <meta property="fb:app_id" content="YOUR_APP_ID"/>
     </head>
     <body>
      Promotional content for the Achievement.  
     This is the landing page where a user will be directed after
     clicking on the achievement story.
     </body>
  </html>

아래 코드로 당신의 앱을 위해 상위 달성을 등록하고

사용자를 위해 발행뿐만 아니라 점수를 게시할 수 있다.

 <?php
   $app_id = 'YOUR_APP_ID';
   $app_secret = 'YOUR_APP_SECRET';
   $app_url = 'YOUR_APP_URL';

  // The Achievement URL
  $achievement = 'YOUR_ACHIEVEMENT_URL';
  $achievement_display_order = 1;

  // The Score
  $score = 'YOUR_SCORE';

  // Authenticate the user
  session_start();
  if(isset($_REQUEST["code"])) {
     $code = $_REQUEST["code"];
  }

  if(empty($code) && !isset($_REQUEST['error'])) {
    $_SESSION['state'] = md5(uniqid(rand(), TRUE)); //CSRF protection
    $dialog_url = 'https://www.facebook.com/dialog/oauth?' 
      . 'client_id=' . $app_id
      . '&redirect_uri=' . urlencode($app_url)
      . '&state=' . $_SESSION['state']
      . '&scope=publish_actions';

    print('');
    exit;
  } else if(isset($_REQUEST['error'])) { // The user did not authorize the app
    print($_REQUEST['error_description']);
    exit;
  };

  // Get the User ID
  $signed_request = parse_signed_request($_POST['signed_request'], $app_secret);
  $uid = $signed_request['user_id'];

  // Get an App Access Token
  $token_url = 'https://graph.facebook.com/oauth/access_token?'
    . 'client_id=' . $app_id
    . '&client_secret=' . $app_secret
    . '&grant_type=client_credentials';

  $token_response = file_get_contents($token_url);
  $params = null;
  parse_str($token_response, $params);
  $app_access_token = $params['access_token'];
  
  // Register an Achievement for the app
  print('Register Achievement:
'); $achievement_registration_URL = 'https://graph.facebook.com/' . $app_id . '/achievements'; $display_order = '1'; $achievement_registration_result = https_post($achievement_registration_URL, 'achievement=' . $achievement . '&display_order=' . $achievement_display_order . '&access_token=' . $app_access_token ); print('

'); // POST a user achievement print('Publish a User Achievement
'); $achievement_URL = 'https://graph.facebook.com/' . $uid . '/achievements'; $achievement_result = https_post($achievement_URL, 'achievement=' . $achievement . '&access_token=' . $app_access_token ); print('

'); // POST a user score print('Publish a User Score
'); $score_URL = 'https://graph.facebook.com/' . $uid . '/scores'; $score_result = https_post($score_URL, 'score=' . $score . '&access_token=' . $app_access_token ); print('

'); function https_post($uri, $postdata) { $ch = curl_init($uri); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata); $result = curl_exec($ch); curl_close($ch); return $result; } function parse_signed_request($signed_request, $secret) { list($encoded_sig, $payload) = explode('.', $signed_request, 2); // decode the data $sig = base64_url_decode($encoded_sig); $data = json_decode(base64_url_decode($payload), true); if (strtoupper($data['algorithm']) !== 'HMAC-SHA256') { error_log('Unknown algorithm. Expected HMAC-SHA256'); return null; } // check sig $expected_sig = hash_hmac('sha256', $payload, $secret, $raw = true); if ($sig !== $expected_sig) { error_log('Bad Signed JSON signature!'); return null; } return $data; } function base64_url_decode($input) { return base64_decode(strtr($input, '-_', '+/')); } ?>

Canvas Performance

페이스북은 너네 캔버스페이지 성능을 올리기 위해 이것저것 노력함.
하지만 너님은 명시적으로 prefetched 해야하는 리소스를 지정하여 페이지 로딩시간을 향상 시킬 수 있다.
최상의 결과를 얻을려면 당신의 앱의 실행과 관련된 가장 큰 리소스를 지정하는걸 우리는 권장한다(CSS,JS,SWF)
 
prefetched 되는 자원을 확인하려면 당신은 Graph API  Applicationobject 에 정적  staticresources  연결을 검색 할 수 있다.

 당신은  Javascript SDK 를 포함하여 각 페이지로드에서 
FB.Canvas.Prefetcher.addStaticResource 와 FB.Canvas.Prefetcher.setCollectionMode 메소드들을
 호출하여   prefetched 되는 영향을 .... ㅅㅂ총체적 난관... 이부분은 패스 



어도비 플래시 개발자를 위한 특별 고려사항

캔버스안에 어도비 플래시 기반의 앱을 만드는 개발자들은, wmode 를 opaque 로 설정하는 것을 권장한다.

<object type="application/x-shockwave-flash" data="http://roflgamez.com/emote.swf" 
    width="640" height="360">
  <param name="wmode" value="opaque">
  ...
</object>


이래야 채팅탭 알림 및 티켓 기타등등 페이스북 대화상자를 플래시 컨텐츠 위에 제대로 표시할 수 있다.

기타모드 (window , direct ,gpu )는 우리에게 당신의 플래시 오브젝트를 숨기길 요구한다.
( Dialogs, Notifications, Chat tabs, and Ticker Flyouts 를 사용할때)
이것은 사용자에게 불쾌하거나 모니터를 박살시키는 짜증을 유발 시킬 수 있다.

우린 몇몇의 앱이 높은 프레임레이트를 위해 wmode를 oqaque 로 설정할 수 없는 경우를 이해한다.
만약 당신의 앱이 window 나 direct 를 wmode로 필요로 한다면
그것은(아마 플래시오브젝트) 각종 페이스북 대화상자를 열때 자동으로 숨겨진다.

당신의 앱을 런칭하기 전에 이기능들이 제대로 돌아가는 지 확인하지 않으면 망할 수 있음.
만족스러운 사용자 경험과  커스터마이징을 원하는 개발자를 위해 자바sdk는 매개변수 hideFlashCallback 를 지원한다.

이것은 개발자들이 자신의 플래시 컨텐츠가 숨겨질때마다 그리고 대화상자 및 기타등등이 보여질대마다
호출되는 자바스크립트 함수를 정의 할수 있도록 하고
플래시 컨텐츠는 FB.Canvas.hideFlashElement 와 FB.Canvas.showFlashElement를 통해수동으로 숨겨지고 표시된다 

샘플 , 다음 스텝  


앱 구축을 시작하는데 도움이 되는 진짜배기 예제를 찾고 있다면 Run with Friends 샘플 앱을 참고해라
이샘플은 페이스북 플래폼의 대부분의 기능과 Real-time Updates. 같은 일부 고급기능도 사용한다.


참고 
 Social Plugins
 
Graph API