如何在 laravel 中通过 Guzzle 从 Facebook 获取电子邮件?

How to get email from facebook through Guzzle in laravel?

我在 laravel 中使用以下代码通过 Facebook 登录。

推荐 https://scotch.io/tutorials/token-based-authentication-for-angularjs-and-laravel-apps for token based authentication and using https://github.com/sahat/satellizer 进行社交媒体整合。

$params = [
        'code' => $request->input('code'),
        'client_id' => $request->input('clientId'),
        'redirect_uri' => $request->input('redirectUri'),
        'client_secret' => 'XXXXXXXXXXXXXXXXXXX'
        /*'client_secret' => Config::get('app.facebook_secret')*/
    ];

    // Step 1. Exchange authorization code for access token.
    $accessTokenResponse = $client->request('GET', 'https://graph.facebook.com/v2.5/oauth/access_token', [
        'query' => $params
    ]);
    $accessToken = json_decode($accessTokenResponse->getBody(), true);

    // Step 2. Retrieve profile information about the current user.
    $profileResponse = $client->request('GET', 'https://graph.facebook.com/v2.5/me', [
        'query' => $accessToken
    ]);
    $profile = json_decode($profileResponse->getBody(), true);

$profile 仅返回 fb id 和用户名。 我应该做哪些更改才能从 Facebook 接收电子邮件。

替换为:

'https://graph.facebook.com/v2.5/me'

有了这个:

'https://graph.facebook.com/v2.5/me?fields=name,email'

它叫做 "Declarative Fields",请参阅更新日志。

另外,当然需要授权email权限。并且必须确认电子邮件。您不能 100% 确定会收到电子邮件,有些用户使用他们的 phone 号码登录。

你也应该看看这个:https://github.com/sahat/satellizer/issues/615

在第 2 步中使用以下代码。

$fields = 'id,email,first_name,last_name,link,name';
$profileResponse = $client->request('GET', 'https://graph.facebook.com/v2.5/me', [
'query' => [
    'access_token' => $accessToken['access_token'],
    'fields' => $fields
]
]);