programing

Facebook 사용자가 페이지를 좋아했는지 확인하고 콘텐츠를 표시하는 방법은 무엇입니까?

goodcopy 2021. 1. 19. 08:05
반응형

Facebook 사용자가 페이지를 좋아했는지 확인하고 콘텐츠를 표시하는 방법은 무엇입니까?


Facebook iFrame 앱을 만들려고합니다. 앱은 먼저 이미지를 표시해야하며 사용자가 페이지를 좋아하면 일부 콘텐츠에 액세스 할 수 있습니다.

RoR을 사용하기 때문에 Facebook PhP SDK를 사용할 수 없습니다.

사용자가 페이지를 좋아하지 않았을 때의 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>


업데이트 21/11/2012 @ALL : 더 잘 작동하도록 예제를 업데이트하고 Chris Jacob 및 FB 모범 사례의 설명을 고려하여 여기 에서 작업 예제를 살펴 봅니다.


안녕하세요 약속 한대로 자바 스크립트 만 사용하는 내 대답입니다.

페이지 BODY의 내용 :

<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
      }
    });

});

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

먼저 FB에 로그인합니다 (이미 USER ID가 있고 사용자가 이미 페이스 북에 로그인되어 있다고 확신하는 경우 로그인 항목 response.session.uid을 건너 뛰고 YOUR_USER_ID (예 : rails 앱에서))로 바꿀 수 있습니다.

그 후 page_fan테이블 에 FQL 쿼리를 수행 하고 사용자가 페이지의 팬인 경우 사용자 ID를 반환하고 그렇지 않으면 빈 배열을 반환하고 그 후에 결과에 따라 div를 표시한다는 의미입니다. 또는 다른.

또한 여기에 작동하는 데모가 있습니다 : http://jsfiddle.net/dwarfy/X4bn6/

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

마지막으로 관련 문서 :

FQL page_fan 테이블

FBJS FB.Data.query

궁금한 점이 있으면 망설이지 말고 ..

건배

업데이트 2

누군가가 말했듯이 자바 스크립트 버전이 작동하려면 jQuery가 필요하지만 쉽게 제거 할 수 있습니다 (document.ready 및 표시 / 숨기기에만 사용됨).

document.ready의 경우 코드를 함수로 래핑하고 다음과 body onload="your_function"같이 더 복잡한 것을 사용할 수 있습니다. Javascript-문서가로드되었는지 감지하는 방법 (IE 7 / Firefox 3) 을 통해 문서 준비를 대체합니다.

표시 및 숨기기 항목은 다음 document.getElementById("container_like").style.display = "none" or "block"같이 사용할 수 있습니다. 보다 안정적인 크로스 브라우저 기술을 보려면 여기를 참조하십시오. http://www.webmasterworld.com/forum91/441.htm

그러나 jQuery는 너무 쉽습니다. :)

최신 정보

여기에 내가 여기에 게시 한 주석과 관련하여 facebook 내부에 표시하기 위해 가져올 때 facebook POST가 CANVAS URL에 게시하는 "signed_request"를 디코딩하는 루비 코드가 있습니다.

액션 컨트롤러에서 :

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

그리고 디코딩 된 요청을 확인하고 한 페이지 또는 다른 페이지를 표시하는 문제입니다 .. (이건 확실하지 않지만 루비에 익숙하지 않습니다)

decoded_request['page']['liked']

다음은 관련 Canvas 클래스 ( fbgraph ruby ​​라이브러리에서 제공 )입니다.

 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

약간의 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
}

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

$(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 메서드 (JavaScript SDK)를 사용했습니다. 또는 다음 예제와 같이 Graph 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
        }
    });
});​

Auth2.0 인증으로 이동하는 Facebook에서 요구하는 페이지를 사용자가 좋아하거나 싫어하는 것에 따라 렌더링을 처리하기 위해 JavaScript 코드에 몇 가지 변경이 필요합니다.

변경은 매우 간단합니다.

세션은 authResponse로, uid는 userID로 대체해야합니다.

Moreover given the requirement of the code and some issues faced by people(including me) in general with FB.login, use of FB.getLoginStatus is a better alternative. It saves query to FB in case user is logged in and has authenticated your app.

Refer to Response and Sessions Object section for info on how this might save query to FB server. http://developers.facebook.com/docs/reference/javascript/FB.getLoginStatus/

Issues with FB.login and its fixes using FB.getLoginStatus. http://forum.developers.facebook.net/viewtopic.php?id=70634

Here is the code posted above with changes which worked for me.

$(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
        }
    });

});

With Javascript SDK, you can change the code as below, this should be added after FB.init call.

     // 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();
}

There is an article here that describes your problem

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>

ReferenceURL : https://stackoverflow.com/questions/6246449/facebook-how-to-check-if-user-has-liked-page-and-show-content

반응형