如何使用FirebaseAuth从Google供应商获取性别和生日?

威廉

我正在尝试使用Firebase AuthUI从Google提供程序获取性别和生日。这是我的代码。

AuthUI.IdpConfig googleIdp = new AuthUI.IdpConfig.Builder(AuthUI.GOOGLE_PROVIDER)
                .setPermissions(Arrays.asList(Scopes.EMAIL, Scopes.PROFILE, Scopes.PLUS_ME))
                .build();

startActivityForResult(
                AuthUI.getInstance().createSignInIntentBuilder()
                        .setLogo(R.drawable.firebase_auth_120dp)
                        .setProviders(Arrays.asList(
                new AuthUI.IdpConfig.Builder(AuthUI.EMAIL_PROVIDER).build(),
                googleIdp))
                        .setIsSmartLockEnabled(false)
                        .setTheme(R.style.AppTheme_Login)
                        .build(),
                RC_SIGN_IN);

在onActivityResult中:

IdpResponse idpResponse = IdpResponse.fromResultIntent(data);

我知道了idpResponse,但是它只包括idpSecretidpToken如何访问个人资料的其他要求字段,例如性别和生日?我可以使用以下方式访问常见字段的电子邮件,姓名,照片等

FirebaseAuth.getInstance().getCurrentUser();
沙比

Firebase不支持该功能,但是您可以通过以下方式实现:

首先,您需要client_idclient_secret

您可以按照以下步骤从Firebase面板中获得这两个:

身份验证>>登录方法点击Google并展开Web SDK配置

Gradle依赖项:

compile 'com.google.apis:google-api-services-people:v1-rev63-1.22.0'

在登录活动中添加以下方法。

    private void setupGoogleAdditionalDetailsLogin() {
                // Configure sign-in to request the user's ID, email address, and basic profile. ID and
                // basic profile are included in DEFAULT_SIGN_IN.
                GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                        .requestEmail()
                        .requestIdToken(GOOGLE_CLIENT_ID)
                        .requestServerAuthCode(GOOGLE_CLIENT_ID)
                        .requestScopes(new Scope("profile"))
                        .build();

        // Build a GoogleApiClient with access to GoogleSignIn.API and the options above.
                mGoogleApiClient = new GoogleApiClient.Builder(this)
                        .enableAutoManage(this, new GoogleApiClient.OnConnectionFailedListener() {
                            @Override
                            public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
                                Log.d(TAG, "onConnectionFailed: ");
                            }
                        })
                        .addApi(Auth.GOOGLE_SIGN_IN_API, gso)
                        .build();
            }

     public void googleAdditionalDetailsResult(Intent data) {
            Log.d(TAG, "googleAdditionalDetailsResult: ");
            GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
            if (result.isSuccess()) {
                // Signed in successfully
                GoogleSignInAccount acct = result.getSignInAccount();
                // execute AsyncTask to get data from Google People API
                new GoogleAdditionalDetailsTask().execute(acct);
            } else {
                Log.d(TAG, "googleAdditionalDetailsResult: fail");
                startHomeActivity();
            }
        }

    private void startGoogleAdditionalRequest() {
            Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
            startActivityForResult(signInIntent, RC_SIGN_GOOGLE);
        }

异步任务以获取更多详细信息

public class GoogleAdditionalDetailsTask extends AsyncTask<GoogleSignInAccount, Void, Person> {
        @Override
        protected Person doInBackground(GoogleSignInAccount... googleSignInAccounts) {
            Person profile = null;
            try {
                HttpTransport httpTransport = new NetHttpTransport();
                JacksonFactory jsonFactory = JacksonFactory.getDefaultInstance();

                //Redirect URL for web based applications.
                // Can be empty too.
                String redirectUrl = "urn:ietf:wg:oauth:2.0:oob";

                // Exchange auth code for access token
                GoogleTokenResponse tokenResponse = new GoogleAuthorizationCodeTokenRequest(
                        httpTransport,
                        jsonFactory,
                        GOOGLE_CLIENT_ID,
                        GOOGLE_CLIENT_SECRET,
                        googleSignInAccounts[0].getServerAuthCode(),
                        redirectUrl
                ).execute();

                GoogleCredential credential = new GoogleCredential.Builder()
                        .setClientSecrets(GOOGLE_CLIENT_ID, GOOGLE_CLIENT_SECRET)
                        .setTransport(httpTransport)
                        .setJsonFactory(jsonFactory)
                        .build();

                credential.setFromTokenResponse(tokenResponse);

                People peopleService = new People.Builder(httpTransport, jsonFactory, credential)
                        .setApplicationName(App.getInstance().getString(R.string.app_name))
                        .build();

                // Get the user's profile
                profile = peopleService.people().get("people/me").execute();
            } catch (IOException e) {
                Log.d(TAG, "doInBackground: " + e.getMessage());
                e.printStackTrace();
            }
            return profile;
        }

        @Override
        protected void onPostExecute(Person person) {
            if (person != null) {
                if (person.getGenders() != null && person.getGenders().size() > 0) {
                    profileGender = person.getGenders().get(0).getValue();
                }
                if (person.getBirthdays() != null && person.getBirthdays().get(0).size() > 0) {
//                    yyyy-MM-dd
                    Date dobDate = person.getBirthdays().get(0).getDate();
                    if (dobDate.getYear() != null) {
                        profileBirthday = dobDate.getYear() + "-" + dobDate.getMonth() + "-" + dobDate.getDay();
                        profileYearOfBirth = DateHelper.getYearFromGoogleDate(profileBirthday);
                    }
                }
                if (person.getBiographies() != null && person.getBiographies().size() > 0) {
                    profileAbout = person.getBiographies().get(0).getValue();
                }
                if (person.getCoverPhotos() != null && person.getCoverPhotos().size() > 0) {
                    profileCover = person.getCoverPhotos().get(0).getUrl();
                }
                Log.d(TAG, String.format("googleOnComplete: gender: %s, birthday: %s, about: %s, cover: %s", profileGender, profileBirthday, profileAbout, profileCover));
            }
            startHomeActivity();
        }
    }

像这样更改您的onActivityResult:

@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == RC_SIGN_GOOGLE) {    // result for addition details request
            googleAdditionalDetailsResult(data);
            return;
        } else if (requestCode == RC_SIGN_IN && resultCode == RESULT_OK) {  //logged in with firebase
            if (FirebaseAuth.getInstance().getCurrentUser().getProviders().get(0).equals("google.com")) {
            // user logged in with google account using firebase ui
                startGoogleAdditionalRequest();
            } else {
            // user logged in with google
                startHomeActivity();
            }
        } else {
            // handle error
        }
    }

更新:如果代码给出错误

personFields掩码为必填项

然后使用以下代码:

profile = peopleService.people().get("people/me"). setRequestMaskIncludeField("person.names,person.emailAddress‌​es,person.genders,pe‌​rson.birthdays").exe‌​cute();

谢谢@AbrahamGharyali。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

如何覆盖供应商服务提供商使用的供应商特征?

Meetup API,如何获取性别和生日

什么是厨师供应商,我如何知道厨师将使用哪个供应商?

获取键盘的供应商和设备ID

如何在Linux上以编程方式获取USB供应商和产品信息?

不建议使用Google Plus API。我如何从requestScopes(Scope(Scopes.PROFILE))获取性别和出生日期

如何使用Go在Google Cloud Functions中使用供应商中的本地存储库

如何从供应商处获取进口包装?

如何使供应商与Google App Engine一起使用?

如何使用 Symfony 3 中供应商文件夹中的 css 和 js 文件?

如何使用Java检测USB供应商ID和产品ID

如何使用 splitChunks 创建多个供应商模块

如何使用javascript或jquery选择供应商前缀?

Rails 5 Javascript 如何使用供应商资产?

如何使用Composer从供应商外部自动加载类?

如何使用anime.js 支持供应商前缀

如何在Laravel中使用供应商类?

如何使用供应商/捆绑目录中安装的宝石

如何在Windows上从USB设备的VID和PID获取供应商名称和产品名称?

如何从Android中的Facebook获取用户性别和生日

Google Guava供应商示例

USB供应商和产品ID

如何检索Java供应商信息

如何搜索供应商名称?

如何更改OEM供应商信息?

使用供应商缓存的Java 8

使用Gulp捆绑供应商文件

获取ADB的制造商供应商ID

获取所有对供应商编号,以便将两个供应商并置

TOP 榜单

热门标签

归档