如何使用CURL在Facebook上发布帖子,而不使用PHP中的SDK

问题描述:

我正在开发一个需要Facebook集成的PHP项目。所以在我做代码之前,我正在使用Facebook Graph API浏览器工具(https://developers.facebook.com/tools/explorer)测试它。我现在正在做的是。如何使用CURL在Facebook上发布帖子,而不使用PHP中的SDK

第一步骤

Get the user access_token by using the button at the top left. 

第二步骤

Make a GET request to "me/accounts" to get the page token and page id. 

第三步骤

Make a POST request to "{page_id}/feed" with the fields message={message} and access_token={page_token} 

它工作完美,张贴在我的Facebook粉丝页。但是,当我尝试用这样的PHP代码代替“第三步”时

$data['message'] = "my message"; 


$data['access_token'] = $page_access_token; //page token from 2nd step 
$ch = curl_init(); 
curl_setopt($ch,CURLOPT_URL, 'https://graph.facebook.com/{page_id}/feed'); 
curl_setopt($ch, CURLOPT_VERBOSE, 1); 
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); 
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE); 
curl_setopt($ch,CURLOPT_POSTFIELDS, $data); 
curl_setopt($ch,CURLOPT_RETURNTRANSFER,TRUE); 
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE); 
curl_setopt($ch, CURLOPT_POST, 1); 


$resp = curl_exec($ch); 

curl_close($ch); 

$data_resp = json_decode($resp); 

print_r($data_resp); 

它向我显示这个错误。

stdClass Object ([error] => stdClass Object ([message] => (#200) Permissions error [type] => OAuthException [code] => 200)) 

我设置的manage_pages,publish_pages,publish_actions权限

+0

调试你的'access_token'并检查它是否获得了所需的权限。 https://developers.facebook.com/tools/debug/ – Criesto

看一看该文档在

个权限

  • publish_actions权限的用户访问令牌可以用来代指人的发布新文章。帖子将出现在用户的声音中。
  • 具有publish_pages权限的页面访问令牌可用于代表该页面发布新帖子。帖子将出现在页面的声音中。

您应该通过

运行用于访问令牌,看它是否包含了适当的权限(S)。

+0

是的。令牌很好,它包含了所有需要的权限。 –

传递数组CURLOPT_POSTFIELDS意味着cURL将发送请求作为内容类型multipart/form-data - 但您想要application/x-www-form-urlencoded代替。

在您的$data数组上使用http_build_query,并将结果字符串用于CURLOPT_POSTFIELDS