Tuesday, April 25, 2017

How to get permanent access token in Facebook Graph API 2.9

Fill the appropriate args and then run this php file to generate a permanent access token. This is the latest method(Referenced from SO) and it'll work until a new Graph API is released sometime around next year.
<?php
$args=[
/*-- Permanent access token generator for Facebook Graph API version 2.9 --*/
//Instructions: Fill Input Area below and then run this php file
/*-- INPUT AREA START --*/
    'usertoken'=>'',
    'appid'=>'',
    'appsecret'=>'',
    'pageid'=>''
/*-- INPUT AREA END --*/
];
echo 'Permanent access token is: <input type="text" value="'.generate_token($args).'"></input>';
function generate_token($args){
    $r=json_decode(file_get_contents("https://graph.facebook.com/v2.9/oauth/access_token?grant_type=fb_exchange_token&client_id={$args['appid']}&client_secret={$args['appsecret']}&fb_exchange_token={$args['usertoken']}")); // get long-lived token
    $longtoken=$r->access_token;
    $r=json_decode(file_get_contents("https://graph.facebook.com/v2.9/me?access_token={$longtoken}")); // get user id
    $userid=$r->id;
    $r=json_decode(file_get_contents("https://graph.facebook.com/v2.9/{$userid}?fields=access_token&access_token={$longtoken}")); // get permanent token
    if($r->id==$args['pageid']) $finaltoken=$r->access_token;
    return $finaltoken;
}
?>

0 comments

Post a Comment