< Back

Publish to Your Facebook Page&#8217;s Wall with PHP

The Facebook API, or the RESTful API, maybe FBML or the Graph API, can be a bit of a challenge. I literally felt like a fourth grader in college calculus when I was first attempting to authenticate with the system. Luckily, after hours and hours of frustration, I was finally able to post to my business page’s wall using Facebook’s Graph API and PHP.

Here are exact steps I took complete with code examples:

1. Request User Authorization Code from Facebook

Our first step is to redirect the user to Facebook so the user can choose whether to allow our application to make updates on their behalf.

function request_user_access_code() {
	header('Location: https://www.facebook.com/dialog/oauth?client_id=YOUR_FACEBOOK_APP_ID&redirect_uri=YOUR_RETURN_URL&scope=manage_pages,publish_stream&response_type=code');
}

Parameters

client_id

  • Your Facebook application’s app id.

redirect_uri

  • URL on your domain that will handle Facebook’s response.
  • Don’t use your own querystring parameters. In fact, make sure you remove any appended question marks.

scope

  • The publish_stream permission provides you wall posting rights.
  • The manage_pages allows you to connect to any page that you administer as the page itself.

response_type

  • I used code, since I wanted my web application to be able to post without the using the Javascript API.
  • Using token, or code_and_token, does cut out a step, since you’re given the user’s access token, but doesn’t work well the PHP’s server-side.

Response

redirect_uri?code=OAuth_code (i.e. http://www.example.com/test.php?code=XXXXXXXXXX)

  • If you successfully interface with Facebook and the user accepts your request, Facebook will send you a request at the URL you provided in the redirect_uri parameter with a querystring parameter called “code”.
  • If the user denies your request or something else bad happens, Facebook will request your redirect_uri with error querystrings detailing the problem.

2. Request User Access Token from Facebook

Now we need to get a Facebook session ID for the user. So, use the returned OAuth “code” to retrieve a Facebook access token. This token is session-based and does expire.

function request_user_access_token() {
	$token_url = "https://graph.facebook.com/oauth/access_token?client_id=YOUR_FACEBOOK_APP_ID&redirect_uri=" . urlencode(YOUR_RETURN_URL) . "&client_secret=YOUR_FACEBOOK_APP_SECRET&code=CODE_FROM_STEP_1;

	$result = file_get_contents($token_url);
	
	parse_str($result);
	
	return $access_token;
}

Parameters

client_id

  • Your Facebook application’s app id.

redirect_uri

  • Identical URL to the redirect_uri parameter in Step 1 — make sure to “urlencode” it. Facebook will sometimes return an error if not.

client_secret

  • Your Facebook application’s app secret.

code

  • Return “code” querystring value from Step 1.

Response

access_token=XXXXXXXXXX

  • Facebook returns a key and value pair in string format, so I use the “parse_str” function to strip the access_token value out.

3. Retrieve User Pages and Find Access Token for your Target Page

So, after authorizing your user and retrieving a Facebook access token for that user, one would think that you could then post to your page. Incorrect assumption, there’s at least 10 more steps (just kidding). What we do need next is an access_token specific to the page that you want to work with. To get that, we pull a JSON array of all the user’s pages (i.e. accounts), and search for a matching Facebook Page ID.

function get_page_access_token($facebook_page_id) {
	// Pull a JSON array of all the user's pages
	$accounts = json_decode(
		file_get_contents('https://graph.facebook.com/me/accounts?access_token=ACCESS_TOKEN_FROM_STEP_2));
	
	if(!empty($accounts)) {
		// loop through user's accounts (i.e. pages)
		foreach($accounts->data as $account) {
			// if account id matches, return page's access_token
	    		if($account->id == $facebook_page_id)
	        			return $account->access_token;
	   	}
	}
}

Parameters

access_token

  • Access token of the authorized Facebook User.

Response

JSON array of User’s Pages

4. Finally, Post to the Page’s Wall via cURL

We eventually arrived at the end of our journey… well sort of. Our last step is to post some coolness up on your Facebook Page as your Facebook Page. So, with the help of cURL, the function below will hopefully do that if the three steps above succeeded.

function post_to_wall($page_id, $access_token, $message) {
	$params = array(
		'access_token' => $access_token, 
		'message' => $message
	);
	
	$result = "";
	
    if (function_exists('curl_init')) {
		//url-ify the data for the POST
		foreach($fields as $key => $value) { $fields_string .= $key.'='.$value.'&'; }
		
		rtrim($fields_string,'&');

		//open connection
		$ch = curl_init();

		//set the url, number of POST vars, POST data
		curl_setopt($ch, CURLOPT_URL, 'https://graph.facebook.com/' . $page_id . '/feed');
		curl_setopt($ch, CURLOPT_POST, count($fields));
		curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

		//execute post
		$result = curl_exec($ch);

      	curl_close($ch);
    } 

    return $result;
}

Parameters

page_id

  • Your Facebook Page’s ID.

access_token

  • Facebook Page specific access token.

message

  • Text you would like to post. You can add a bunch more parameters to this call for links and attachments.

Response

JSON object of Success or Failure

Time for a Nap

Although these steps seem partially intuitive now, at one point, I did consider giving up on technology and entering a life of solitude. All I’m hoping is that this post might save one person from a similar experience.

UPDATE: Code Example

Connect with us

Thank You!

We really appreciate your interest in what we do.

We'll get back to you as soon as we can.