Facebook’s Real-time Updates documentation is not very explicit on how to subscribe to a feed, especially when all I am looking for is an example. So after figuring out what
OAuthException (#15) "This method must be called with an app access_token" was trying to tell me and fixing the problem, I figured I would share my PHP example here. Hopefully, it will be helpful to you.* There are two parts that you need to set up:
- Setup an endpoint for the subscription
- Post to Facebook and tell them you are subscribing
1. Setup an Endpoint
This part is actually pretty easy because Facebook actually gives you example code (yay!). Put that file on a web server somewhere with an external ip so that Facebook can reach it. Replace
define('VERIFY_TOKEN', 'abc');. Save this value for later.
2. Post to Facebook
Now comes the part that is not well documented. In order to subscribe you need to first specifically get an
access_token, then POST to Facebook.
A. Get an
$app_id = APP_ID; $secret = APPLICATION_SECRET; $token_url = "https://graph.facebook.com/oauth/access_token?" . "client_id=" . $app_id . "&client_secret=" . $secret . "&grant_type=client_credentials"; $response = @file_get_contents($token_url); $params = null; parse_str($response, $params);
B. POST to Facebook with cURL
Remember when we defined the
VERIFY_TOKEN earlier? Replace
VERIFY_TOKEN with that value in this code, and
ENDPOINT_URLwith the url of the file from part 1.
$base_url = "https://graph.facebook.com/$app_id/subscriptions"; $url = $base_url . "?access_token=" . $params['access_token']; $fields_string = ''; $fields = array( 'callback_url=ENDPOINT_URL', 'object=user', 'verify_token=VERIFY_TOKEN', 'fields=feed' ); $fields_string = implode("&", $fields); //open connection $ch = curl_init(); //set the url, number of POST vars, POST data curl_setopt($ch,CURLOPT_URL,$url); curl_setopt($ch,CURLOPT_POST,count($fields)); curl_setopt($ch,CURLOPT_POSTFIELDS,$fields_string); //execute post $result = curl_exec($ch); //close connection curl_close($ch);
Once you visit this page successfully, Facebook will call the callback_url defined, verify that the
VERIFY_TOKEN in both parts match, and then start sending Real-time Updates to your endpoint.
That was easy.
*By the time you find this post and need help, you can either learn from my example code or, more likely, bang your head against a wall once you realize Facebook has changed its API once again.