콘텐츠로 건너뛰기

자주 방문한 페이지

최근 방문한 페이지

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.

이 사이트는 쿠키를 사용하여 사이트별 언어 및 표시 옵션에 대한 환경설정을 저장합니다.

Google Play에서 성공을 거두는 데 도움이 되는 최신 Android 개발자 뉴스 및 도움말을 받아 보세요.

* 필수 입력란

완료되었습니다.

WeChat에서 Google Developers 팔로우하기

이 사이트를 (으)로 탐색할까요?

페이지를 요청했지만 이 사이트의 언어 환경설정은 입니다.

언어 환경설정을 변경하고 이 사이트를 (으)로 탐색할까요? 언어 환경설정을 나중에 변경하려면 각 페이지 하단의 언어 메뉴를 사용하세요.

이 클래스를 사용하려면 API 수준 이상이 필요합니다.

문서에 대해 선택한 API 수준이 이므로 이 문서가 표시되지 않습니다. 왼쪽 탐색 메뉴의 선택기로 문서 API 수준을 변경할 수 있습니다.

앱에 필요한 API 수준 지정에 관한 자세한 내용은 다양한 플랫폼 버전 지원을 참조하세요.

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