Like a Facebook Post externally using Graph Api - example
Asked Answered
P

1

1

Could someone please give me an example of posting a like for a facebook post from an external app with an authenticated user?

Say I have a feed pulling posts from facebook, and I want to create a button that lets the user like a post from my app. On click of this button, how could I best create that like so that the post is updated on Facebook with the user's like?

My thoughts are that I could make a javascript onclick function that ajaxes to a php script that does something like - $facebook->api("/$id/likes",'POST'); , but do I need to re-initialize facebook from that page before I can make this call? or send my access token etc.? This is what kind of confuses me about this server-side method. How do you make this call upon click? An example would be really helpful! Thanks in advance!!

Pepillo answered 11/7, 2012 at 8:8 Comment(0)
P
0

Okay so finally found a decent solution, and without curl. This is the script I call to in my ajax function onclick:

<?php
$access_token = $_GET['token'];

$post_id = $_GET['id'];

function do_post_request($url, $data, $optional_headers = null)
{
$params = array('http' => array(
          'method' => 'POST',
          'content' => $data
        ));
if ($optional_headers !== null) {
  $params['http']['header'] = $optional_headers;
}
$ctx = stream_context_create($params);
$fp = @fopen($url, 'rb', false, $ctx);
if (!$fp) {
  echo "error";
}
$response = @stream_get_contents($fp);
if ($response === false) {
  throw new Exception("Problem reading data");
}
  return $response;
}

$data = "access_token=".$access_token;

$url = 'https://graph.facebook.com/'.$post_id.'/likes';

$result = do_post_request($url, $data, $optional_headers = null);
?>

Also in my tested working code the $post_id has the user id whose post it was first like this: SOURCEUSERID_POSTID

Got this solution from a combination of this post - http://wezfurlong.org/blog/2006/nov/http-post-from-php-without-curl/

and this one - Like posts over Facebook graph api

hope this helps someone else out !

Pepillo answered 11/7, 2012 at 12:11 Comment(2)
i have tried your soluation if am the owner of the post am able add like , but if user loged in and try add like to my post he is getting an permission error 200 , please have look my post #12577981Tsimshian
moata_u asked some great questions, if you want to learn more, like what my ajax function looks like and the html, and how to check if the logged in user already likes a post, go here #12577981Pepillo

© 2022 - 2024 — McMap. All rights reserved.