Laravel Social获取Google、Facebook及Twitter的性别与DOB问题
嘿,我来帮你搞定Laravel Socialite获取性别和出生日期的问题!不同平台的设置和API调用方式略有不同,我分平台给你详细拆解:
Facebook 获取性别与出生日期
- 首先得调整你的Facebook应用权限:登录Facebook开发者后台,找到你的应用后,进入「产品」->「Facebook登录」->「设置」,先确保「登录后的重定向URI」和你Laravel项目里的配置一致。接着去「应用审核」->「权限与功能」,申请
user_gender和user_birthday权限——提醒下,现在Facebook对这类隐私权限审核挺严的,你得明确说明这些数据的使用场景哦。 - 然后在Laravel里给Socialite添加对应的scopes:
在你处理登录跳转的控制器方法里,修改成这样:return Socialite::driver('facebook') ->scopes(['email', 'user_gender', 'user_birthday']) ->redirect(); - 最后获取用户数据时,就能直接从返回的数组里拿到性别和生日了:
$user = Socialite::driver('facebook')->user(); // 提取性别 $gender = $user->user['gender']; // 提取出生日期 $birthday = $user->user['birthday'];
Google 获取性别与出生日期
- 注意啦,Google Plus API已经被弃用了,现在得用Google People API。先去Google Cloud控制台,给你的项目启用「People API」。
- 接下来配置OAuth同意屏幕,添加
https://www.googleapis.com/auth/user.birthday.read和https://www.googleapis.com/auth/user.gender.read这两个权限,确保用户授权时能看到这些权限说明。 - 然后在Laravel里设置Socialite的scopes:
return Socialite::driver('google') ->scopes([ 'email', 'profile', 'https://www.googleapis.com/auth/user.birthday.read', 'https://www.googleapis.com/auth/user.gender.read' ]) ->redirect(); - 这里要注意,Socialite默认不会返回性别和生日,得额外调用People API获取:
$googleUser = Socialite::driver('google')->user(); $client = new \GuzzleHttp\Client(); $response = $client->get('https://people.googleapis.com/v1/people/me?personFields=genders,birthdays', [ 'headers' => [ 'Authorization' => 'Bearer ' . $googleUser->token, ], ]); $userData = json_decode($response->getBody(), true); // 处理性别(做个空值判断,避免用户没设置时报错) $gender = $userData['genders'][0]['value'] ?? null; // 处理出生日期(返回的是包含年/月/日的数组,按需格式化) $birthday = $userData['birthdays'][0]['date'] ?? null;
Twitter 获取性别与出生日期
- Twitter的限制会多一点:首先你的开发者应用得申请elevated access权限,而且用户必须公开了性别和出生日期,你才能拿到这些数据。
- 先去Twitter开发者平台,给你的应用申请elevated access,然后在「Project & Apps」->「Permissions and features」里确保权限至少是「Read」,并且配置好「User authentication settings」。
- 然后在Laravel里设置Socialite的scopes:
return Socialite::driver('twitter') ->scopes(['users.read']) ->redirect(); - 最后调用Twitter的API获取用户详情:
$twitterUser = Socialite::driver('twitter')->user(); $client = new \GuzzleHttp\Client(); $response = $client->get('https://api.twitter.com/2/users/' . $twitterUser->id . '?user.fields=gender,birth_date', [ 'headers' => [ 'Authorization' => 'Bearer ' . $twitterUser->token, ], ]); $userData = json_decode($response->getBody(), true); // 提取性别 $gender = $userData['data']['gender'] ?? null; // 提取出生日期(格式为YYYY-MM-DD) $birthDate = $userData['data']['birth_date'] ?? null;
通用提醒
- 不管哪个平台,用户都可以选择不公开性别或出生日期,所以你的代码一定要做好空值判断,避免出现数组越界或者变量未定义的错误。
- 各个平台的隐私政策都很严格,申请权限时一定要如实说明数据用途,不然可能通不过审核哦。
内容的提问来源于stack exchange,提问作者Sagar Shinde
相关产品推荐
相关产品推荐

