Integrar o reCAPTCHA Enterprise a apps iOS

Nesta página, explicamos como integrar o reCAPTCHA Enterprise ao seu app iOS.

Devido à variação de dispositivos móveis em termos de tamanho da tela, desempenho e IU dos apps, o desafio reCAPTCHA da caixa de seleção visual (Não sou um robô) não está disponível para apps para dispositivos móveis iOS. Em vez disso, implemente sua própria estratégia de aplicação em níveis, como um fluxo de MFA, para fornecer um caminho de resgate alternativo para tráfego suspeito.

Antes de começar

  1. Defina o SDK mínimo do app como iOS 11 ou crie um novo app para dispositivos móveis.

  2. Prepare seu ambiente para o reCAPTCHA Enterprise.

  3. Crie uma chave reCAPTCHA para a plataforma de apps iOS.

    Se preferir, copie o ID de uma chave reCAPTCHA atual para iOS executando uma das seguintes etapas:

    • Para copiar o ID de uma chave atual do console do Google Cloud, faça o seguinte:

      1. Acesse a página do reCAPTCHA Enterprise.

        Acessar o reCAPTCHA Enterprise

      2. Na lista de chaves reCAPTCHA, mantenha o ponteiro do mouse sobre a chave que você quer copiar e clique em .
    • Para copiar o ID de uma chave atual usando a API REST, use o método projects.keys.list.
    • Para copiar o ID de uma chave atual com a CLI gcloud, use o comando gcloud recaptcha keys list.

  4. Ter uma conta no GitHub.

  5. Consulte os detalhes de privacidade da Apple.

Preparar o ambiente iOS

Para preparar o ambiente de desenvolvimento, faça o seguinte:

  1. Faça o download e instale a versão mais recente do Xcode e crie um novo aplicativo em branco de visualização única para iOS.

  2. Faça o download do SDK usando uma destas opções:

    CocoaPods

    1. Faça o download e instale o CocoaPods.
    2. Crie um Podfile e adicione as seguintes linhas:

      source "https://github.com/CocoaPods/Specs.git"
      
      target 'AppTarget' do
      
        # Podfiles must include use_frameworks! or
        # use_frameworks! :linkage => :static
        use_frameworks!
      
        pod "RecaptchaEnterprise", "18.5.0-beta02"
        ...
      
      end
      
    3. Instale as dependências necessárias executando pod update.

    Gerenciador de pacotes do Swift

    1. No XCode, selecione File > Add Packages e insira o seguinte URL no campo Search ou Enter Package URL: https://github.com/GoogleCloudPlatform/recaptcha-enterprise-mobile-sdk
    2. Na caixa de diálogo XCode, insira os seguintes detalhes:

      • Nome de usuário do GitHub.
      • Um token de acesso pessoal que você criou usando as instruções do GitHub. O Personal Access Token precisa ter os escopos listados na caixa de diálogo XCode Sign In.

      O Xcode instala o SDK e as dependências necessárias.

    Flutter

    Para instruções detalhadas sobre como usar o reCAPTCHA Enterprise no Flutter, consulte a documentação do Flutter (link em inglês).

    ReactNative

    Para instruções detalhadas sobre como usar o reCAPTCHA Enterprise no React Native, consulte a documentação do React Native.

    Download direto

    1. Se você quiser fazer o download do SDK e das dependências dele como xcframeworks, faça o download do client.

Configure o app

Você pode escrever seus aplicativos em Swift ou Objective-C.

Para configurar seu app, adicione os seguintes arquivos:

Swift

  1. Caso seu app esteja escrito em Swift, crie um cabeçalho de ponte Objective-C e inclua a seguinte importação:

    #import <RecaptchaEnterprise/RecaptchaEnterprise.h>
    

Objective-C

  1. Caso seu app seja escrito em Objective-C, crie um arquivo Swift de exemplo e inclua a importação abaixo para garantir que o Xcode possa encontrar e vincular as bibliotecas do Swift.

    import Foundation
    
  2. Para garantir que o código Swift seja vinculado corretamente, navegue até Destino > Configurações do build > Sempre incorporar bibliotecas padrão do Swift e verifique se a opção está definida como Yes.

Integrar o reCAPTCHA Enterprise ao seu app iOS

Para integrar o reCAPTCHA Enterprise ao seu app para iOS, siga estas etapas no Xcode:

  1. Para instanciar o SDK com a chave reCAPTCHA (KEY_ID) que você criou, atualize o app com o seguinte código:

    Swift com storyboard

    1. Atualize o ViewController.swift.

      Se você estiver usando CocoaPods, ignore a linha import RecaptchaEnterprise, porque a instrução de importação #import <RecaptchaEnterprise/RecaptchaEnterprise.h> no arquivo *-Bridging-Header.h é suficiente.

      import RecaptchaEnterprise
      
      class ViewController: UIViewController {
        var recaptchaClient: RecaptchaClient?
      
        override func viewDidLoad() {
          super.viewDidLoad()
          Task {
            do {
              let client = try await Recaptcha.getClient(withSiteKey: "KEY_ID")
              self.recaptchaClient = client
            } catch let error as RecaptchaError {
               print("RecaptchaClient creation error: \(String(describing: error.errorMessage)).")
            }
          }
        }
      }
      

      Se a versão mínima do SO do seu aplicativo for anterior à 13, use um fechamento final:

      import RecaptchaEnterprise
      
      class ViewController: UIViewController {
        var recaptchaClient: RecaptchaClient?
      
        override func viewDidLoad() {
          super.viewDidLoad()
          Recaptcha.getClient(withSiteKey: "KEY_ID") { client, error in
            guard let client = client else {
                print("RecaptchaClient creation error: \(error).")
              return
            }
            self.recaptchaClient = client
          }
        }
      }
      

    Swift com SwiftUI

    1. Crie uma classe ViewModel.

      Se você estiver usando CocoaPods, ignore a linha import RecaptchaEnterprise, porque a instrução de importação #import <RecaptchaEnterprise/RecaptchaEnterprise.h> no arquivo *-Bridging-Header.h é suficiente.

      import RecaptchaEnterprise
      
      @MainActor class ViewModel: ObservableObject {
        private var recaptchaClient: RecaptchaClient?
      
        init() {
           Task {
            do {
              let client = try await Recaptcha.getClient(withSiteKey: "KEY_ID")
              self.recaptchaClient = client
            } catch let error as RecaptchaError {
               print("RecaptchaClient creation error: \(String(describing: error.errorMessage)).")
            }
          }
        }
      }
      

      Se a versão mínima do SO do seu aplicativo for anterior à 13, use um fechamento final:

      import RecaptchaEnterprise
      
      class ViewController: UIViewController {
        var recaptchaClient: RecaptchaClient?
      
        override func viewDidLoad() {
          super.viewDidLoad()
          Recaptcha.getClient(withSiteKey: "KEY_ID") { client, error in
            guard let client = client else {
                print("RecaptchaClient creation error: \(error).")
              return
            }
            self.recaptchaClient = client
          }
        }
      }
      
    2. Instancie ViewModel em ContentView.swift.

      import SwiftUI
      import RecaptchaEnterprise
      
      struct ContentView: View {
        @StateObject private var viewModel = ViewModel()
      
        var body: some View {
        }
      }
      
      struct ContentView_Previews: PreviewProvider {
        static var previews: some View {
          ContentView()
        }
      }
      

    Objective-C

    1. Atualize o ViewController.h.

      #import <RecaptchaEnterprise/RecaptchaEnterprise.h>
      
      @interface ViewController : UIViewController
      @property (strong, atomic) RecaptchaClient *recaptchaClient;
      @end
      
    2. Atualize o ViewController.m.

      @implementation ViewController
      [Recaptcha getClientWithSiteKey:@"KEY_ID"
            completion:^void(RecaptchaClient* recaptchaClient, NSError* error) {
              if (!recaptchaClient) {
                NSLog(@"%@", (RecaptchaError *)error.errorMessage);
                return;
              }
              self->_recaptchaClient = recaptchaClient;
            }
      ];
      @end
      
  2. Crie um botão para chamar o reCAPTCHA Enterprise e acionar execute().

    Swift com storyboard

    1. No storyboard, crie um botão.
    2. Crie uma ação em ViewController vinculada ao botão que você criou.
    3. Chame o método execute() transmitindo uma ação Login para retornar um token reCAPTCHA usando o seguinte snippet de código:

      guard let recaptchaClient = recaptchaClient else {
        print("RecaptchaClient creation failed.")
        return
      }
      Task {
        do {
          let token = try await recaptchaClient.execute(withAction: RecaptchaAction.login)
          print(token)
        } catch let error as RecaptchaError {
          print(error.errorMessage)
        }
      }
      

      Se a versão mínima do SO do seu aplicativo for anterior à 13, use um fechamento final:

      guard let recaptchaClient = recaptchaClient else {
        print("RecaptchaClient creation failed.")
        return
      }
      recaptchaClient.execute(withAction: RecaptchaAction.login) { token, error in
        if let token = token {
          print(token)
        } else {
          print(error)
        }
      }
      

    Swift com SwiftUI

    1. Atualize o ViewModel.swift com o código de execução:

      import RecaptchaEnterprise
      
      @MainActor class ViewModel: ObservableObject {
      
        func execute() {
          guard let recaptchaClient = self.recaptchaClient else {
            print("Client not initialized correctly.")
            return
          }
      
          Task {
            do {
              let token = try await recaptchaClient.execute(withAction: RecaptchaAction.login)
              print(token)
            } catch let error as RecaptchaError {
              print(error.errorMessage)
            }
          }
        }
      }
      

      Se a versão mínima do SO do seu aplicativo for anterior à 13, use um fechamento final:

      guard let recaptchaClient = recaptchaClient else {
        print("RecaptchaClient creation failed.")
        return
      }
      recaptchaClient.execute(withAction: RecaptchaAction.login) { token, error in
        if let token = token {
          print(token)
        } else {
          print(error)
        }
      }
      
    2. O ContentView.swift foi atualizado.

      import SwiftUI
      import RecaptchaEnterprise
      
      struct ContentView: View {
        @StateObject private var viewModel = ViewModel()
      
        var body: some View {
      
          Button {
            viewModel.execute()
          } label: {
            Text("Execute")
          }.padding()
      
          Spacer()
        }
      }
      
      struct ContentView_Previews: PreviewProvider {
        static var previews: some View {
          ContentView()
        }
      }
      

    Objective-C

    1. No storyboard, crie um botão.
    2. Crie uma ação em ViewController vinculada ao botão que você criou.
    3. Chame o método execute() transmitindo uma ação Login para retornar um token reCAPTCHA usando o seguinte snippet de código:

      if (!self->_recaptchaClient) {
        return;
      }
      
      [recaptchaClient execute:RecaptchaAction.login
          completion:^void(NSString* _Nullable  token, NSError* _Nullable error) {
        if (!token) {
          NSLog (@"%@", (RecaptchaError *)error.errorMessage);
          return;
        }
        NSLog (@"%@", token);
      }];
      
  3. Teste o aplicativo:

    1. O reCAPTCHA Enterprise usa o AppAttest da Apple como parte do mecanismo de detecção. Se você não planeja usar uma chave de teste com uma pontuação fixa para desenvolvimento local, faça o seguinte:

      1. No Xcode, adicione o recurso App Attest ao app.

      2. No arquivo .entitlements do seu projeto, defina o ambiente do App Attest como production.

    2. Para limpar o ambiente de build do Xcode, no menu Produto, clique em Limpar pasta de build.

    3. Para executar o aplicativo, no menu Product, clique em Run.

    4. No aplicativo carregado, clique no botão criado anteriormente.

    5. A janela de saída de depuração deve retornar um token de reCAPTCHA (string alfanumérica) se a integração for bem-sucedida.

Definir um tempo limite para chamadas de API

Especifique um valor de tempo limite para as APIs getClient e execute usando a propriedade withTimeout de cada API.

Swift

  1. Defina o tempo limite ao chamar getClient.

        Task {
          do {
            self.recaptchaClient = try await Recaptcha.getClient(
              withSiteKey: "KEY_ID",
              withTimeout: 15000
            )
          } catch let error as RecaptchaError {
              print("RecaptchaClient creation error: \(String(describing: error.errorMessage)).")
          }
        }
    

    Se a versão mínima do SO do seu aplicativo for anterior à 13, use um fechamento final:

      Recaptcha.getClient(
        withSiteKey: "KEY_ID",
        withTimeout: 15000
      ) { client, error in
        guard let client = client else {
            print("RecaptchaClient creation error: \(error).")
          return
        }
        self.recaptchaClient = client
      }
    
  2. Defina o tempo limite ao chamar execute.

      Task {
        do {
          let token = try await recaptchaClient.execute(
            withAction: RecaptchaAction.login,
            withTimeout: 10000)
          print(token)
        } catch let error as RecaptchaError {
          print(error.errorMessage)
        }
      }
    

    Se a versão mínima do SO do seu aplicativo for anterior à 13, use um fechamento final:

      recaptchaClient.execute(
        withAction: RecaptchaAction.login,
        withTimeout: 10000
      ) { token, error in
        if let token = token {
          print(token)
        } else {
          print(error)
        }
      }
    

Objective-C

  1. Defina o tempo limite ao chamar getClient.

      [Recaptcha getClientWithSiteKey:@"KEY_ID"
                  withTimeout:15000.0
                   completion:^void(RecaptchaClient *recaptchaClient, NSError *error) {
                     if (!recaptchaClient) {
                       NSLog(@"%@", (RecaptchaError *)error.errorMessage);
                       return;
                     }
                     self->_recaptchaClient = recaptchaClient;
                   }];
    
  2. Defina o tempo limite ao chamar execute.

      [recaptchaClient execute:RecaptchaAction.login
          witTimeout:10000.0
          completion:^void(NSString* _Nullable  token, NSError* _Nullable error) {
        if (!token) {
          NSLog (@"%@", (RecaptchaError *)error.errorMessage);
          return;
        }
        NSLog (@"%@", token);
      }];
    

Referência da API

Para uma referência completa da API reCAPTCHA para iOS, consulte RecaptchaEnterprise.

A seguir

  • Para avaliar o token de resposta reCAPTCHA, crie uma avaliação.