facebook Archives | Codeexecute

Fetch facebook profile data using javascript

fetch Facebook profile data

Facebook is the most popular social networking site. Facebook provides graph api to get data  . We can fetch Facebook profile data using JavaScript also.

<script type="text/javascript">
window.fbAsyncInit = function() {
FB.init({
appId : 'Your Facebook App Id',
cookie : true,
xfbml : true,
version : 'v2.8'
});
};

(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 fbLoginFunction()
{
FB.login(function(response) {
if (response.authResponse)
{
FB.api('/me', 'get', { fields: 'id,name,gender,hometown,email' }, function(response) {
console.log(response);
});
} else {
alert("Login attempt failed!");
}
}, { scope: 'email,user_birthday,user_location,user_hometown,public_profile' });
}
</script>
<a href="javascript:void(0);" onclick="fbLoginFunction();" class="btn btn-primary btn-xl rounded-pill mt-5">Login</a>
 

How to get the fields value from Facebook Token Meta Data Response?

Facebook SDK to Login with Facebook for my Website:
$accessToken = YOUR_ACCESS_TOKEN;
$fb = new Facebook\Facebook([
    'app_id' => fbAppId,
    'app_secret' => fbSecret,
    'default_graph_version' => 'v2.2',
    ]);
$oAuth2Client = $fb->getOAuth2Client(); 
$tokenMetadata = $oAuth2Client->debugToken($accessToken);
echo "<pre>";print_r($tokenMetadata);

By using the above code, I get the following response. How can I get the get the fields value from this array.

Facebook\Authentication\AccessTokenMetadata Object
(
    [metadata:protected] => Array
        (
            [app_id] => APP_ID
            [application] => APP_NAME
            [expires_at] => DateTime Object
                (
                    [date] => 2016-04-09 10:19:12
                    [timezone_type] => 3
                    [timezone] => UTC
                )

            [is_valid] => 1
            [issued_at] => DateTime Object
                (
                    [date] => 2016-02-09 10:19:12
                    [timezone_type] => 3
                    [timezone] => UTC
                )

            [scopes] => Array
                (
                    [0] => email
                    [1] => publish_actions
                    [2] => public_profile
                )

            [user_id] => USER_ID
        )

)

To fetch all of the metadata use below funcation:


$expiresAt = (array)$tokenMetadata->getField('expires_at');//pass fields name

$expiresDate = $expiresAt['date'];