FACEBOOK API:如何从PHP API获取长期访问令牌

问题描述 投票:1回答:1

我的问题:如何从PHP API获取长期访问令牌。我已经阅读了有关此问题的所有以前的帖子,但仍然没有答案。基本上,我从API资源管理器获得了一个短暂的访问令牌。随后,我编写了一个简单的PHP程序图,调用了facebook graph API来请求一个长寿的访问令牌。但是,它不起作用。我在这里错过了一些东西。这是我编写的PHP代码的片段:

  $response = $fb->request("GET", "GET /oauth/access_token?  
    grant_type=fb_exchange_token&           
    client_id={my app id}&
    client_secret={my app secret}&
    fb_exchange_token={'the short-lived token obtained from the api 
   explorer'}")
    ..//error checking...
      //

    // then I call this:
    $token = $response->getaccessToken();
   // end of program

事实证明,getaccessToken()返回与我传递给API相同的短期令牌。因此,我正在考虑如何使其工作。

根据API文档,使用输入参数“ fb_exhcnage_token”进行的调用应返回“长期访问令牌”。但是,我不明白。

我是Facebook API的新手。任何帮助都将得到批准,谢谢。

php facebook api access-token
1个回答
0
投票

这在长期令牌成为60天到期后于2019年有效。这是Facebook的说明,用于将短期令牌(前端提供)交换为长期令牌(仅限服务器):

https://developers.facebook.com/docs/facebook-login/access-tokens/refreshing/

Generate a Long-lived User or Page Access Token
You will need the following:

A valid User or Page Access Token
Your App ID
Your App Secret
Query the GET oath/access_token endpoint.

curl -i -X GET "https://graph.facebook.com/{graph-api-version}/oauth/access_token?  
    grant_type=fb_exchange_token           
    client_id={app-id}&
    client_secret={app-secret}&
    fb_exchange_token={your-access-token}" 

Sample Response
{
  "access_token":"{long-lived-access-token}",
  "token_type": "bearer",
  "expires_in": 5183944            //The number of seconds until the token expires
}

您可以使用curl_init()在PHP中发出该curl请求:

https://www.php.net/manual/en/book.curl.php


或者,如果您更喜欢使用Facebook PHP SDK,则可以执行此操作:

1。)使用您的凭据创建FB请求对象。2.)使用FB对象和访问令牌请求长期令牌

public function createFacebookRequestObject($facebookUser)
    {
        try {
            return new Facebook([
                'app_id' => config('env.FACEBOOK_GRAPH_API_ID'),
                'app_secret' => config('env.FACEBOOK_GRAPH_API_SECRET'),
                'default_graph_version' => 'v4.0',
                'default_access_token' => $facebookUser->access_token
            ]);
        } catch (\Facebook\Exceptions\FacebookSDKException $e) {
            return 'Facebook SDK returned an error: ' . $e->getMessage();
        }
    }

public function fetchLongTermAccessToken($fb, $facebookUser)
        {
            return $fb->get(
                "/oauth/access_token?grant_type=
                fb_exchange_token&fb_exchange_token=" 
              . $facebookUser['access_token']  
                . '&client_id=' 
                . config('env.FACEBOOK_APP_ID'), );
        }
© www.soinside.com 2019 - 2024. All rights reserved.