Check if user likes page via Graph API

前端 未结 1 1318
伪装坚强ぢ
伪装坚强ぢ 2020-12-22 03:00

I have seen a few similar questions but I think this is new...

I am trying to add a popover on a blog that will contain a Facebook like button for a Facebook page an

相关标签:
1条回答
  • 2020-12-22 03:34

    You can tell if a user likes a page from the signed_request which is sent in the request from facebook. You don't have to query the graph api.

    We use c# and get it like so:

    protected void Page_Load(object sender, EventArgs e)
        {
            Result = DecodePayload(Request["signed_request"]);
        }
    
        public JObject DecodePayload(string payload)
        {
            var encoding = new UTF8Encoding();
            var decodedJson = payload.Split('.')[1].Replace("=", string.Empty).Replace('-', '+').Replace('_', '/');
            var base64JsonArray = Convert.FromBase64String(decodedJson.PadRight(decodedJson.Length + (4 - decodedJson.Length % 4) % 4, '='));
            Json = encoding.GetString(base64JsonArray);
            var result = JObject.Parse(Json);
            return result;
        }
    

    Then in the page

    <% if (Result["page"] == null || Result["page"]["liked"] == null || !(bool) Result["page"]["liked"])
         {%> 
     Content if liked
    <%}%>
    

    One more important thing as of the 30th March the page layout is changing to timeline and you should be aware of a bug currently that does not refresh the page upon liking it see this:

    Does anyone know a fix for the lack of page refresh on facebook timeline pages when liking?

    UPDATE

    The php for decoding the signed request is:

       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, '-_', '+/'));
    }
    
    0 讨论(0)
提交回复
热议问题