TrinityTuts

Add Google reCaptcha in Android Application

Last updated on August 28th, 2020 at 05:13 pm

In this post I will explain to you how we can add Google reCaptcha verification in our Android application in simple steps.

Google reCaptcha is a free service which uses advanced risk analysis engine to prevent web and mobile application from invalid traffic and spam.

SafetyNet includes reCaptcha API for android application which helps to protect application from spam and invalid request. So, let’s get started.

Get an API key from the Google reCaptcha website.

Step 1. Go to Google reCaptcha website.

Step 2. Fill all the required fields note you need to select reCAPTCHA Android if you are selecting reCAPTCHA type V2 as shown in the below image.

Step 3. Now you also need to define your package name in the packages field you can add multiple packages here.

Step 4. Once you fill all fields you get your API. We use Site Key in our Android application.

Google reCaptcha Android Integration

Now we implement reCaptcha in Android in simple steps.

Step 1. Create a new Android studio project or open an already existing project where you want to implement reCaptcha and add below library in your app build.gradle and sync your project.

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

Step 2. Now once the library added you need to add Internet permission in your AndroidManifest.xml file.

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

Step 3. Now open your activity_main.xml file and create a button which invokes captcha verification

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/reCaptcha"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Show Recaptcha"></Button>

</LinearLayout>

Step 4. Now when the user clicks on button we need to verify it so check below code how we can do that.

package com.recaptcha;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import com.google.android.gms.common.api.ApiException;
import com.google.android.gms.common.api.CommonStatusCodes;
import com.google.android.gms.safetynet.SafetyNet;
import com.google.android.gms.safetynet.SafetyNetApi;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;

import java.util.concurrent.Executor;

public class MainActivity extends AppCompatActivity {

    Button reCaptcha;
    String SITE_KEY, TAG ="resp", URL_VERIFY_ON_SERVER;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        SITE_KEY = "YOUR_IP_ADDRESS";
        URL_VERIFY_ON_SERVER = "YOUR_SERVER_VERIFICATION_URL";

        reCaptcha = (Button)findViewById(R.id.reCaptcha);

        reCaptcha.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SafetyNet.getClient(MainActivity.this).verifyWithRecaptcha(SITE_KEY)
                        .addOnSuccessListener(MainActivity.this,
                                new OnSuccessListener<SafetyNetApi.RecaptchaTokenResponse>() {
                                    @Override
                                    public void onSuccess(SafetyNetApi.RecaptchaTokenResponse response) {
                                        // Indicates communication with reCAPTCHA service was
                                        // successful.
                                        String userResponseToken = response.getTokenResult();
                                        Log.e("response", userResponseToken);
                                        if (!userResponseToken.isEmpty()) {
                                            // Validate the user response token using the
                                            // reCAPTCHA siteverify API.

                                        }
                                    }
                                })
                        .addOnFailureListener(MainActivity.this, 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.
                                    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());
                                }
                            }
                        });
            }
        });
    }
}

You need to add your key to the above code and try. Now when you successfully verify you get code in userResponseToken variable which you can pass to your server and verify serverside. Here below PHP code to verify the response token on the server.

<?php
    $secretKey = "YOUR_SERVER_KEY";
    $url = 'https://www.google.com/recaptcha/api/siteverify';
    $capatcheData = ['secret' => $secretKey, 'response' => "YOUR_RESPONSE_TOKEN"];
    $options = [
        'http' => [
            'header'  => "Content-type: application/x-www-form-urlencoded\r\n",
            'method'  => 'POST',
            'content' => http_build_query($capatcheData)
        ]
    ];
    $context  = stream_context_create($options);
    $response = file_get_contents($url, false, $context);
    $responseKeys = json_decode($response, true);
    header('Content-type: application/json');
    if($responseKeys["success"] == 1){
        $rsp = ['status' => 1, 'msg' => 'Verified Successfully', 'error' => ''];
    }else {
        $rsp = ['status' => 0, 'msg' => 'Verifation Failed', 'error' => ''];
    }

https://github.com/anehkumar/AndroidGoogleReCaptcha

Hope this post helps you to implement Google reCaptcha in your Android project.