How To Generate Facebook Long-Lived Access Token

Have you ever came across API tasks? Then, probably you heard about the ‘Access Token’. The access token is a kind of identity token social websites (Like Facebook) uses to perform operations on the behalf of a user.

In other words, an application with valid access token can fetch your friend list, post on your wall, get your basic details like email, birth date, etc. Of course, you need to allow permission for all those accesses. Without your permission access token can’t access users information.

When talking about Facebook API, their API provides 2 types of tokens: short-lived and long-lived access tokens.

The short-lived token has a short span of a time. That means you can’t give API calls after token expires. You will get the unauthorized response once the token expires. Each API call requires valid access token as a parameter then only they send a response in back.

Once token expired you need to ask the user for go through the login process again using your application.

That does not make sense. It’s kind of doing a repeated process which user do not like actually.

This is where we should use the concept of Long-Lived access token of Facebook. A long-lived token generally lasts about 60 days. And it is much better than using short-lived tokens.

Having said that, let’s see how to generate a Long-Lived access token of Facebook.

Register An Application

To get started, you first need to register an application on Facebook Developers. You will get step by step guide on how to register and configure an app here.

Once you registered the app, copy app id and app secret which we require in a moment.

Facebook App Keys

Generate A Long-Lived Access Token

Now, we have app id and app secret keys. Create a file called config.php and add our keys using PHP define() method.

config.php

<?php
define('CLIENT_ID', 'YOUR_CLIENT_ID');
define('CLIENT_SECRET', 'YOUR_CLIENT_SECRET');
define('REDIRECT_URL', 'YOUR_SITE_URL/redirect.php');
?>

In the above code, we specified REDIRECT_URL to YOUR_SITE_URL/redirect.php. So, create the file redirect.php. This is the file where we will write the code for generating a Long-Lived token.

But before that, we need to create a login URL which redirects a user to the Facebook login page to authorize your app. Create a file login.php and add the below code in it.

login.php

<?php
require_once "config.php";
echo "<a href='https://www.facebook.com/v2.10/dialog/oauth?client_id=" . CLIENT_ID . "&redirect_uri=" . REDIRECT_URL . "'>Login To Facebook</a>";
?>

When a user clicks on the link for Login To Facebook, they will redirect to Facebook login page. Once, they allow permission to your app, the user will redirect to the YOUR_SITE_URL/redirect.php. In return, we get a code as a GET parameter from the Facebook. Using this code value we generate a first short-lived access token. And then through this short-lived token, we generate a Long-Lived access token.

Make sure you have CURL extension enabled on your server else our code will not work as expected.

redirect.php

<?php
require_once "config.php";
 
if (isset($_GET['code']) && !empty($_GET['code'])) {
    $post = ['client_id'=> CLIENT_ID, "redirect_uri" => REDIRECT_URL, "client_secret" => CLIENT_SECRET, 'code' => $_GET['code']];
    $arr_result = getFBResponse($post);
 
    //generate long-lived access token
    if (isset($arr_result->access_token)) {
        $post1 = ['grant_type' => 'fb_exchange_token', 'client_id'=> CLIENT_ID, "client_secret" => CLIENT_SECRET, 'fb_exchange_token' => $arr_result->access_token ];
        $arr_result1 = getFBResponse($post1);
        echo "Long Lived Token: " . $arr_result1->access_token;
    }
}
 
function getFBResponse($arr_post = []) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL,'https://graph.facebook.com/v2.10/oauth/access_token');
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($arr_post));
    $response = curl_exec($ch);
    return json_decode($response);
}
?>

That’s it! We hope you got to know about the process of generating a Long-Lived access token for Facebook API. Please share your thoughts in the comment section below.

If you liked this article, then please subscribe to our YouTube Channel for video tutorials.

Leave a Reply

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