Google +集成使用访问令牌



在我的android应用程序中,我需要集成Google+登录。我已经尝试过这种方法,我可以成功地获得访问令牌。但是我无法在我的访问令牌中获得电子邮件地址,而传入我的web服务。

我在谷歌上搜索了三天,我尝试了很多方法,但没有找到解决问题的方法。我已经尝试了所有的范围,我没有得到电子邮件地址在我的访问令牌。

String mScope = "oauth2:" + Scopes.PLUS_LOGIN + " " + Scopes.PLUS_ME;
String exchangeCode = GoogleAuthUtil.getToken(getApplicationContext(), Plus.AccountApi.getAccountName(mGoogleApiClient), mScope);

这里我得到访问令牌,而不是电子邮件地址在我的令牌

String exchangeCode = GoogleAuthUtil.getToken(
                         SigninScreen.this,
                         Plus.AccountApi.getAccountName(mGoogleApiClient) + "",
                         "oauth2:"
                           + Scopes.PLUS_ME + " "
                           + "https://www.googleapis.com/auth/plus.login" + " "
                           + "https://www.googleapis.com/auth/plus.me" + " "
                           + "https://www.googleapis.com//auth/plus.profile.emails.read" + " "
                           + "https://www.googleapis.com/auth/userinfo.profile");

这里我得到这样的错误

 com.google.android.gms.auth.UserRecoverableAuthException: NeedPermission

by this way also I tried

accessToken = GoogleAuthUtil.getToken(
                                   MainActivity.this,
                                   Plus.AccountApi.getAccountName(mGoogleApiClient) + "",
                                   "oauth2:"
                                     + Scopes.PROFILE + " "
                                     + "https://www.googleapis.com/auth/plus.login" + " "
                                     + "https://www.googleapis.com/auth/plus.profile.emails.read");

我使用这个方法得到错误

Client error response [url] https://www.googleapis.com/plus/v1/people/me?prettyPrint=false [status code] 403 [reason phrase] Forbidden
谁能告诉我我做错了什么?我需要从Google Plus获得访问令牌,并将令牌传递给我的web服务并获得详细信息。

试试这个…

在OnCreate . .

mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this).addApi(Plus.API)
                .addScope(Plus.SCOPE_PLUS_LOGIN).build();

将这三个方法添加到Activity…呼入呼出

 private void signInWithGplus() {
            Log.i("call", "signinwithgoogle");
            mGoogleApiClient.connect();
            if (!mGoogleApiClient.isConnecting()) {
                mSignInClicked = true;
                resolveSignInError();
            }
        }
        private void resolveSignInError() {
            Log.i("call", "resolvesigninerror");
            if (mConnectionResult.hasResolution()) {
                try {
                    mIntentInProgress = true;
                    mConnectionResult.startResolutionForResult(this, RC_SIGN_IN);
                } catch (SendIntentException e) {
                    mIntentInProgress = false;
                    mGoogleApiClient.connect();
                }
            }
        }
        static void signOutFromGplus() {
            Log.i("call", "signoutfromgoogle");
            if (mGoogleApiClient.isConnected()) {
                Plus.AccountApi.clearDefaultAccount(mGoogleApiClient);
                mGoogleApiClient.disconnect();
                // Toast.makeText(getApplicationContext(), "sign out from google",
                // Toast.LENGTH_SHORT).show();
                storeUserData.setBoolean(AppConstants.KEY_IS_LOGIN, false);
                updateUI(false);
            }
        }

还添加到身份验证。通过这种方法,您将获得整个配置文件信息:

 private void getProfileInformation() {
            try {
                if (Plus.PeopleApi.getCurrentPerson(mGoogleApiClient) != null) {
                    Person currentPerson = Plus.PeopleApi
                            .getCurrentPerson(mGoogleApiClient);
                    googleFirstName = currentPerson.getDisplayName();
                    googleImage = currentPerson.getImage().getUrl();
                    // String personGooglePlusProfile = currentPerson.getUrl();
                    googleEmailId = Plus.AccountApi
                            .getAccountName(mGoogleApiClient);
                    googleId = currentPerson.getId();
                    Log.i("googleId", googleId);
                    JSONObject fullname = new JSONObject(currentPerson.getName()
                            + "");
                    googleFirstName = fullname.getString("familyName");
                    googleLastName = fullname.getString("givenName");
                    if (currentPerson.getGender() == 0)
                        googleGender = "female";
                    else if (currentPerson.getGender() == 1)
                        googleGender = "male";
                    else
                        googleGender = "other";
                    // by default the profile url gives 50x50 px image only
                    // we can replace the value with whatever dimension we want by
                    // replacing sz=X
                    googleImage = googleImage
                            .substring(0, googleImage.length() - 2)
                            + PROFILE_PIC_SIZE;
                    new GetGoogleAuthTask().execute();
                    // new LoadProfileImg(null).execute(personPhotoUrl);
                } else {
                    // Toast.makeText(getApplicationContext(),
                    // "Person information is null", Toast.LENGTH_LONG).show();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        SharedPreferences SharedPreference;
        Editor editor;
        private class GetGoogleAuthTask extends AsyncTask<Void, Void, String> {
            @Override
            protected String doInBackground(Void... params) {
                String token = null;
                try {
                    token = GoogleAuthUtil.getToken(RegisterActivity.this,
                            Plus.AccountApi.getAccountName(mGoogleApiClient),
                            "oauth2:" + Scopes.PLUS_LOGIN + " " + Scopes.PLUS_ME);
                            // Change the permissions as per your need.
                } catch (IOException transientEx) {
                    // Network or server error, try later
                    Log.e(TAG, transientEx.toString());
                } catch (UserRecoverableAuthException e) {
                    // Recover (with e.getIntent())
                    Log.e(TAG, e.toString());
                    // Intent recover = e.getIntent();
                    // startActivityForResult(recover, REQUEST_CODE_TOKEN_AUTH);
                } catch (GoogleAuthException authEx) {
                    // The call is not ever expected to succeed
                    // assuming you have already verified that
                    // Google Play services is installed.
                    Log.e(TAG, authEx.toString());
                }
                return token;
            }
            @Override
            protected void onPostExecute(String token) {
                if (token != null) {
                    googleToken = token;
                    // Log.i(TAG, "Access token retrieved:" + token);
                    SharedPreference = getApplicationContext()
                            .getSharedPreferences("TokenPreference", 0);
                    editor = SharedPreference.edit();
                    editor.putString("access_token", token);
                    editor.commit();
                }
                Log.i("GooGle", "called");
                loginWithGoogleData();
                storeUserData.setBoolean(AppConstants.KEY_IS_LOGIN, true);
            }
        }

和最后一个活动结果

 @Override
        public void onActivityResult(int requestCode, int responseCode, Intent data) {
            super.onActivityResult(requestCode, responseCode, data);
            uiHelper.onActivityResult(requestCode, responseCode, data);
            /******** GOOGLE CODE START **************/
            if (requestCode == RC_SIGN_IN) {
                if (responseCode != RESULT_OK) {
                    mSignInClicked = false;
                }
                mIntentInProgress = false;
                if (!mGoogleApiClient.isConnecting()) {
                    mGoogleApiClient.connect();
                }
            }
            /******** GOOGLE CODE END **************/
        }

不要忘记在清单中添加权限…

<uses-permission android:name="android.permission.GET_ACCOUNTS"/>
<uses-permission android:name="android.permission.USE_CREDENTIALS"/>

3天后终于有了解决办法。

我已经改变了作用域。现在工作得很好。我可以从访问令牌获得所有详细信息,甚至电子邮件id。

protected String doInBackground(String... args) {

            String token = null;
            String scope = "oauth2:" + Scopes.PLUS_LOGIN + " " + "https://www.googleapis.com/auth/userinfo.email" + " https://www.googleapis.com/auth/plus.profile.agerange.read";
            try {
                token = GoogleAuthUtil.getToken(
                        SigninScreen.this,
                        Plus.AccountApi.getAccountName(mGoogleApiClient),
                        scope);
                System.out.println("OKAY!"+token);
            } catch (IOException transientEx) {
                // Network or server error, try later
                Log.e(TAG, transientEx.toString());
            } catch (UserRecoverableAuthException e) {
                // Recover (with e.getIntent())
                Log.e(TAG, e.toString());
                Intent recover = e.getIntent();
                startActivityForResult(recover, 125);
            } catch (GoogleAuthException authEx) {
                // The call is not ever expected to succeed
                // assuming you have already verified that 
                // Google Play services is installed.
                Log.e(TAG, authEx.toString());
            }
            return token;

最新更新