Firebase Unity Facebook登录无法返回/存储用户邮箱问题求助
解决Firebase Facebook登录无法获取用户邮箱的问题
我之前也碰到过一模一样的坑!核心问题在于Facebook OAuth登录的权限机制和Firebase的同步逻辑,咱们一步步拆解解决:
1. 主动从Facebook Graph API拉取邮箱信息
虽然你代码里请求了email权限,但Facebook默认不会在登录成功后主动返回邮箱字段——你得主动调用Graph API去获取这个信息。
修改你的登录回调逻辑,先拉取邮箱再走Firebase登录流程:
public void SignInFacebook() { var perms = new List<string>() { "public_profile", "email", "user_friends" }; FB.LogInWithReadPermissions(perms, AuthCallback); } private void AuthCallback(ILoginResult result) { if (FB.IsLoggedIn) { var aToken = Facebook.Unity.AccessToken.CurrentAccessToken; Debug.Log("User ID: " + aToken.UserId); foreach (string perm in aToken.Permissions) { Debug.Log("Granted permission: " + perm); } // 关键步骤:主动请求Facebook Graph API获取邮箱 FB.API("/me?fields=email", HttpMethod.GET, FetchEmailCallback); } else { Debug.Log("User cancelled login"); } } private void FetchEmailCallback(IGraphResult result) { if (result.Error != null) { Debug.LogError("Failed to get user email from Facebook: " + result.Error); return; } string userEmail = string.Empty; if (result.ResultDictionary.ContainsKey("email")) { userEmail = result.ResultDictionary["email"].ToString(); Debug.Log("Fetched email: " + userEmail); } else { Debug.LogWarning("User didn't grant email access or has no email linked to Facebook"); return; } // 继续Firebase登录并同步邮箱 var aToken = Facebook.Unity.AccessToken.CurrentAccessToken; Credential credential = FacebookAuthProvider.GetCredential(aToken.TokenString); auth.SignInWithCredentialAsync(credential).ContinueWithOnMainThread(task => { if (task.IsCanceled) { Debug.LogError("SignInWithCredentialAsync was canceled."); return; } if (task.IsFaulted) { Debug.LogError("SignInWithCredentialAsync encountered an error: " + task.Exception); return; } Firebase.Auth.FirebaseUser newUser = task.Result; // 如果Firebase用户邮箱为空,手动更新 if (string.IsNullOrEmpty(newUser.Email)) { newUser.UpdateEmailAsync(userEmail).ContinueWithOnMainThread(updateTask => { if (updateTask.IsCanceled || updateTask.IsFaulted) { Debug.LogError("Failed to update Firebase user email: " + updateTask.Exception); } else { Debug.LogFormat("User signed in successfully: {0} - {1} - ({2})", newUser.DisplayName, newUser.Email, newUser.UserId); } }); } else { Debug.LogFormat("User signed in successfully: {0} - {1} - ({2})", newUser.DisplayName, newUser.Email, newUser.UserId); } }); }
2. 排查其他潜在问题
- Facebook权限配置:确认你的Facebook开发者应用中已添加
email权限(测试用户无需审核即可使用,但正式上线需要提交权限审核)。 - 用户隐私设置:部分用户可能在Facebook账号中隐藏了邮箱,或者拒绝了
email权限请求,这种情况要做好空值处理。 - Firebase配置验证:检查Firebase控制台的Facebook登录配置,确保App ID、App Secret与Facebook开发者平台完全一致,且回调URL已正确添加到Facebook应用的OAuth设置中。
为什么其他登录方式正常?
邮箱、谷歌登录本身就是以邮箱为核心身份标识,Firebase会直接从登录凭证中提取并存储邮箱;而Facebook登录是OAuth授权,需要你明确通过Graph API请求email字段,Firebase才会同步(或你手动更新)这个信息。
内容的提问来源于stack exchange,提问作者Mohamed
相关产品推荐
相关产品推荐

