How to post content on Facebook (Meta) from your server app

Sayantan Sarkar
4 min readMar 20, 2023

--

Publish Content on Facebook

Facebook recently launched the Facebook Meta platform, which enables developers to build immersive and interactive experiences that leverage the power of the Facebook platform. With Facebook Meta, you can create rich, interactive content that can be shared across the Facebook platform, and reach millions of people.

In this tutorial, we will walk through the steps required to post content on Facebook Meta from your server app. This will enable you to easily share your content on Facebook, and reach a wider audience.

Before jumping right into showing the steps, let me tell you the background story about it.

So, I was working on a application where some new requirement came in, it was like our end user would click publish button from client app and our backend application should publish content (or list of contents) on their Facebook account. So, I started reading document Graph API documentation. Initially my plan was to publish content on user’s Facebook profile feed. So, I started looking for getting that special permission to post content on user’s profile feed with user_access_token. After spending tons of time, I found that the permission needed was publish_actions, But it was deprecated by Facebook team due to data privacy and security reasons. Also, it was not possible to login from server end and receive access_token. I had to develop another client application which would prompt user for Facebook login and give permissions to receive user_access_token.

But, I found that it is possible to publish content on Facebook page instead of user’s profile feed. So, there were some tweak needed in the original plan. Now I was off to start the integration with my server application.

First and foremost, create a developer account in Facebook. Going into the account, create an App of type ‘Business’ and fill up other details. Now you have an app. Go into that application dashboard -> Add Products -> Facebook Login for Business.

app dashboard

Then go to Configurations under Facebook Login for Business -> Create Configuration ->Add a name -> Choose User Access Token -> Add permissions- publish_videos and page_manage_posts and create configuration file. Now you have an configuration Id —

Configuration Id

Once you are done with this, you have done your part in Facebook app configuration. The next step is to configure your client application for Facebook login. I have created a simple index.html for Facebook login-

<!DOCTYPE html>
<html>
<head>
<title>Facebook Login JavaScript Example</title>
<meta charset="UTF-8">
</head>
<body>
<script>
window.fbAsyncInit = function() {
FB.init({
appId : '-your-app-Id-',
cookie : true,
xfbml : true,
version : 'v16.0'
});

FB.AppEvents.logPageView();

};

(function(d, s, id){
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) {return;}
js = d.createElement(s); js.id = id;
js.src = "https://connect.facebook.net/en_US/sdk.js";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));

function checkLoginState() {
FB.login(
function(response) {
getPageAccessToken(response.authResponse.accessToken, response.authResponse.userID);
}
);
}

async function getPageList(userAccessToken, userId) {
const urlEndpoint = new URL("https://graph.facebook.com/"+ userId + "/accounts");
urlEndpoint.searchParams.set("fields","name,access_token");
urlEndpoint.searchParams.set("access_token", userAccessToken);
const response = fetch(urlEndpoint)
.then((response) => response.json())
.then((json) => {
console.log("Page ID:" + json.data[0].id);
console.log("Page Access Token:"+ json.data[0].access_token);
});
}


function logoutFromFacebook() {
FB.getLoginStatus(function(response) {
if(response && response.status === 'connected'){
FB.logout(function(response){
console.log(response);
});

}
});

}
</script>
<fb:login-button config_id="-your-app-config-id-" onlogin="checkLoginState();">
</fb:login-button>
<button onclick="logoutFromFacebook()">
Logout
</button>
</body>
</html>

Note: I had to enable https in my localhost to successfully complete login to Facebook.

For login, I am using app-id, client-id, client-secret and configuration id of application and all these details can be found in app dashboard. Now let me elaborate on the details of what I am doing here.

In index.html file config_id is passed with login button. On clicking login button, user will be promted for login and give permission for the scopes i.e. publish_videos and page_manage_posts that I have asked for my application. After completion of this step, access_token and user id would be received. On receiving, next function call is triggered i.e. it would receive a list of pages with its page id and page access token. To make it simple, I have used the data of first page received in the list and passed this page_id and page_access_token to my server app to post on Facebook page.

Now, we are at last step to finally publish content in Facebook page. In my server application, I have used a function to take required data as argument and publish the content on Facebook page.

public async Task<bool> PublishToPage(string pageAccessToken, string pageId, Stream imageData, string message = "")
{
string publishEndpoint = "https://graph.facebook.com"+ "/"+ pageId + "/photos";
MemoryStream memoryStreamForImageData = new MemoryStream ();
imageData.CopyTo(memoryStreamForImageData);
using (var formData = new MultipartFormDataContent())
{
formData.Add(new StringContent(pageAccessToken), "access_token");
formData.Add(new StringContent(message), "caption");
formData.Add(new ByteArrayContent(memoryStreamForImageData.ToArray()), "source", "image.png");
var response = await client.PostAsync(publishEndpoint, formData);
if (!response.IsSuccessStatusCode)
{
return false;
}
return true;
}
}

As, you have come up to this step and if you can successfully complete whole integration, Congratulate yourself and pat on your back, you have really done a great job.

I love to share my experience in different software development and also about travel in different offbeat parts in India.

Follow me on Medium

Follow me on Instagram

Follow me on Twitter

--

--

Sayantan Sarkar

Software Engineer 2 at Lexmark (India), Passionate about Technology, Startup and Love to travel