Facebook 在其新文档中解释了 2020 年 10 月后获取用户图像的新方法here https://developers.facebook.com/docs/graph-api/reference/user/picture/他们声明了所需的更改如下:
此端点支持应用程序范围的用户 ID (ASID)、用户 ID (UID) 和页面范围的用户 ID (PSID)。目前您可以无要求地查询 ASID 和 UID。但是,从 2020 年 10 月 24 日开始,所有基于 UID 的查询都需要访问令牌。如果您查询 UID,因此必须包含令牌:
1. 获得一个access_token
以 Facebook 为您提供的任何形式
根据您的应用程序结构,您可以使用 Facebook 提供的以下方法之一来获得access_token
。您可以找到更多关于access_token
在 FB 文档上here https://developers.facebook.com/docs/facebook-login/access-tokens.
应用程序访问令牌 https://developers.facebook.com/docs/facebook-login/access-tokens#apptokens
客户端访问令牌 https://developers.facebook.com/docs/facebook-login/access-tokens#clienttokens
作为我正在使用的客户端访问令牌的示例:
发出 GET 请求https://graph.facebook.com/oauth/access_token
具有以下参数:
[
"client_id" => #FACEBOOK_CLIENT_ID,
"client_secret" => #FACEBOOK_CLIENT_SECRET,
"grant_type" => "client_credentials",
]
作为回应你会得到你的access_token
您需要将其附加到新的图像 URL 上。
2. 获取完整头像 URLaccess_token
随附的。
截至 2020 年 10 月 23 日,这对我有用。
现在是完整图像格式
{$this->graphUrl}/{$this->version}/{$userID}/picture?type=large&redirect=false&access_token={$access_token}
如果你设置redirect=false
您将得到一个 JSON 对象作为响应:
{
"data": {
"height": 100,
"is_silhouette": false,
"url": "https://platform-lookaside.fbsbx.com/platform/profilepic/?asid=10152700727498624&height=100&width=100&ext=1606081666&hash=AeTQyGgugiSbRcB7Sxw",
"width": 100
}
}
另一方面,如果你离开redirect=true
或者根本不设置它,您将获得图像本身,然后可以将其保存在磁盘上或使用 url 作为图像路径。但我不确定给定的 URL 是否长期存在。我现在使用相同的 URL 已经工作了近一周,所以我认为一旦您使用有效的 access_token 请求该 URL,该 URL 将保持原样。
PHP 中的请求示例
由于我已经在 PHP 中实现了这一点,所以我无法为您提供示例代码,但会向您展示我在 Laravel 框架内使用 Guzzle 客户端完成此操作的方式。你可以看看我升级后的 Laravel Socialite Provider 类here https://gist.github.com/Gkiokan/6869accc9bd952ec3654f0570cebf7aa.
public function getAccessToken(){
// Make a request to get the Access Client
$res = Http::get("https://graph.facebook.com/oauth/access_token", [
"client_id" => config('services.facebook.client_id'),
"client_secret" => config('services.facebook.client_secret'),
"grant_type" => "client_credentials",
]);
// Response is a JSON Object, so decode it into an Array
$r = $res->json();
// Return the access_token Array Key out of the response
return Arr::get($r, 'access_token', false);
}
public function getFacebookAvatar(array $user){
// get the access_token from the above method
$access_token = $this->getAccessToken();
// build the new URI path for the User Image
$path = "{$this->graphUrl}/{$this->version}/{$userID}/picture?type=large&redirect=false&access_token={$access_token}";
$res = Http::get($path);
// Get the final User Image URL out of the response
return Arr::get($res->json(), 'data.url', false);
}
构建自己的访问令牌的快速而肮脏的方法(不推荐)
有一种方法可以构建您自己的access_token
但这应该仅用于测试目的,因为您提供了完整的凭据并且可能会被劫持。您可以通过使用您的凭据和|
作为这种格式的分隔符:{cliend_id}|{client_secret}
.