简体   繁体   English

在解析器上使用Google+登录

[英]Login using Google+ on Parse

I know this question has already been asked, but I couldn't find any solution. 我知道这个问题已经被提出,但是我找不到任何解决方案。 I am using Parse, where are users are able to login using Facebook, Twitter, and Google+. 我正在使用Parse,用户可以在其中使用Facebook,Twitter和Google+登录。 As of now, only Facebook and Twitter is fully functional. 截至目前,只有Facebook和Twitter可以正常使用。

I have managed to login using Facebook and Twitter in the following way: 我设法通过以下方式使用Facebook和Twitter登录:

private void onLoginButtonClicked() {
        LoginActivity.this.progressDialog = ProgressDialog.show(
                LoginActivity.this, "", "Logging in...", true);
        List<String> permissions = Arrays.asList("public_profile", "user_about_me",
                "user_relationships", "user_birthday", "user_location");
        ParseFacebookUtils.logIn(permissions, this, new LogInCallback() {
            @Override
            public void done(ParseUser user, ParseException err) {
                LoginActivity.this.progressDialog.dismiss();
                if (user == null) {
                    Log.d(IntegratingFacebookTutorialApplication.TAG,
                            "Uh oh. The user cancelled the Facebook login.");
                } else if (user.isNew()) {
                    Log.d(IntegratingFacebookTutorialApplication.TAG,
                            "User signed up and logged in through Facebook!");
                    showUserDetailsActivity();

                } else {
                    Log.d(IntegratingFacebookTutorialApplication.TAG,
                            "User logged in through Facebook!");
                moodpage();             

                }
            }
        });
    }

    private void onTwitterButtonClicked() {
        ParseTwitterUtils.logIn(this, new LogInCallback() {
              @Override
              public void done(ParseUser user, ParseException err) {
                if (user == null) {
                  Log.d("MyApp", "Uh oh. The user cancelled the Twitter login.");
                } else if (user.isNew()) {
                  Log.d("MyApp", "User signed up and logged in through Twitter!");
                  showUserDetailsActivity();        
                  } else {
                  Log.d("MyApp", "User logged in through Twitter!");
                  moodpage();               }
              }

            });
    }

I am trying to figure out to achieve this with Google+ through parse. 我正在尝试通过解析来使用Google+实现这一目标。 Someone has suggested for me to look into Parse Rest API, however, I am not familiar with it, and need more guidance. 有人建议我研究Parse Rest API,但是我不熟悉它,需要更多指导。

Some people have suggested me to use https://github.com/Glamdring/google-plus-java-api/ and looks promissing, but I am not sure how I would work that out. 有人建议我使用https://github.com/Glamdring/google-plus-java-api/ ,看起来有些许,但我不确定如何解决。

for example lets say I have 例如说我有

    googleButton = (Button) findViewById(R.id.twitterButton);
        googleButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {



                onGoogleButtonClicked();
            }
        });

private void onGoogleButtonClicked(); {
        //what to input here
    }

Any clarification will be appreciated. 任何澄清将不胜感激。

Parse.com only support facebook and twitter yet but not google+, for that you have to implement your own using authentication at cloud (parse.com) side Parse.com仅支持facebook和twitter,但不支持google +,因为您必须在云(parse.com)端使用身份验证来实现自己的

This is long process so be patient 这是一个漫长的过程,所以请耐心等待

Follow this steps 遵循这个步骤

1) get google profile information for that implement this necessary functions 1)获取实现此必要功能的 Google个人资料信息

put in onCreate() 放在onCreate()

mGoogleApiClient = new GoogleApiClient.Builder(getActivity())
    .addConnectionCallbacks(this) //lets impement ConnectionCallbacks
    .addOnConnectionFailedListener(this).addApi(Plus.API) // lets implement OnConnectionFailedListener
    .addScope(Plus.SCOPE_PLUS_LOGIN).build();
    mGoogleApiClient.connect();

2) method of implemented OnConnectionFailedListener 2)实现OnConnectionFailedListener的方法

@Override
public void onConnectionFailed(ConnectionResult result) {
    // TODO Auto-generated method stub
    if (!result.hasResolution()) {
        GooglePlayServicesUtil.getErrorDialog(result.getErrorCode(), getActivity(),
                0).show();
        return;
    }

    if (!mIntentInProgress) {
        // Store the ConnectionResult for later usage
        mConnectionResult = result;

        if (mSignInClicked) {
            // The user has already clicked 'sign-in' so we attempt to
            // resolve all
            // errors until the user is signed in, or they cancel.
            resolveSignInError();
        }
    }
}

/**
 * Method to resolve any signin errors for google plus
 * */
private void resolveSignInError() {
    if (mConnectionResult.hasResolution()) {
        try {
            mIntentInProgress = true;
            mConnectionResult.startResolutionForResult(getActivity(), RC_SIGN_IN);
        } catch (SendIntentException e) {
            mIntentInProgress = false;
            mGoogleApiClient.connect();
        }
    }
}

3) call on google+ button click 3) 在Google+按钮上点击

private void loginUsingGoolgePlus() {
    // TODO Auto-generated method stub
    if (!mGoogleApiClient.isConnecting()) {
        mSignInClicked = true;
        resolveSignInError();
    }

}

4) methods of implemented ConnectionCallbacks 4)实现ConnectionCallbacks的方法

@Override
public void onConnected(Bundle arg0) {
    // TODO Auto-generated method stub
    mSignInClicked = false;
    Toast.makeText(getActivity(), "User is connected!", Toast.LENGTH_LONG).show();

    // Get user's information
    getProfileInformation();

}
@Override
public void onConnectionSuspended(int arg0) {
    // TODO Auto-generated method stub
    mGoogleApiClient.connect();

}

5) this method will give you profile information 5)此方法将为您提供个人资料信息

/**
 * Fetching user's information name, email, profile pic
 * */
private void getProfileInformation() {
    try {
        if (Plus.PeopleApi.getCurrentPerson(mGoogleApiClient) != null) {
            Person currentPerson = Plus.PeopleApi
                    .getCurrentPerson(mGoogleApiClient);
            String personName = currentPerson.getDisplayName();
            String personPhotoUrl = currentPerson.getImage().getUrl();
            String personGooglePlusProfile = currentPerson.getUrl();
            final String email = Plus.AccountApi.getAccountName(mGoogleApiClient);

            Log.e(TAG, "Name: " + personName + ", plusProfile: "
                    + personGooglePlusProfile + ", email: " + email
                    + ", Image: " + personPhotoUrl);

            // by default the profile url gives 50x50 px image only
            // we can replace the value with whatever dimension we want by
            // replacing sz=X
            personPhotoUrl = personPhotoUrl.substring(0,
                    personPhotoUrl.length() - 2)
                    + PROFILE_PIC_SIZE;

            new Thread(new Runnable() {

                @Override
                public void run() {
                    // TODO Auto-generated method stub
                    googleAuthWithParse(email);
                }
            }).start();
        } else {
            Toast.makeText(getActivity(),
                    "Person information is null", Toast.LENGTH_LONG).show();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

6) this is important here we generate one token and using this and email id, we call script function accessGoogleUser at cloud side (Parse.com) (this cloud code nothing but javascript main.js 6)这很重要,在这里我们生成一个令牌,并使用该令牌和电子邮件ID,我们在云端(Parse.com)调用脚本函数accessGoogleUser (此云代码只不过是javascript main.js

- accessGoogleUser will give you accessToken using this accessToken you can do login or signup accessGoogleUser将使用此accessToken为您提供accessToken,您可以登录或注册

protected void googleAuthWithParse(String email) {
    // TODO Auto-generated method stub
     String scopes = "oauth2:" + Scopes.PLUS_LOGIN + " ";
     String googleAuthCode = null;
    try {
        googleAuthCode = GoogleAuthUtil.getToken(
                 getActivity(),                                           // Context context
                 email,                                             // String email
                 scopes,                                            // String scope
                 null                                      // Bundle bundle
         );
    } catch (UserRecoverableAuthException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    } catch (IOException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    } catch (GoogleAuthException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

     //Log.i(TAG, "Authentication Code: " + googleAuthCode);

    final HashMap<String, Object> params = new HashMap<String, Object>();
    params.put("code", googleAuthCode);
    params.put("email", email);
    //loads the Cloud function to create a Google user
    ParseCloud.callFunctionInBackground("accessGoogleUser", params, new FunctionCallback<Object>() {
        @Override
        public void done(Object returnObj, ParseException e) {
            if (e == null) {
                Log.e("AccessToken", returnObj.toString());
                ParseUser.becomeInBackground(returnObj.toString(), new LogInCallback() {
                    public void done(final ParseUser user, ParseException e) {
                        if (user != null && e == null) {
                            showToast("The Google user validated");

                            if(user.isNew()){
                                  //isNew means firsttime   
                            }else{

                              loginSuccess();
                            }
                        } else if (e != null) {
                            showToast("There was a problem creating your account.");
                            e.printStackTrace();
                            mGoogleApiClient.disconnect();
                        } else
                            showToast("The Google token could not be validated");
                    }
                });
            } else {
                        if (e != null) {

                            try {
                                JSONObject jsonObject = new JSONObject(e.getMessage());
                                showToast(jsonObject.getString("message"));
                            } catch (JSONException e1) {
                                // TODO Auto-generated catch block
                                e1.printStackTrace();
                            }
                            e.printStackTrace();
                            mGoogleApiClient.disconnect();
                        }
            }
        }
    });
}

7) How to upload cloud code main.js at parse.com cloud 7)如何 在parse.com云 上上传云代码 main.js

read carefully and download Parse.exe and from here after download do 仔细阅读并下载Parse.exe,下载后从此处进行

place parse.exe and ParseConsole.exe in ':\\Windows\\System32' folder. Then search for Windows PowerShell in the start menu and run it as an administrator. Wait for the prompt in the window (mine was a blue window) to indicate it is in the ':\\Windows\\System32' folder. Then type '.\\ParseConsole.exe' and press enter.

this how we upload files 这就是我们上传文件的方式

below files will create at C:\\Users\\xxxx while follow image steps 下面的文件将在C:\\ Users \\ xxxx中创建,同时按照image steps

1) cloud
   - main.js
2) config
  ─ global.json
3) public
  ─ index.html

在此处输入图片说明

8) download main.js from here and replace with default main.js which created in cloud folder 8)此处 下载main.js并替换为在cloud folder创建的默认main.js

Note : don't forgot to add your client id and secret into this main.js 注意:不要忘记在此main.js添加客户端ID和密码

9) check this too.!! 9)也检查一下!!

Require Revocable Sessions should be false in parse data browser -> settings ->General 在解析数据浏览器->设置->常规中, Require Revocable Sessions should be false

Ask me for any doubt. 问我任何疑问。 i am ready for help.!! 我准备帮忙!!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM