我从事的一个项目将Facebook页面作为其数据源之一。它周期性地从它导入一些数据,不涉及GUI。然后我们使用一个网络应用程序来显示我们已经拥有的数据。

并非所有信息都是公开的。这意味着我必须访问一次数据,然后保存它。然而,我不知道这个过程,我还没有找到一个好的教程。我想我需要一个access_token,我怎么能从用户得到它,一步一步?用户是一个facebook页面的管理员,他是否必须添加一些我们的FB应用程序的页面?

编辑:感谢@phwd的提示。我做了一个教程,如何获得一个永久的页面访问令牌,即使offline_access不再存在。

编辑:我刚刚发现它的答案在这里:持久的FB访问令牌服务器拉FB页面信息


如果只请求页数据,则可以使用页访问令牌。您只需授权用户一次即可获得用户访问令牌;将有效期延长到两个月,然后请求该页的令牌。这在场景5中都有解释。请注意,获取的页面访问令牌仅在用户访问令牌有效期间有效。


除了在Vlasec回答中推荐的步骤,您还可以使用:

图形API资源管理器进行查询,例如/{pageId}?= access_token&access_token = THE_ACCESS_TOKEN_PROVIDED_BY_GRAPH_EXPLORER字段 访问令牌调试器以获取有关访问令牌的信息。


按照Facebook扩展页面令牌文档中列出的说明,我能够获得一个不会过期的页面访问令牌。

我建议使用Graph API Explorer完成所有这些步骤,除非另有说明。

0. 创建Facebook应用

如果你已经有一个应用程序,跳到第一步。

进入我的应用程序。 点击“+添加新应用”。 建立一个网站应用程序。

你不需要改变它的权限之类的。你只需要一个应用程序,在你完成访问令牌之前不会消失。

1. 获取用户短期访问令牌

转到图形API资源管理器。 选择你想要获取访问令牌的应用程序(在“应用程序”下拉菜单中,而不是“我的应用程序”菜单中)。 点击“获取令牌”>“获取用户接入令牌”。 在弹出的“扩展权限”选项卡下,选中“manage_pages”。 点击“获取访问令牌”。 授予具有管理目标页面权限的Facebook帐户的访问权限。请注意,如果该用户失去访问权限,最终的、永不过期的访问令牌可能会停止工作。

出现在“访问令牌”字段中的令牌是您的短期访问令牌。

2. 生成长期访问令牌

按照Facebook文档中的这些说明,向

https://graph.facebook.com/v2.10/oauth/access_token?grant_type=fb_exchange_token&client_id= {app_id} client_secret = {app_secret} &fb_exchange_token = {short_lived_token}

输入应用程序的ID和secret以及在前一步中生成的短期令牌。

不能使用图形API资源管理器。由于某种原因,它在这个请求上卡住了。我认为这是因为响应不是JSON,而是一个查询字符串。因为它是一个GET请求,所以您可以直接在浏览器中访问URL。

响应应该是这样的:

{“access_token”:“ABC123”,“token_type”:“持票人”、“expires_in”:5183791}

“ABC123”将是您的长期访问令牌。您可以将其放入访问令牌调试器中进行验证。在“Expires”下面应该有类似“2个月”的内容。

3.获取用户ID

使用长期访问令牌,向

https://graph.facebook.com/v2.10/me?access_token= {long_lived_access_token}

id字段是您的帐户id。下一步将需要它。

4. 获取永久页面访问令牌

发出GET请求

https://graph.facebook.com/v2.10/ {account_id} /账户? access_token = {long_lived_access_token}

JSON响应应该有一个数据字段,下面是用户可以访问的项的数组。找到要从中获得永久访问令牌的页面的项。access_token字段应该有您的永久访问令牌。复制它并在访问令牌调试器中测试它。在“过期”下面应该显示“永不”。


除了上面提到的方法,值得一提的是,对于服务器到服务器的应用程序,你也可以使用这种形式的永久访问令牌: app_id | app_secret 这种类型的访问令牌称为App令牌。它通常可用于调用Graph API并在应用程序后端查询公共节点。 这里提到:https://developers.facebook.com/docs/facebook-login/access-tokens


While getting the permanent access token I followed above 5 steps as Donut mentioned. However in the 5th step while generating permanent access token its returning the long lived access token(Which is valid for 2 months) not permanent access token(which never expires). what I noticed is the current version of Graph API is V2.5. If you trying to get the permanent access token with V2.5 its giving long lived access token.Try to make API call with V2.2(if you are not able to change version in the graph api explorer,hit the API call https://graph.facebook.com/v2.2/{account_id}/accounts?access_token={long_lived_access_token} in the new tab with V2.2) then you will get the permanent access token(Which never expires)


应用程序请求限制达到(#4)- FB API v2.1及更高

这个答案把我引向了“我们的终极答案”,所以它非常相关,所以我把它附加在这里。虽然这与上述内容有关,但它是不同的,facebook似乎简化了这一过程。

当FB将api滚到v 2.1时,我们网站上的共享计数停止工作。在我们的例子中,我们已经有一个FB应用程序,我们没有使用FB登录。所以我们需要做的是获得一个FB APP令牌来发出新的请求。截至2016年8月23日。

Go to: https://developers.facebook.com/tools/explorer Select the api version and then use GET and paste the following: /oauth/access_token?client_id={app-id}&client_secret={app-secret}&grant_type=client_credentials You will want to go grab your app id and your app secret from your app page. Main FB Apps developer page Run the graph query and you will see: { "access_token": "app-id|app-token", "token_type": "bearer" } Where "app-id" and "app-token" will be your app id from your FB app page and the generated FB App HASH you just received. Next go test your new APP access token: FB Access Token tester You should see, by pasting the "app-token" into the token tester, a single app based token without an expiration date/time.

在我们的例子中,我们使用FB js sdk,所以我们改变了我们的调用,就像这样(请注意,这只得到分享计数,而不是分享和评论计数的结合,就像它以前一样):

FB.api(
    '/','GET',{
    // this is our FB app token for our FB app 
        access_token: FBAppToken,
        "id":"{$shareUrl}","fields":"id,og_object{ engagement }"
}

这是现在正常工作。这花费了大量的搜索和FB的官方错误报告,以确认我们必须开始向FB api发出令牌化请求。顺便说一句,我确实要求他们(FB)在错误代码(#4)中添加一条提到标记化请求的线索。

我刚从我们的一个开发人员那里得到另一份报告,说我们的FB评论计数也破了,因为需要新的标记化请求,所以我会相应地更新。


我尝试了这些步骤: https://developers.facebook.com/docs/marketing-api/access#graph-api-explorer

获取永久页面访问令牌

进入图形API资源管理器 在应用程序中选择你的应用程序 将长寿命访问令牌粘贴到access token中 在“访问令牌”旁边,选择要为其设置访问令牌的页面。访问令牌显示为一个新字符串。 单击i查看此访问令牌的属性 再次点击“打开访问令牌工具”按钮,打开“访问令牌调试器”工具,检查属性

一个提示,它只适用于我的网页语言是英语。


我做了一个PHP脚本,使它更容易。创建一个应用程序。在Graph API资源管理器中选择你的应用程序,并获得具有manage_pages和publish_pages权限的用户令牌。在关于页面的底部找到页面的ID。填写配置变量并运行脚本。

<?php
$args=[
    'usertoken'=>'',
    'appid'=>'',
    'appsecret'=>'',
    'pageid'=>''
];

echo generate_token($args);

function generate_token($args){
    $r=json_decode(file_get_contents("https://graph.facebook.com/v2.8/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.8/me?access_token={$longtoken}")); // get user id
    $userid=$r->id;
    $r=json_decode(file_get_contents("https://graph.facebook.com/v2.8/{$userid}/accounts?access_token={$longtoken}")); // get permanent token
    foreach($r->data as $d) if($d->id==$args['pageid']) return $d->access_token;
}

以下是我的解决方案,只使用图形API资源管理器和访问令牌调试器:

Graph API Explorer: Select your App from the top right dropdown menu Select "Get User Access Token" from dropdown (right of access token field) and select needed permissions Copy user access token Access Token Debugger: Paste copied token and press "Debug" Press "Extend Access Token" and copy the generated long-lived user access token Graph API Explorer: Paste copied token into the "Access Token" field Make a GET request with "PAGE_ID?fields=access_token" Find the permanent page access token in the response (node "access_token") (Optional) Access Token Debugger: Paste the permanent token and press "Debug" "Expires" should be "Never"

(API版本2.9-2.11,3.0-3.1测试)


另一个PHP答案使生活更简单。更新为Facebook Graph API 2.9。把它装满,装上。

<?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;
}
?>

附录(备选):

从图2.9开始,在调试了短访问令牌之后,只需单击访问令牌调试器工具底部的扩展访问令牌,就可以跳过获取长访问令牌的许多麻烦。掌握了pageid和longlivetoken的信息后,运行下面的php以获得永久访问令牌。

<?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 --*/
    'longlivedtoken'=>'',
    '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/{$args['pageid']}?fields=access_token&access_token={$args['longlivedtoken']}"));
return $r->access_token;
}
?>

尽管第二个代码为您节省了很多麻烦,但我建议运行第一个php代码,除非您非常着急,因为它会交叉检查pageid和userid。如果您错误地选择了user令牌,则第二个代码将无法工作。

感谢dw1和Rob


很多例子都不起作用,不确定是不是因为2.9v的电压,但我撞到了头。无论如何,我采用了@dw1版本,并在@KFunk视频的帮助下对其进行了一些修改,并以2.9的价格让它为我工作。希望这能有所帮助。

$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/{$args['pageid']}?fields=access_token&access_token={$longtoken}")); // get user id
    $finaltoken=$r->access_token;
    return $finaltoken;
}

我找到了这个答案,它指的是这个工具,它真的很有用。

我希望当你读到这篇文章时,这个答案仍然有效。


多亏了@donut,我设法在JavaScript中获得了永不过期的访问令牌。

// Initialize exchange
fetch('https://graph.facebook.com/v3.2/oauth/access_token?grant_type=fb_exchange_token&client_id={client_id}&client_secret={client_secret}&fb_exchange_token={short_lived_token}')
.then((data) => {
    return data.json();
})
.then((json) => {
    // Get the user data
    fetch(`https://graph.facebook.com/v3.2/me?access_token=${json.access_token}`)
    .then((data) => {
        return data.json();
    })
    .then((userData) => {
        // Get the page token
        fetch(`https://graph.facebook.com/v3.2/${userData.id}/accounts?access_token=${json.access_token}`)
        .then((data) => {
            return data.json();
        })
        .then((pageToken) => {
            // Save the access token somewhere
            // You'll need it at later point
        })
        .catch((err) => console.error(err))
    })
    .catch((err) => console.error(err))
})
.catch((err) => {
    console.error(err);
})

然后我像这样使用保存的访问令牌

fetch('https://graph.facebook.com/v3.2/{page_id}?fields=fan_count&access_token={token_from_the_data_array}')
.then((data) => {
    return data.json();
})
.then((json) => {
    // Do stuff
})
.catch((err) => console.error(err))

我希望有人能修改这段代码,因为它有点乱,但这是我能想到的唯一方法。


如果你有facebook的应用,那么你可以尝试app-id和app-secret。

如:

access_token={your-app_id}|{your-app_secret}

它不需要频繁地更改令牌。


截至2020年4月,我之前的永久页面令牌开始在1到12小时内到期。我开始使用具有manage_pages权限的用户令牌来实现前面的目标(轮询页面的事件)。这些代币似乎是永久的。

我根据这篇文章中找到的信息创建了一个python脚本,托管在github.com/k-funk/facebook_permanent_token上,以跟踪需要哪些参数,以及获取永久令牌的方法是有效的。


由于所有早期的答案都是旧的,并且由于facebook的政策不断变化,其他提到的答案可能不适用于永久代币。

经过大量的调试,我能够获得永不过期令牌使用以下步骤:

图形API浏览器:

Open graph api explorer and select the page for which you want to obtain the access token in the right-hand drop-down box, click on the Send button and copy the resulting access_token, which will be a short-lived token Copy that token and paste it in access token debugger and press debug button, in the bottom of the page click on extend token link, which will extend your token expiry to two months. Copy that extended token and paste it in the below url with your pageId, and hit in the browser url https://graph.facebook.com/{page_id}?fields=access_token&access_token={long_lived_token} U can check that token in access token debugger tool and verify Expires field , which will show never.

这是它


我根据donut的回答创建了一个小的NodeJS脚本。将以下文件存储在名为get-facebook-access-token.js的文件中:

const fetch = require('node-fetch');
const open = require('open');

const api_version = 'v9.0';
const app_id = '';
const app_secret = '';
const short_lived_token = '';
const page_name = '';

const getPermanentAccessToken = async () => {
  try {
    const long_lived_access_token = await getLongLivedAccessToken();
    const account_id = await getAccountId(long_lived_access_token);
    const permanent_page_access_token = await getPermanentPageAccessToken(
      long_lived_access_token,
      account_id
    );
    checkExpiration(permanent_page_access_token);
  } catch (reason) {
    console.error(reason);
  }
};

const getLongLivedAccessToken = async () => {
  const response = await fetch(
    `https://graph.facebook.com/${api_version}/oauth/access_token?grant_type=fb_exchange_token&client_id=${app_id}&client_secret=${app_secret}&fb_exchange_token=${short_lived_token}`
  );
  const body = await response.json();
  return body.access_token;
};

const getAccountId = async (long_lived_access_token) => {
  const response = await fetch(
    `https://graph.facebook.com/${api_version}/me?access_token=${long_lived_access_token}`
  );
  const body = await response.json();
  return body.id;
};

const getPermanentPageAccessToken = async (
  long_lived_access_token,
  account_id
) => {
  const response = await fetch(
    `https://graph.facebook.com/${api_version}/${account_id}/accounts?access_token=${long_lived_access_token}`
  );
  const body = await response.json();
  const page_item = body.data.find(item => item.name === page_name);  
  return page_item.access_token;
};

const checkExpiration = (access_token) => {
  open(`https://developers.facebook.com/tools/debug/accesstoken/?access_token=${access_token}&version=${api_version}`);
}

getPermanentAccessToken();

填入常量,然后运行:

npm install node-fetch
npm install open
node get-facebook-access-token.js

运行脚本后,浏览器中会打开一个页面,显示令牌及其有效期。


上面的大多数答案现在都没有给出永久代币,他们只延长到2个月。我是这样得到它的:

从图形资源管理器工具中,选择相关权限并获得短时间页面访问令牌。 转到调试器工具并粘贴您的访问令牌。然后,单击页面底部的“扩展令牌”按钮。 复制扩展的令牌并在这个API中使用它: https://graph.facebook.com/v2.10/me?fields=access_token&access_token= < extended_access_token > 这将返回永久访问令牌。你可以在调试器工具中验证,expires at字段应该说“Never”。