Langsung ke konten

Paling sering dikunjungi

Terakhir dikunjungi

navigation

SafetyNet reCAPTCHA API

The SafetyNet service includes a reCAPTCHA API that you can use to protect your app from malicious traffic.

reCAPTCHA is a free service that uses an advanced risk analysis engine to protect your app from spam and other abusive actions. If the service suspects that the user interacting with your app might be a bot instead of a human, it serves a CAPTCHA that a human must solve before your app can continue executing.

This document explains how to integrate the reCAPTCHA API from SafetyNet into your app.

Additional Terms of Service

By accessing or using the reCAPTCHA API, you agree to the Google APIs Terms of Service, and to these Additional Terms. Please read and understand all applicable terms and policies before accessing the APIs.

reCAPTCHA Terms of Service

You acknowledge and understand that the reCAPTCHA API works by collecting hardware and software information, such as device and application data and the results of integrity checks, and sending that data to Google for analysis. Pursuant to Section 3(d) of the Google APIs Terms of Service, you agree that if you use the APIs that it is your responsibility to provide any necessary notices or consents for the collection and sharing of this data with Google.

Registering a reCAPTCHA key pair

To register a key pair for use with the SafetyNet reCAPTCHA API, navigate to the reCAPTCHA Android signup site, then complete the following sequence of steps:

  1. In the form that appears, provide the following information:

    • Label: A unique label for your key. Typically, you use the name of your company or organization.
    • Package Names: Provide the package name of each app that uses this API key. In order for an app to use the API, the package name that you enter must be an exact match of the package name for that app. Enter each package name on its own line.
    • Send alerts to owners: Check this checkbox if you want to receive emails about the reCAPTCHA API.
  2. Check the Accept the reCAPTCHA Terms of Service checkbox, then click Register.

  3. In the Adding reCAPTCHA to your app section on the page that appears next, your public and private keys appear under Site key and Secret key, respectively. You use the site key when you send the verify request, and you use the secret key when you validate the user response token.

Adding a SafetyNet API dependency

Before using the reCAPTCHA API, you need to add the SafetyNet API to your project. If you use Android Studio and you want to selectively compile this API into your Gradle dependencies, you should include the build rule that's shown in the following code snippet:

apply plugin: 'com.android.application'
...
dependencies {
    compile 'com.google.android.gms:play-services-safetynet:15.0.0'
}

For more information, see Set Up Google Play Services.

Using the reCAPTCHA API

This section describes how to call the reCAPTCHA API to send a CAPTCHA verification request and receive the user response token.

Send the verify request

To invoke the SafetyNet reCAPTCHA API, you call the verifyWithRecaptcha() method. Usually, this method corresponds to the user's selecting a UI element, such as a button, in your activity.

When using the verifyWithRecaptcha() method in your app, you must do the following:

The following code snippet shows how to invoke this method:

public void onClick(View v) {
    SafetyNet.getClient(this).verifyWithRecaptcha(YOUR_API_SITE_KEY)
        .addOnSuccessListener((Executor) this,
            new OnSuccessListener<SafetyNetApi.RecaptchaTokenResponse>() {
                @Override
                public void onSuccess(SafetyNetApi.RecaptchaTokenResponse response) {
                    // Indicates communication with reCAPTCHA service was
                    // successful.
                    String userResponseToken = response.getTokenResult();
                    if (!userResponseToken.isEmpty()) {
                        // Validate the user response token using the
                        // reCAPTCHA siteverify API.
                    }
                }
        })
        .addOnFailureListener((Executor) 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.d(TAG, "Error: " + CommonStatusCodes
                                .getStatusCodeString(statusCode));
                    } else {
                        // A different, unknown type of error occurred.
                        Log.d(TAG, "Error: " + e.getMessage());
                    }
                }
        });
}

Validate the user response token

When the reCAPTCHA API executes the onSuccess() method, the user has successfully completed the CAPTCHA challenge. However, this method only indicates that the user has solved the CAPTCHA correctly. You still need to validate the user's response token from your backend server.

To learn how to validate the user's response token, see Verifying the user's response.

Handling communication errors

If your app cannot communicate with the reCAPTCHA service successfully, it may be because the API is encountering an error. You should add logic in your app to gracefully handle such an error. Also, when the error occurs, your app should display a message to your users explaining why your app cannot finish processing their CAPTCHA response.

The following list shows the status codes for the most common API errors:

RECAPTCHA_INVALID_SITEKEY

The site key is invalid. Check that you've registered an API key successfully and that you've correctly copied the site key as a parameter when calling the API.

Constant value: 12007

RECAPTCHA_INVALID_KEYTYPE

The type of site key is invalid. Create a new site key by navigating to the reCAPTCHA Android signup site.

Constant value: 12008

RECAPTCHA_INVALID_PACKAGE_NAME

The calling app's package name doesn't match any of the names that you've associated with the site key. Add the calling app's package name to the site key on the reCAPTCHA Admin Console, or disable package name validation for your site key.

Constant value: 12013

UNSUPPORTED_SDK_VERSION

The API isn't supported on the device's Android SDK version. Upgrade to a new version of the Android SDK, then try communicating with the API again.

Constant value: 12006

TIMEOUT

The session timed out as the API waited for a response, either because the user didn't interact with the CAPTCHA or because the CAPTCHA loading process itself timed out. Wait for the user to invoke the API again. In the meantime, you can inform the user that they must complete the CAPTCHA to continue using your app.

Constant value: 15

NETWORK_ERROR

There is no Internet connection. After ensuring connectivity, try communicating with the API again.

Constant value: 7

ERROR

The operation encountered a general failure.

Constant value: 13

For more details about the status codes that the reCAPTCHA API can return, see the SafetyNetStatusCodes reference.

Situs ini menggunakan cookies untuk menyimpan preferensi Anda tentang bahasa di situs tertentu dan opsi tampilan.

Dapatkan berita dan tips terbaru dari developer Android yang akan membantu Anda mencapai kesuksesan di Google Play.

* Wajib Diisi

Hore!

Ikuti Google Developers di WeChat

Buka situs ini dalam bahasa ?

Anda meminta halaman dalam bahasa , namun preferensi bahasa untuk situs ini adalah .

Ingin mengubah preferensi bahasa dan mengakses situs ini dalam bahasa ? Jika nanti Anda ingin mengubah preferensi bahasa, gunakan menu bahasa di bagian bawah setiap halaman.

Kelas ini memerlukan tingkat API atau yang lebih tinggi

Dokumen ini tersembunyi karena level API yang Anda pilih untuk dokumentasi ini adalah . Anda dapat mengubah level API dokumentasi dengan pemilih di atas menu navigasi sebelah kiri.

Untuk informasi lebih lanjut tentang menentukan level API yang diperlukan aplikasi Anda, baca Mendukung Versi Platform Yang Berbeda.

Take a short survey?
Help us improve the Android developer experience. (April 2018 — Developer Survey)