Third & GroveThird & Grove
Jan 5, 2017 - Ed Hornig

How to sync Facebook Live videos with your website

Facebook Live is a powerful and easy-to-use video live streaming service - part of a trend towards realtime self publication. Facebook is heavily pushing their new service with advertising in the hopes of compete with others in the same space like Snapchat and Instagram.

Here we show you how to sync your live Facebook videos on your website using PHP, so that the videos will automatically appear whenever they are created.

Authenticate with Facebook

First you’ll need to create a new Facebook app. Fill out the basic settings for your app and then click the “Add Product” link and add the “Facebook Login” product. Add the redirect URL here that Facebook will callback to on your site when you attempt to authenticate from the website.

Next install Facebook SDK v5 for PHP in your code. Using the SDK, it’s easy to create an authentication link. See the official Facebook login example for more documentation.

/login.php
$api_settings = array(
'app_id' => [YOUR APP ID],
'app_secret' => [YOUR APP SECRET],
'default_graph_version' => 'v2.8',
);
$fb = new Facebook\Facebook($api_settings);
$helper = $fb->getRedirectLoginHelper();
$permissions = ['manage_pages'];
$loginUrl = $helper->getLoginUrl(“https://www.example.com/fb-callback.php", $permissions);

 

The ‘manage_pages’ permission will be needed to access the live_videos endpoint of the FB Graph API. Note that this means an administrator of the FB page with the live videos will need to authenticate the FB app on your website.

The code for the callback url (https://www.example.com/fb-callback.php) should follow the example given in the FB documentation. In addition, you will want to save the long-lived access token to the database. Here we'll do that with the drupal function variable_set().

variable_set('fb_access_token', $access_token);

 

Receiving API updates in real time with webhooks

Creating a webhook subscription allows our website to be informed in realtime whenever there is a new Live Video.

Go to your FB app and add a new ‘Product’, ‘Webhooks’. In the GUI, you’ll need to choose a callback url (subscribe-callback.php) and the fields to monitor (live_videos). You’ll also need a token which is the 'fb_access_token' saved above.

Let’s edit the code in /login.php to render the authentication link, check for the long-lived access token, and get the page access token. You’ll need the page access token to subscribe to the FB page.

/login.php
$api_settings = array(
'app_id' => [YOUR APP ID],
'app_secret' => [YOUR APP SECRET],
'default_graph_version' => 'v2.8',
);
$fb = new Facebook\Facebook($api_settings);
$helper = $fb->getRedirectLoginHelper();
$_SESSION['FBRLH_state'] = $_GET['state'];
$permissions = ['manage_pages']; // Optional permissions
$loginUrl = $helper->getLoginUrl($base_url . "/facebook/callback/login", $permissions);
$fb_access_token = variable_get('fb_access_token');
if (empty($fb_access_token)) {
$markup = t('Facebook is not authenticated. ');
$markup .= l(t('Authenticate with Facebook!'), $loginUrl) ;
return $markup;
}
$fb->setDefaultAccessToken($fb_access_token);
// Get page access Token.
$page_id = '<YOUR FB PAGE ID>';
$page_access_token_response = json_decode($fb->get("$page_id?fields=access_token")->getBody());

 

Now let’s subscribe to the FB page using the FB Graph API.

$fb->setDefaultAccessToken($page_access_token);
// Create a subscription to the FB page.
$subscribe = json_decode($fb->post("$page_id/subscribed_apps")->getBody());
$subscriptions = json_decode($fb->get("$page_id/subscribed_apps")->getBody());

 

Check the contents of $subscriptions to make sure you have successfully subscribed.

Before you can successfully subscribe, you’ll need to set up the /subscribe-callback.php callback to accept and validate the FB callback.

/subscribe-callback.php
if (isset($_GET['hub_mode'])) {
$verification_token = $_GET['hub_verify_token'];
$challenge = $_GET['hub_challenge'];
$mode = $_GET['hub_mode'];
}
if ($mode === 'subscribe') {
drupal_add_http_header('Content-Type', 'application/json');
echo $challenge;
return;
}

 

Now execute /login.php and check to see that you have created the subscription.

Assuming we are subscribed, whenever someone makes a change to a live video on FB, FB will ping the subscription callback url informing us of the change. Specifically, FB will send a POST request with a body of json, like so:

{
"entry": [{
"changes": [{
"field": "live_videos",
"value": {
"status": "live",
"id": 1249048395127179
}
}],
"id": "480269095393980",
"time": 1483548671
}],
"object": "page"
}

 

In this case we are being informed that the live_video with id 1249048395127179 has just gone ‘live’.

Let’s add code to the subscription callback to handle such a POST request.

/subscribe-callback.php
// Handle FB webhook post request.
$post = file_get_contents('php://input');
if (!empty($post)) {
watchdog('facebook_graph_api_callback_subscription post', $post);
$post = json_decode($post, false, 512, JSON_BIGINT_AS_STRING);
$items = $post->entry;
foreach ($items as $item) {
$changes = $item->changes;
foreach ($changes as $change) {
if (strtolower($change->field) != 'live_videos') {
break;
}
$value = $change->value;
$status = $value->status;
if (strtolower($status) != 'live') {
break;
}
$id = $value->id;
break 2;
}
}
if (isset($id)) {
watchdog('facebook_graph_api_callback_subscription id', $id);
facebook_graph_api_get_videos($id);
}
}

 

This code reads the information FB is sending us and grabs the id of a video that has just gone ‘live’ if there is one. Then it calls a custom function do_something() with the video id as the argument.

Now that we have the FB video id, we can save it to our database and render it on the page using FB’s embedded video code snippets.