복붙노트

[RUBY-ON-RAILS] 사용자가 페이지와 쇼의 콘텐츠를 좋아하는 경우 페이스 북은 어떻게 확인합니까?

RUBY-ON-RAILS

사용자가 페이지와 쇼의 콘텐츠를 좋아하는 경우 페이스 북은 어떻게 확인합니까?

나는 페이스 북 iframe이 응용 프로그램을 만들려고하고 있습니다. 응용 프로그램은 먼저 이미지를 표시해야하며, 사용자가 페이지를 좋아하는 경우에, 그는 일부 콘텐츠에 대한 액세스 권한을 얻을 것이다.

그래서 저는 제가 페이스 북 페소 SDK를 사용할 수 없습니다의 RoR을 사용합니다.

사용자가 페이지를 좋아하지 않은 경우 여기 내 iframe이 HTML은 다음과 같습니다

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<link rel="stylesheet" type="text/css" href="style.css" />
<style type="text/css">
body {
width:520px;
margin:0; padding:0; border:0;
font-family: verdana;
background:url(repeat.png) repeat;
margin-bottom:10px;
}
p, h1 {width:450px; margin-left:50px; color:#FFF;}
p {font-size:11px;}
</style>
<meta http-equiv="Content-Type" content="text/html;
charset=iso-8859-1" />
</head>
<body>
<div id="container">
<img src="welcome.png" alt="Frontimg">
</div>

그리고, 사용자가 페이지를 좋아 한 경우 :

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<link rel="stylesheet" type="text/css" href="style.css" />
<style type="text/css">
body {
width:520px;
margin:0; padding:0; border:0;
font-family: verdana;
background:url(repeat.png) repeat;
margin-bottom:10px;
}
p, h1 {width:450px; margin-left:50px; color:#FFF;}
p {font-size:11px;}
</style>
<meta http-equiv="Content-Type" content="text/html;
charset=iso-8859-1" />
</head>
<body>
<div id="container">
<img src="member.png" alt="Frontimg">
<p>You liked this page</p>

해결법

  1. ==============================

    1.UPDATE 21/11/2012 @ALL : 나는 그것이 잘 작동하고 크리스 야곱과 FB 모범 사례에서 계정 발언에 소요 여기서 일 예를의 모습이 너무 예를 업데이트

    UPDATE 21/11/2012 @ALL : 나는 그것이 잘 작동하고 크리스 야곱과 FB 모범 사례에서 계정 발언에 소요 여기서 일 예를의 모습이 너무 예를 업데이트

    안녕하세요 그래서 같은 내 대답은 자바 스크립트를 사용하고 여기 약속 :

    페이지의 본문의 내용 :

    <div id="fb-root"></div>
    <script src="http://connect.facebook.net/en_US/all.js"></script>
    <script>
      FB.init({
        appId  : 'YOUR APP ID',
        status : true, 
        cookie : true, 
        xfbml  : true  
      });
    </script>
    
    <div id="container_notlike">
    YOU DONT LIKE
    </div>
    
    <div id="container_like">
    YOU LIKE
    </div>
    

    CSS의 :

    body {
    width:520px;
    margin:0; padding:0; border:0;
    font-family: verdana;
    background:url(repeat.png) repeat;
    margin-bottom:10px;
    }
    p, h1 {width:450px; margin-left:50px; color:#FFF;}
    p {font-size:11px;}
    
    #container_notlike, #container_like {
        display:none
    }
    

    그리고 마지막으로 자바 스크립트 :

    $(document).ready(function(){
    
        FB.login(function(response) {
          if (response.session) {
    
              var user_id = response.session.uid;
              var page_id = "40796308305"; //coca cola
              var fql_query = "SELECT uid FROM page_fan WHERE page_id = "+page_id+"and uid="+user_id;
              var the_query = FB.Data.query(fql_query);
    
              the_query.wait(function(rows) {
    
                  if (rows.length == 1 && rows[0].uid == user_id) {
                      $("#container_like").show();
    
                      //here you could also do some ajax and get the content for a "liker" instead of simply showing a hidden div in the page.
    
                  } else {
                      $("#container_notlike").show();
                      //and here you could get the content for a non liker in ajax...
                  }
              });
    
    
          } else {
            // user is not logged in
          }
        });
    
    });
    

    그것은 무엇을 그래서 무엇을합니까?

    이미 사용자 ID가 있다면 첫 번째는 (FB에 로그인, 당신은 당신이 로그인 물건을 우회 할 수 및 YOUR_USER_ID와 response.session.uid 교체해야합니다 사용자가 이미 페이스 북에 기록되어 있습니다 (당신의 레일 예를 들어 앱에서)

    그것은 page_fan 테이블에 FQL 쿼리를 만들고, 그 후 의미는 사용자가 페이지의 팬이 있다면, 그것은 사용자 ID를 반환하고, 그렇지 않으면 그 후, 빈 배열을 반환하고 결과의 쇼에 따라이다 div이 다른.

    또한 작업 데모 여기있다 : http://jsfiddle.net/dwarfy/X4bn6/

    그것은 예를 들어 코카콜라 페이지를 사용하고, 그것은 가서 코카콜라 페이지는 달리 / 추천하고 다시 실행하려고 ...

    마지막으로 몇 가지 관련 문서 :

    FQL page_fan 테이블

    FBJS FB.Data.query

    당신은 질문이있는 경우 주저하지 말고 ..

    건배

    업데이트 2

    누군가에 의해 언급 한 바와 같이, (그것은 단지 document.ready 및 표시 / 숨기기 위해 사용되는) jQuery를 작업에 자바 스크립트 버전이 필요하지만 당신은 쉽게 제거 할 수 있습니다.

    우리가 문서를 교체하는 것이 문서 (IE 7 / 파이어 폭스 3)로드되었는지 어떻게 그렇게 감지 - 자바 스크립트는 다음 document.ready를 들어, 기능과 사용의 몸 온로드 = "your_function"이상 여기처럼 복잡 뭔가 코드를 포장 할 수 준비된.

    그리고 쇼 숨기기 물건 당신은 같은 것을 사용할 수 있습니다. HTTP : document.getElementById를 ( "container_like")를 style.display를 =는 "없음"또는 "블록"보다 안정적인 크로스 브라우저 기술에 대한 여기에 볼 //www.webmasterworld .COM / forum91 / 441.htm

    그러나 jQuery를 너무 쉽게 :)

    최신 정보

    상대적으로 내가 아래 여기에 여기에 게시 코멘트에이 페이스 북의 내부 표시를 인출 할 때 캔버스 URL에 POST 페이스 북의 그 "signed_request"를 디코딩하는 일부 루비 코드입니다.

    액션 컨트롤러에서 :

    decoded_request = Canvas.parse_signed_request(params[:signed_request])
    

    그리고 자사의 디코딩 된 요청을 표시 한 페이지 또는 다른 확인의 문제 .. (확실하지 이것에 대해, 내가 루비 편안하지 않다)

    decoded_request['page']['liked']
    

    그리고 여기 (fbgraph 루비 라이브러리) 관련 캔버스 클래스는 다음과 같습니다

     class Canvas
    
        class << self
          def parse_signed_request(secret_id,request)
            encoded_sig, payload = request.split('.', 2)
            sig = ""
            urldecode64(encoded_sig).each_byte { |b|
              sig << "%02x" % b
            }
            data = JSON.parse(urldecode64(payload))
              if data['algorithm'].to_s.upcase != 'HMAC-SHA256'
              raise "Bad signature algorithm: %s" % data['algorithm']
            end
            expected_sig = OpenSSL::HMAC.hexdigest('sha256', secret_id, payload)
            if expected_sig != sig
              raise "Bad signature"
            end
            data
          end
    
          private
    
          def urldecode64(str)
            encoded_str = str.gsub('-','+').gsub('_','/')
            encoded_str += '=' while !(encoded_str.size % 4).zero?
            Base64.decode64(encoded_str)
          end
        end  
    
     end
    
  2. ==============================

    2.당신은 약간의 PHP 코드를 작성해야합니다. 확인할 수있는 사용자 첫 번째 클릭 탭을 때 그는 페이지 또는하지를 좋아한다. 아래의 샘플 코드는

    당신은 약간의 PHP 코드를 작성해야합니다. 확인할 수있는 사용자 첫 번째 클릭 탭을 때 그는 페이지 또는하지를 좋아한다. 아래의 샘플 코드는

    include_once("facebook.php");
    
        // Create our Application instance.
        $facebook = new Facebook(array(
          'appId'  => FACEBOOK_APP_ID,
          'secret' => FACEBOOK_SECRET,
          'cookie' => true,
        ));
    
    $signed_request = $facebook->getSignedRequest();
    
    // Return you the Page like status
    $like_status = $signed_request["page"]["liked"];
    
    if($like_status)
    {
        echo 'User Liked the page';
        // Place some content you wanna show to user
    
    }else{
        echo 'User do not liked the page';
        // Place some content that encourage user to like the page
    }
    
  3. ==============================

    3.다음은이 답변의 포크입니다 작업 예제입니다 :

    다음은이 답변의 포크입니다 작업 예제입니다 :

    $(document).ready(function(){
        FB.login(function(response) {
            if (response.status == 'connected') {
                var user_id = response.authResponse.userID;
                var page_id = "40796308305"; // coca cola page https://www.facebook.com/cocacola
                var fql_query = "SELECT uid FROM page_fan WHERE page_id="+page_id+" and uid="+user_id;
    
                FB.api({
                    method: 'fql.query',
                    query: fql_query
                },
                function(response){
                    if (response[0]) {
                        $("#container_like").show();
                    } else {
                        $("#container_notlike").show();
                    }
                }
                );    
            } else {
            // user is not logged in
            }
        });
    });
    

    내가 대신 사용되지 않습니다 FB.Data.query,의, FB.api 방법 (자바 스크립트 SDK)를 사용했다. 또는 당신은이 예와 같이 그래프 API를 사용할 수 있습니다 :

    $(document).ready(function() {
        FB.login(function(response) {
            if (response.status == 'connected') {
                var user_id = response.authResponse.userID;
                var page_id = "40796308305"; // coca cola page https://www.facebook.com/cocacola
                var fql_query = "SELECT uid FROM page_fan WHERE page_id=" + page_id + " and uid=" + user_id;
    
                FB.api('/me/likes/'+page_id, function(response) {
                    if (response.data[0]) {
                        $("#container_like").show();
                    } else {
                        $("#container_notlike").show();
                    }
                });
            } else {
                // user is not logged in
            }
        });
    });​
    
  4. ==============================

    4.사용자가 좋아하거나 페이지가 Auth2.0 권한 부여로 이동 페이스 북에 의해 위임 좋아하지 않는 기반으로 렌더링 핸들에 자바 스크립트 코드에 필요한 몇 가지 변경 사항이 있습니다.

    사용자가 좋아하거나 페이지가 Auth2.0 권한 부여로 이동 페이스 북에 의해 위임 좋아하지 않는 기반으로 렌더링 핸들에 자바 스크립트 코드에 필요한 몇 가지 변경 사항이 있습니다.

    변화는 매우 간단하다 : -

    세션은 authResponse로 대체하고 사용자 ID에 의해 uid를해야합니다

    또한 코드의 요구 사항과 FB.login와 일반적으로 (나를 포함한) 사람들이 직면 한 몇 가지 문제가 주어 FB.getLoginStatus의 사용은 더 나은 대안이다. 그것은 경우 사용자에 FB에 쿼리 저장이 기록되어 있고 응용 프로그램을 인증했다.

    이 FB 서버에 쿼리를 저장하는 방법에 대한 정보를 원하시면 응답 및 세션 개체 섹션을 참조하십시오. http://developers.facebook.com/docs/reference/javascript/FB.getLoginStatus/

    FB.login 및 FB.getLoginStatus를 사용하여 수정 문제. http://forum.developers.facebook.net/viewtopic.php?id=70634

    여기에 나를 위해 일한 변경 위에서 게시 된 코드입니다.

    $(document).ready(function(){
        FB.getLoginStatus(function(response) {
            if (response.status == 'connected') {
                var user_id = response.authResponse.userID;
                var page_id = "40796308305"; //coca cola
                var fql_query = "SELECT uid FROM page_fan WHERE page_id =" + page_id + " and uid=" + user_id;
                var the_query = FB.Data.query(fql_query);
    
                the_query.wait(function(rows) {
    
                    if (rows.length == 1 && rows[0].uid == user_id) {
                        $("#container_like").show();
    
                        //here you could also do some ajax and get the content for a "liker" instead of simply showing a hidden div in the page.
    
                    } else {
                        $("#container_notlike").show();
                        //and here you could get the content for a non liker in ajax...
                    }
                });
            } else {
                // user is not logged in
            }
        });
    
    });
    
  5. ==============================

    5.자바 스크립트 SDK를 사용하면 다음과 같이 코드를 변경할 수 있습니다,이 FB.init 호출 후에 추가해야합니다.

    자바 스크립트 SDK를 사용하면 다음과 같이 코드를 변경할 수 있습니다,이 FB.init 호출 후에 추가해야합니다.

         // Additional initialization code such as adding Event Listeners goes here
    FB.getLoginStatus(function(response) {
          if (response.status === 'connected') {
            // the user is logged in and has authenticated your
            // app, and response.authResponse supplies
            // the user's ID, a valid access token, a signed
            // request, and the time the access token 
            // and signed request each expire
            var uid = response.authResponse.userID;
            var accessToken = response.authResponse.accessToken;
            alert('we are fine');
          } else if (response.status === 'not_authorized') {
            // the user is logged in to Facebook, 
            // but has not authenticated your app
            alert('please like us');
             $("#container_notlike").show();
          } else {
            // the user isn't logged in to Facebook.
            alert('please login');
          }
         });
    
    FB.Event.subscribe('edge.create',
    function(response) {
        alert('You liked the URL: ' + response);
          $("#container_like").show();
    }
    
  6. ==============================

    6.문제를 설명 여기에 기사가있다

    문제를 설명 여기에 기사가있다

    http://www.hyperarts.com/blog/facebook-fan-pages-content-for-fans-only-static-fbml/

        <fb:visible-to-connection>
           Fans will see this content.
           <fb:else>
               Non-fans will see this content.
           </fb:else>
        </fb:visible-to-connection>
    
  7. from https://stackoverflow.com/questions/6246449/facebook-how-to-check-if-user-has-liked-page-and-show-content by cc-by-sa and MIT license