如何通过Google GSI在Gmail注册时获取用户性别?
如何通过Gmail登录获取用户性别信息
你当前拿到的ID Token里不包含性别字段,因为Google默认不会把性别数据放在ID Token中。要获取用户性别,需要完成以下两步:
1. 扩展登录请求的权限范围(Scope)
在初始化Google Sign-In时,需要添加包含用户个人信息的权限范围,比如profile(涵盖基本个人信息)或者更精准的user.gender.read。修改你的代码,在初始化时指定scope:
scriptGSI.then(() => { window.google.accounts.id.initialize({ client_id: '你的Google客户端ID', // 替换成你的实际客户端ID scope: 'email profile', // 添加profile scope以获取个人信息权限 callback: handleCredentialResponse }); // 渲染登录按钮 window.google.accounts.id.renderButton( document.getElementById('g_id_signin'), { theme: 'outline', size: 'large' } ); });
2. 调用Google API获取性别信息
拿到ID Token后,用它作为授权凭证,调用Google的用户信息API或者People API来获取性别:
方法一:调用OAuth2用户信息接口
这个接口返回的信息比较简洁,包含性别字段:
function handleCredentialResponse(response) { const idToken = response.credential; // 调用用户信息接口 fetch('https://www.googleapis.com/oauth2/v3/userinfo', { headers: { 'Authorization': `Bearer ${idToken}` } }) .then(res => res.json()) .then(userData => { // 性别字段为gender,可能的值:male/female/other,若用户未设置则不存在 const userGender = userData.gender; console.log('用户性别:', userGender); // 这里处理你的业务逻辑 }) .catch(err => console.error('获取用户信息失败:', err)); }
方法二:调用People API(更精准)
如果只需要性别信息,可以调用People API的指定字段接口,减少返回数据量:
function handleCredentialResponse(response) { const idToken = response.credential; fetch('https://people.googleapis.com/v1/people/me?personFields=genders', { headers: { 'Authorization': `Bearer ${idToken}` } }) .then(res => res.json()) .then(data => { if (data.genders && data.genders.length > 0) { const gender = data.genders[0].value; console.log('用户性别:', gender); } else { console.log('用户未设置公开的性别信息'); } }) .catch(err => console.error('获取性别失败:', err)); }
注意事项
- 确保你的Google Cloud项目已启用People API(如果用方法二),可以在Google Cloud控制台的API库中搜索启用。
- 在OAuth同意屏幕设置中,添加你使用的权限范围,用户登录时会看到对应的授权提示,只有用户同意后才能获取到性别信息。
- 若用户未在Google账户中设置性别或未公开性别信息,接口会返回空值,需要处理这种情况。
内容的提问来源于stack exchange,提问作者Naruto Uzumaki
相关产品推荐
相关产品推荐

