如果您想使用API发布到Facebook页面,则需要浪费几个小时或阅读此简短指南。
您应该拥有Facebook应用程序。如果不是 - 创建一个。
1.获取简短的用户令牌
在此处获取Short用户实时令牌https://developers.facebook.com/tools/explorer。检查权限:pages_read_engagement
和pages_manage_posts
2.获取永远的用户令牌并将其保存在.env文件中
打开https://graph.facebook.com/oauth/access_token?grant_type=fb_exchange_token&client_id=$app_id&client_secret=$app_secret&fb_exchange_token=$short_user_token
并获取您的永远用户令牌(更改app_id,app_secret和short_user_token)
您可以使用浏览器或一些简单的功能
<?php
function getForeverUserToken(): string
{
//this values I'm getting from .env file.
$app_id = config('services.facebook.client_id');
$app_secret = config('services.facebook.client_secret');
$short_user_token = config('services.facebook.short_token');
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL, "https://graph.facebook.com/oauth/access_token?grant_type=fb_exchange_token&client_id=$app_id&client_secret=$app_secret&fb_exchange_token=$short_user_token");
$response = curl_exec($ch);
curl_close($ch);
if ($response === false) {
die("Error: " . curl_error($ch));
}
$data = json_decode($response, true);
if (isset($data["error"])) {
die("Error: " . $data["error"]["message"]);
}
return $data["access_token"];
}
3.发布您的消息
要发布到Facebook页面,我们将需要页面访问令牌。这个令牌的持续时间为60天,但可以随时更改。在此示例中,我们每次都会生成一个新的令牌,但是如果您散装发布,您可以保存一段时间。
<?php
class FacebookPost {
public static function getPageAccessToken(): string
{
$pageId = config('services.facebook.page_id');
$forever_user_token = config('services.facebook.admin_token');
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://graph.facebook.com/$pageId?fields=access_token&access_token=$forever_user_token");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec($ch);
if ($response === false) {
die("Error: " . curl_error($ch));
}
$data = json_decode($response, true);
if (isset($data["error"])) {
die("Error: " . $data["error"]["message"]);
}
return $data["access_token"];
}
public static function postMessage(string $message, ?string $link = null): array
{
$page_token = self::getPageAccessToken();
$pageId = config('services.facebook.page_id');
$data = [
'message' => $message,
'access_token' => $page_token
];
//if we post link, include it
if ($link) {
$data['link'] = $link;
}
$ch = curl_init("https://graph.facebook.com/{$pageId}/feed");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($ch);
curl_close($ch);
return json_decode($result, true);
}
}
在Facebook上,您可以阅读更多详细信息以及如何发布照片或视频: