Google reCAPTCHA Integrating in Android Application

Hii in this Android solution we are sharing how to use Google reCAPTCHA Integrating into Android Application. An Android security purpose, you can add google re Captcha for registration form and query form in Android. Google reCAPTCHA is verified the user is not a robot its a real user.

While submitting some form or any other kind of information on a website, you might have noticed some captcha that you have to fill before submitting the details. That captcha may be of the form of an image having some numbers written on it and you just have to enter those numbers in the EditText provided to you. In Android, Another captcha can be an image and you have to identify user and robot.

In this Android blog, we will learn how to implement CAPTCHA using Google’s reCAPTCHA in our Android Application. So, let’s get started. Just follow these simple steps.

 

 

Generate the reCAPTCHA Site Key and Secret Key

So, we have seen the flow of Google’s reCAPTCHA in the Android application. Our next step is to integrate this reCAPTCHA in our app. So, firstly we need to generate a Site Key and a Secret Key from the reCAPTCHA website. Follow the below steps:

  1. Visit the reCAPTCHA website.
  2. Enter the label to identify your key. You can enter any name here.
  3. After entering the label, select the reCAPTCHA type that you want to add to your app. I will be using reCAPTCHA v2 and after that reCAPTCHA Android.
  4. Enter the package name of your Android project.
  5. Finally, select the Accept the reCAPTCHA Terms and Conditions and Send alerts to owners.
  6. Click on Submit
  7. Hare, You Can see SITE_KEY, and SITE_SECRET_KEY.

Lest Integration in your Android App.

Step 1:  Add Dependency on our App build Gradle.

implementation 'com.google.android.gms:play-services-safetynet:17.0.0'

Step 2:-  Make a UI for Google reCAPTCHA.

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:layout_marginTop="20dp"
    android:padding="5dp">

    <TextView
        android:id="@+id/GoogleCaptchaText"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="Google Captcha "
        android:textAppearance="@style/page_title" />

    <CheckBox
        android:id="@+id/GoogleCaptcha"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:buttonTint="@color/new_Blue" />

</LinearLayout>

Step 3: Add your java class Implication follow these codes.

add this method for your ReCaptcha generation in Android. You can add whare you want to show reCaptcha like on button click and Checkbox Click show.

public void Catcha(){
    SafetyNet.getClient(mActivity).verifyWithRecaptcha("Enter Site_key")
            .addOnSuccessListener(new OnSuccessListener<SafetyNetApi.RecaptchaTokenResponse>() {
                @Override
                public void onSuccess(SafetyNetApi.RecaptchaTokenResponse recaptchaTokenResponse) {
                    // Indicates communication with reCAPTCHA service was
                    // successful.
                    String userResponseToken = recaptchaTokenResponse.getTokenResult();
                    if (!userResponseToken.isEmpty()) {
                        handleCaptchaResult(userResponseToken);
                        // Validate the user response token using the
                        // reCAPTCHA siteverify API.
                        Log.e(TAG, "VALIDATION STEP NEEDED");
                    }else {
                        GoogleCaptcha.setChecked(false);
                    }
                }
            })
            .addOnFailureListener(new OnFailureListener() {
                @Override
                public void onFailure(@NonNull Exception e) {
                    if (e instanceof ApiException) {
                        // An error occurred when communicating with the
                        // reCAPTCHA service. Refer to the status code to
                        // handle the error appropriately.
                        GoogleCaptcha.setChecked(false);
                        ApiException apiException = (ApiException) e;
                        int statusCode = apiException.getStatusCode();
                        Log.e(TAG, "Error: " + CommonStatusCodes
                                .getStatusCodeString(statusCode));
                    } else {
                        // A different, unknown type of error occurred.
                        Log.e(TAG, "Error: " + e.getMessage());
                    }
                }
            });
}

 

The second Method to Send a request to google server to verify your ReCaptcha token. 

void handleCaptchaResult(final String responseToken) {
    String url = "https://www.google.com/recaptcha/api/siteverify";
    StringRequest request = new StringRequest(Request.Method.POST, url,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    try {
                        JSONObject jsonObject = new JSONObject(response);
                        if(jsonObject.getBoolean("success")){
                            GoogleCaptchaText.setText("You're not a Robot");
                            GoogleCaptcha.setChecked(true);
                        }
                    } catch (Exception ex) {
                        Log.d(TAG, "Error message: " + ex.getMessage());
                        GoogleCaptcha.setChecked(false);
                    }
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    GoogleCaptcha.setChecked(false);
                    Log.d(TAG, "Error message: " + error.getMessage());
                }
            }) {
        @Override
        protected Map<String, String> getParams() {
            Map<String, String> params = new HashMap<>();
            params.put("secret", SITE_SECRET_KEY);
            params.put("response", responseToken);
            return params;
        }
    };
    request.setRetryPolicy(new DefaultRetryPolicy(
            50000,
            DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
            DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
    queue.add(request);
}

 

Facebooktwitterredditpinterestlinkedinmail
Recommended
Hi Everyone in this Android tutorial, I am sharing how…