Post to facebook page using api with plain php
Tags: webdev, php, facebook, api
Published: 2023-04-27 04:35:47


If you want to post to your facebook page using api you need to waste few hours or read this short guide.

You should have facebook app. If not - create one.

## 1. Get Short User Token

Get short user live token here [https://developers.facebook.com/tools/explorer](https://developers.facebook.com/tools/explorer). Check permissions: `pages_read_engagement` and `pages_manage_posts`
![](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hyj4ezixhqe2u21ojvv4.png)

## 2. Get Forever User Token and save it in .env file

Open `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` and get your forever user token (change app_id, app_secret and short_user_token)
You can use browser or some simple func

```php
<?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. Post your message

To post to facebook page, we will need **Page Access Token**. Duration of this token is 60 days, but can be changed anytime. In this example, we generate a new token everytime, but you can save it for some time if you're bulk posting.

```php
<?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);
}
}
```

On facebook you can read more details and how to post photos or videos:

1. [How to get access token](https://developers.facebook.com/docs/pages/access-tokens/)
2. [How to post to page using your page access token](https://developers.facebook.com/docs/pages/publishing)