Like a Facebook Post externally using Graph Api - example

☆樱花仙子☆ 提交于 2019-12-24 09:59:16

问题


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!!


回答1:


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 !



来源:https://stackoverflow.com/questions/11428242/like-a-facebook-post-externally-using-graph-api-example

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!