Post to facebook Page using Graph API v9.0 and PHP SDK v5 with non expiring access token

Post to facebook Page using Graph API v9.0 and PHP SDK v5 tutorial aims at showing you how to dynamically post links and messages to your facebook page and groups from your PHP script.

Create Your Facebook App

Go to developers.facebook.com

First thing is to create your facebook app. Go to https://developers.facebook.com/ and click on My Apps. Follow the arrow directions on the image below.

Click on Create App

Once you click My Apps, the landing page will look like the image below – if you don’t have any app created yet

or this other image below – if you already have some app created on facebook.

In anycase, click on the green button: Create App, as shown in both images.

Next you see the pop up as shown in the image below, click on: Manage Business Integrations and click on continue.

On the next pop up which looks like the image below

Enter your App Display Name, App Contact Email, App Purpose and click on Create App.

Copy your App ID and your Secret Key

You have successfully created your app, now you land on the page shown in the image below.

Click on Settings, then under Settings click on Basic and then you will see the page as shown in the image below.

Copy your App ID, click on Show, enter your password again for confirmation and then copy your App Secret key; keep both keys somewhere, we will need them soon. Enter the domain where you will be posting links and messages from; enter privacy policy url of that domain and click on Save Changes.

Get Access Token

Click on tools and under tools click on Graph API Explorer. Follow the arrow on the image below

As you land on the Graph API Explorer page shown in the image below,

click on the Get Token drop down arrow – follow the red marker on the image above, and then select: Get Page Access Token.

Once you selected get page access token, you will see a pop up as shown in the image below.

Click on Continue as your username and then on the next screen Select the page you want to post to and click next. On the next screen, ignore the: Submit for Login Review and click on: Done.

Once you click on Done, you see a drop down as show in the image below

Click on – 2 options selected drop down icon – and select: pages_manage_post and publish_to_groups. Then click on User_Token and click on your page name under Page Acess Tokens – see red marker on images below for directions.

Note that every time you add new permission to your app, the blue submit button deactivates – see image below,

and at this point if you try posting anything, you will receive an error message. So after selecting pages_manage_post and publish_to_groups, you have to click on the blue button: Generate Access Token – as seen in the image above, and you will be prompted with the screen shown in the image below

Click on choose what you allow and select the groups and pages you want to post to and save. Now your token is updated.

One caution before we continue; since we are posting to pages and groups in this tutorial, always make sure that your page is what is selected as shown in the image below to be sure that you have the right token.

Test your Graph API token

Get your Page ID

Go to your facebook page and click on About, you will see Page ID on the pop up menu down below. Remove this field: me?fields=id,name – see red marker on image below. Copy your facebook ID and paste it there in this format: 175366478453835/feed

Change the GET variable to POST variable; see marker on image above for direction. As you change GET to POST, you see where to enter POST parameters as shown in the image below

Click on Add Parameter and type: message in Enter key field and any message – for e.g This is a test post – in the Enter value field and click on Submit. If all went well, you should see a response message in the format shown below.

The response starts with your facebook Page ID before and underscore and some other figures. Now go to your facebook page, refresh the page and look out for the message you posted. If you found it, then all is well; we can now go on to implementing the code in PHP.

How to get non expiring facebook Graph API access token

https://graph.facebook.com/oauth/access_token?grant_type=fb_exchange_token&client_id=appid&client_secret=appsecret&fb_exchange_token=accesstoken

On the link above, put your facebook App ID where you have appid, put your secret key where you have appsecret and then copy the access token on the Graph API Explorer and paste where you have accesstoken. Copy the link and paste in your browser and hit enter, then copy the link you see in your browser; this is your non expiring access token which you will use in your code. The purpose of this is so that you do not have to go to your code always to change token after it expires.

Download Facebook PHP SDK

https://github.com/facebookarchive/php-graph-sdk?fbclid=IwAR3RJKGdiusW-mHMMqFUnzchVPNZU7DMP4YgvkQQ3E32XNh_hZOdrNPJzN0

Click on the link above to download the facebook PHP SDK. The latest version is V5, click on the green button named code; then click on download ZIP to download the file.

Once download, unzip it in the folder you prefer in your project and reference it in the page where your facebook code resides accordingly.

PHP Code To Post To Facebook Page

The code is basically divided into 3 parts

  1. Reference To Facebook PHP SDK
  2. Facebook App settings
  3. Post to Facebook Page

Reference To Facebook PHP SDK

define('FACEBOOK_SDK_V5_SRC_DIR', __DIR__.'/src/Facebook/');
require_once(__DIR__.'/src/Facebook/autoload.php');

For me the file where my code is written and the unzipped called src is in the same folder, hence the way i have referenced it in the code above.

Facebook App settings

$fb = new Facebook\Facebook([
    'app_id' => 'Put_your_facebook_app_id_here',
    'app_secret' => 'Put_your_facebook_app_secret_key_here',
    'default_graph_version' => 'v9.0',
]);

Post To Facebook Page

$linkData = [
    'link' => 'Put_Whatever_URL_You_Are_Posting_To_Facebook_Here',
    'message' => 'Put_Whatever_Message_You_Are_Posting_To_Facebook_Here'
];
$pageAccessToken ='yournonexpiringtoken';

try {
    $response = $fb->post('/me/feed', $linkData, $pageAccessToken);
} catch(Facebook\Exceptions\FacebookResponseException $e) {
    echo 'Graph returned an error: '.$e->getMessage();
    exit;
} catch(Facebook\Exceptions\FacebookSDKException $e) {
    echo 'Facebook SDK returned an error: '.$e->getMessage();
    exit;
}
$graphNode = $response->getGraphNode();

Post To Facebook Group

Same code as above, but change the below line of code

$response = $fb->post('/me/feed', $linkData, $pageAccessToken);

to this one

$response = $fb->post('Your_Group_ID_Here/feed', $linkData, $pageAccessToken);

Navigate to your group, look at the URL you will see something like this: https://web.facebook.com/groups/116032146927374

The digit part of the URL is your group ID, copy it and paste in the code above.

8 comments
  1. Do u know if this is still valid and working?
    The “Get token” part – where I’m logged into FB and continue as me – and after chosen the page to post to – I get “Sorry, this content isn’t availabe right now” in the small popup.
    Have tried with another FB user – same prob. I never get to the point about permissions.
    If u still do stuff about FB – we would like to pay u for your help. We are stock…Everything worked start of year – but no longer. I guess its a checkbox somewhere in the jungle.
    Maybe we could do a online meeting?
    Hope to hear from you
    Best regards
    Peter Stub

  2. Excellent description. FB docs unfathomable for the novice. You made it simple.
    A little bit of fiddling around to make it work with Drupal’s response object, but no problem.
    Thanks much.

  3. BEST article on the subject! Thank you for the arrows and images. I found a ton of similar articles and wasted MANY minutes trying to find the buttons they are talking about. And they were not complete!
    On a separate note. Do you know what I did wrong, that my final page access token has an expiration (i got it back like that)? Did the steps a few times over, same result.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.