Integra reCAPTCHA con le app per Android

Questa pagina spiega come integrare reCAPTCHA nella tua app per Android.

Se vuoi fornire verifiche visive per il traffico sospetto, puoi utilizzare l'API reCAPTCHA SafetyNet.

Prima di iniziare

  1. Prepara l'ambiente per reCAPTCHA.

  2. Crea una chiave reCAPTCHA per la piattaforma app per Android.

    In alternativa, puoi copiare l'ID di una chiave reCAPTCHA esistente per Android eseguendo uno dei seguenti passaggi:

    • Per copiare l'ID di una chiave esistente dalla console Google Cloud, segui questi passaggi:

      1. Vai alla pagina reCAPTCHA.

        Vai a reCAPTCHA

      2. Nell'elenco delle chiavi reCAPTCHA, tieni il puntatore sulla chiave che vuoi copiare, quindi fai clic su .
    • Per copiare l'ID di una chiave esistente utilizzando l'API REST, utilizza il metodo projects.keys.list.
    • Per copiare l'ID di una chiave esistente utilizzando gcloud CLI, utilizza il comando gcloud recaptcha keys list.

Preparare l'ambiente Android

Android nativo

  1. Prepara il tuo ambiente di sviluppo scaricando e installando l'ultima versione di Android Studio.

  2. Assicurati di avere un'app con il valore minimo dell'SDK per Android impostato su API 19: Android 4.4 (KitKat). Puoi impostare l'SDK minimo dell'app su API 19 o creare una nuova app mobile.

  3. Se vuoi creare una nuova app mobile, crea un'applicazione di test avviando un nuovo progetto Android Studio:

    1. Seleziona Attività vuota. Se vuoi utilizzare Jetpack Compose nella tua app scegli Vuota Attività di scrittura.
    2. Imposta la lingua su kotlin.
    3. Imposta il valore minimo dell'SDK su API 19: Android 4.4 (KitKat).
  4. Assicurati che il Repository Maven google() di Google sia nell'elenco dei repository nel file build.gradle a livello di progetto, come mostrato nello snippet seguente:

    allprojects {
        repositories {
            google()
        }
    }
    

    Per maggiori informazioni, consulta il Repository Maven di Google.

  5. Per aggiungere la dipendenza dell'API reCAPTCHA, aggiungi la seguente regola di build alla sezione dependencies del file build.gradle a livello di app.

      implementation 'com.google.android.recaptcha:recaptcha:18.5.1'
    

    Per saperne di più sull'aggiunta di dipendenze nelle app per Android, consulta Aggiungere dipendenze build.

  6. Aggiungi l'autorizzazione Internet tra il primo tag <manifest> e il primo tag <application> nel file manifest dell'applicazione (ad esempio, AndroidManifest.xml). Questa autorizzazione è richiesta perché l'API reCAPTCHA coinvolge operazioni di rete.

    <manifest ...>
    
        <uses-permission android:name="android.permission.INTERNET" />
    
        <application ...>
        ...
      </application>
    </manifest>
    
  7. Se vuoi utilizzare le librerie AndroidX nel nuovo progetto, compila l'SDK per Android 9.0 o versioni successive e aggiungi il seguente snippet di codice a gradle.properties.

    android.useAndroidX=true
    android.enableJetifier=true
    

    Per maggiori informazioni, vedi Migrazione ad AndroidX.

Flutter

Per istruzioni dettagliate sull'utilizzo di reCAPTCHA tramite Flutter, consulta la documentazione di Flutter.

ReactNative

Per istruzioni dettagliate sull'utilizzo di reCAPTCHA tramite React Native, consulta la documentazione di React Native.

Integra reCAPTCHA con la tua app per Android

  1. Crea un'istanza per un client utilizzando la chiave reCAPTCHA (KEY_ID) che hai creato per la tua app per Android.

    Kotlin

    class MainActivity : AppCompatActivity() {
    
        private lateinit var recaptchaClient: RecaptchaClient
    
        override fun onCreate(savedInstanceState: Bundle?) {
          super.onCreate(savedInstanceState)
          setContentView(R.layout.activity_main)
          initializeRecaptchaClient()
          // ... rest of onCreate code
        }
    
        private fun initializeRecaptchaClient() {
          lifecycleScope.launch {
            Recaptcha.getClient(application, "KEY_ID")
              .onSuccess { client ->
                recaptchaClient = client
              }
              .onFailure { exception ->
                // Handle communication errors ...
                // See "Handle communication errors" section
              }
          }
        }
    
        // ... rest of activity code.
    }
    

    Java

    public final class MainActivity extends Activity {
      @Nullable private RecaptchaTasksClient recaptchaTasksClient = null;
    
      @Override
      protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initializeRecaptchaClient();
        // ... rest of onCreate code
      }
    
      private void initializeRecaptchaClient() {
        Recaptcha
          .getTasksClient(getApplication(), "KEY_ID")
          .addOnSuccessListener(
              this,
              new OnSuccessListener<RecaptchaTasksClient>() {
                @Override
                public void onSuccess(RecaptchaTasksClient client) {
                  MainActivity.this.recaptchaTasksClient = client;
                }
              })
          .addOnFailureListener(
              this,
              new OnFailureListener() {
                @Override
                public void onFailure(@NonNull Exception e) {
                  // Handle communication errors ...
                  // See "Handle communication errors" section
                }
              });
      }
    
      // ... rest of activity code.
    }
    
  2. Per ogni azione dell'app protetta mediante reCAPTCHA, chiama il metodo execute passando un RecaptchaAction. reCAPTCHA fornisce un insieme integrato di azioni e, se necessario, puoi creare azioni personalizzate.

    Il seguente snippet di codice mostra come utilizzare execute per proteggere un'azione LOGIN.

    Kotlin

    private fun executeLoginAction() {
      lifecycleScope.launch {
        recaptchaClient
          .execute(RecaptchaAction.LOGIN)
          .onSuccess { token ->
            // Handle success ...
            // See "What's next" section for instructions
            // about handling tokens.
          }
          .onFailure { exception ->
            // Handle communication errors ...
            // See "Handle communication errors" section
          }
      }
    }
    

    Java

    private void executeLoginAction(View v) {
      assert recaptchaTasksClient != null;
      recaptchaTasksClient
        .executeTask(RecaptchaAction.LOGIN)
        .addOnSuccessListener(
            this,
            new OnSuccessListener<String>() {
              @Override
              public void onSuccess(String token) {
                // Handle success ...
                // See "What's next" section for instructions
                // about handling tokens.
              }
            })
        .addOnFailureListener(
            this,
            new OnFailureListener() {
              @Override
              public void onFailure(@NonNull Exception e) {
                // Handle communication errors ...
                // See "Handle communication errors" section
              }
            });
    }
    

Il seguente snippet di codice campione mostra un'integrazione completa dei metodi getClient() e execute() in una singola app Attività:

Kotlin

class MainActivity : AppCompatActivity() {

  private lateinit var recaptchaClient: RecaptchaClient

  override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
    initializeRecaptchaClient()
    findViewById<View>(R.id.btn_login).setOnClickListener { executeLoginAction() }
    findViewById<View>(R.id.btn_redeem).setOnClickListener { executeRedeemAction() }
  }

  private fun initializeRecaptchaClient() {
    lifecycleScope.launch {
      Recaptcha.getClient(application, "KEY_ID")
        .onSuccess { client ->
          recaptchaClient = client
        }
        .onFailure { exception ->
          // Handle communication errors ...
          // See "Handle communication errors" section
        }
    }
  }

  private fun executeLoginAction() {
    lifecycleScope.launch {
      recaptchaClient
        .execute(RecaptchaAction.LOGIN)
        .onSuccess { token ->
          // Handle success ...
          // See "What's next" section for instructions
          // about handling tokens.
        }
        .onFailure { exception ->
          // Handle communication errors ...
          // See "Handle communication errors" section
        }
    }
  }

  private fun executeRedeemAction(){
    lifecycleScope.launch {
      recaptchaClient
        .execute(RecaptchaAction.custom("redeem"))
        .onSuccess { token ->
          // Handle success ...
          // See "What's next" section for instructions
          // about handling tokens.
        }
        .onFailure { exception ->
          // Handle communication errors ...
          // See "Handle communication errors" section
        }
    }
  }
}

Java

public final class MainActivity extends Activity {
  @Nullable private RecaptchaTasksClient recaptchaTasksClient = null;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    initializeRecaptchaClient();
    findViewById(R.id.btn_login).setOnClickListener(this::executeLoginAction);
    findViewById(R.id.btn_redeem).setOnClickListener(this::executeRedeemAction);
  }

  private void initializeRecaptchaClient() {
    Recaptcha
      .getTasksClient(getApplication(), "KEY_ID")
      .addOnSuccessListener(
          this,
          new OnSuccessListener<RecaptchaTasksClient>() {
            @Override
            public void onSuccess(RecaptchaTasksClient client) {
              MainActivity.this.recaptchaTasksClient = client;
            }
          })
      .addOnFailureListener(
          this,
          new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
              // Handle communication errors ...
              // See "Handle communication errors" section
            }
          });
  }

  private void executeLoginAction(View v) {
    assert recaptchaTasksClient != null;
    recaptchaTasksClient
      .executeTask(RecaptchaAction.LOGIN)
      .addOnSuccessListener(
          this,
          new OnSuccessListener<String>() {
            @Override
            public void onSuccess(String token) {
              // Handle success ...
              // See "What's next" section for instructions
              // about handling tokens.
            }
          })
      .addOnFailureListener(
          this,
          new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
              // Handle communication errors ...
              // See "Handle communication errors" section
            }
          });
  }

  private void executeRedeemAction(View v) {
    assert recaptchaTasksClient != null;
    recaptchaTasksClient
      .executeTask(RecaptchaAction.custom("redeem"))
      .addOnSuccessListener(
          this,
          new OnSuccessListener<String>() {
            @Override
            public void onSuccess(String token) {
              // Handle success ...
              // See "What's next" section for instructions
              // about handling tokens.
            }
          })
      .addOnFailureListener(
          this,
          new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
              // Handle communication errors ...
              // See "Handle communication errors" section
            }
          });
  }
}

Imposta un timeout per le chiamate API

Puoi specificare un valore di timeout per le API getClient e execute utilizzando la proprietà timeout di ciascuna API.

Viene utilizzato un timeout predefinito di 10 secondi per getClient e di 10 secondi per le API execute.

Kotlin

  • Imposta il timeout durante la chiamata a getClient.

        lifecycleScope.launch {
          Recaptcha.getClient(application, "KEY_ID", timeout = 20000L)
            .onSuccess { client ->
              recaptchaClient = client
            }
            .onFailure { exception ->
              // Handle communication errors ...
              // See "Handle communication errors" section
            }
        }
    

    Questo snippet di codice imposta il timeout di getClient su 20 secondi.

  • Imposta il timeout durante la chiamata a execute.

        lifecycleScope.launch {
          recaptchaClient
            .execute(RecaptchaAction.LOGIN(), timeout = 10000L)
            .onSuccess { token ->
              // Handle success ...
              // See "What's next" section for instructions
              // about handling tokens.
            }
            .onFailure { exception ->
              // Handle communication errors ...
              // See "Handle communication errors" section
            }
        }
    

    Questo snippet di codice imposta il timeout di execute su 10 secondi.

Java

  • Imposta il timeout durante la chiamata a getClient.

      Recaptcha
        .getTasksClient(getApplication(), "KEY_ID", 20000L)
        .addOnSuccessListener(
            this,
            new OnSuccessListener<RecaptchaTasksClient>() {
              @Override
              public void onSuccess(RecaptchaTasksClient client) {
                MainActivity.this.recaptchaTasksClient = client;
              }
            })
        .addOnFailureListener(
            this,
            new OnFailureListener() {
              @Override
              public void onFailure(@NonNull Exception e) {
                // Handle communication errors ...
                // See "Handle communication errors" section
              }
            });
    

    Questo snippet di codice imposta il timeout di getClient su 20 secondi.

  • Imposta il timeout durante la chiamata a execute.

      recaptchaTasksClient
        .executeTask(RecaptchaAction.custom("redeem"), 10000L)
        .addOnSuccessListener(
            this,
            new OnSuccessListener<String>() {
              @Override
              public void onSuccess(String token) {
                // Handle success ...
                // See "What's next" section for instructions
                // about handling tokens.
              }
            })
        .addOnFailureListener(
            this,
            new OnFailureListener() {
              @Override
              public void onFailure(@NonNull Exception e) {
                // Handle communication errors ...
                // See "Handle communication errors" section
              }
            });
    

    Questo snippet di codice imposta il timeout di execute su 10 secondi.

Gestire gli errori di comunicazione

Se la tua app non riesce a comunicare con il servizio reCAPTCHA, il motivo potrebbe essere un errore nell'API. Per gestire correttamente questi errori, devi aggiungere una logica nell'app.

Per maggiori dettagli sulle mitigazioni per gli errori comuni dell'API, vedi RecaptchaErrorCode.

Riferimento API

Per un riferimento completo dell'API reCAPTCHA per Android, visita la pagina com.google.android.recaptcha.

Passaggi successivi

  • Per valutare il token di risposta reCAPTCHA, crea una valutazione.