facebook: permanent Page Access Token?

后端 未结 16 2540
情书的邮戳
情书的邮戳 2020-11-22 02:39

I work on a project that has facebook pages as one of its data sources. It imports some data from it periodically with no GUI involved. Then we use a web app to show the dat

16条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2020-11-22 02:54

    Another PHP answer to make lives easier. Updated for Facebook Graph API 2.9 . Just fill 'er up and load.

    '',
        'appid'=>'',
        'appsecret'=>'',
        'pageid'=>''
    /*-- INPUT AREA END --*/
    ];
    echo 'Permanent access token is: ';
    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;
    }
    ?>
    

    Addendum: (alternative)

    Graph 2.9 onwards , you can skip much of the hassle of getting a long access token by simply clicking Extend Access Token at the bottom of the Access Token Debugger tool, after having debugged a short access token. Armed with information about pageid and longlivedtoken, run the php below to get permanent access token.

    '',
        'pageid'=>''
    /*-- INPUT AREA END --*/
    ];
    echo 'Permanent access token is: ';
    function generate_token($args){
    $r=json_decode(file_get_contents("https://graph.facebook.com/v2.9/{$args['pageid']}?fields=access_token&access_token={$args['longlivedtoken']}"));
    return $r->access_token;
    }
    ?>
    

    Although the second code saves you a lot of hassle, I recommend running the first php code unless you are in a lot of hurry because it cross-checks pageid and userid. The second code will not end up working if you choose user token by mistake.

    Thanks to dw1 and Rob

提交回复
热议问题