Nesta página, descrevemos como lidar com problemas com vereditos de integridade.
Depois que um token de integridade é solicitado, você tem a opção de mostrar uma caixa de diálogo do Google Play para o usuário. Você pode mostrar a caixa de diálogo quando houver um ou mais problemas com o veredito de integridade ou se ocorrer uma exceção durante uma solicitação de API Integrity. Depois que a caixa de diálogo for fechada, confira se o problema foi corrigido fazendo outra solicitação de token de integridade. Se você fizer solicitações padrão, será necessário ativar o provedor de token novamente para receber um novo veredito.
Solicitar uma caixa de diálogo de integridade para corrigir um problema de veredito
Quando o cliente solicita um token de integridade, é possível usar o método oferecido no
StandardIntegrityToken (API padrão) e na
IntegrityTokenResponse (API clássica):
showDialog(Activity activity, int integrityDialogTypeCode).
As etapas abaixo descrevem como usar a API Play Integrity para mostrar uma
caixa de diálogo de correção usando o código de caixa de diálogo GET_LICENSED.
Outros códigos de caixa de diálogo que o app pode solicitar estão listados após esta seção.
Solicite um token de integridade do app e o envie ao servidor. Você pode usar a solicitação padrão ou clássica.
Kotlin
// Request an integrity token val tokenResponse: StandardIntegrityToken = requestIntegrityToken() // Send token to app server and get response on what to do next val yourServerResponse: YourServerResponse = sendToServer(tokenResponse.token())Java
// Request an integrity token StandardIntegrityToken tokenResponse = requestIntegrityToken(); // Send token to app server and get response on what to do next YourServerResponse yourServerResponse = sendToServer(tokenResponse.token());Unity
// Request an integrity token StandardIntegrityToken tokenResponse = RequestIntegrityToken(); // Send token to app server and get response on what to do next YourServerResponse yourServerResponse = sendToServer(tokenResponse.Token);Unreal Engine
// Request an integrity token StandardIntegrityToken* Response = RequestIntegrityToken(); // Send token to app server and get response on what to do next YourServerResponse YourServerResponse = SendToServer(Response->Token);Nativo
/// Request an integrity token StandardIntegrityToken* response = requestIntegrityToken(); /// Send token to app server and get response on what to do next YourServerResponse yourServerResponse = sendToServer(StandardIntegrityToken_getToken(response));No servidor, descriptografe o token de integridade e confira o campo
appLicensingVerdict. Ele poderia ficar assim:// Licensing issue { ... "accountDetails": { "appLicensingVerdict": "UNLICENSED" } }Se o token contiver
appLicensingVerdict: "UNLICENSED", responda ao cliente do app, solicitando que ele mostre a caixa de diálogo de licenciamento:Kotlin
private fun getDialogTypeCode(integrityToken: String): Int{ // Get licensing verdict from decrypted and verified integritytoken val licensingVerdict: String = getLicensingVerdictFromDecryptedToken(integrityToken) return if (licensingVerdict == "UNLICENSED") { 1 // GET_LICENSED } else 0 }Java
private int getDialogTypeCode(String integrityToken) { // Get licensing verdict from decrypted and verified integrityToken String licensingVerdict = getLicensingVerdictFromDecryptedToken(integrityToken); if (licensingVerdict.equals("UNLICENSED")) { return 1; // GET_LICENSED } return 0; }Unity
private int GetDialogTypeCode(string IntegrityToken) { // Get licensing verdict from decrypted and verified integrityToken string licensingVerdict = GetLicensingVerdictFromDecryptedToken(IntegrityToken); if (licensingVerdict == "UNLICENSED") { return 1; // GET_LICENSED } return 0; }Unreal Engine
private int GetDialogTypeCode(FString IntegrityToken) { // Get licensing verdict from decrypted and verified integrityToken FString LicensingVerdict = GetLicensingVerdictFromDecryptedToken(IntegrityToken); if (LicensingVerdict == "UNLICENSED") { return 1; // GET_LICENSED } return 0; }Nativo
private int getDialogTypeCode(string integrity_token) { /// Get licensing verdict from decrypted and verified integrityToken string licensing_verdict = getLicensingVerdictFromDecryptedToken(integrity_token); if (licensing_verdict == "UNLICENSED") { return 1; // GET_LICENSED } return 0; }No seu app, chame
showDialogcom o código solicitado extraído do seu servidor:Kotlin
// Show dialog as indicated by the server val showDialogType: Int? = yourServerResponse.integrityDialogTypeCode() if (showDialogType == null) { return } // Create dialog request val dialogRequest = StandardIntegrityDialogRequest.builder() .setActivity(activity) .setTypeCode(showDialogType) .setStandardIntegrityResponse(StandardIntegrityResponse.TokenResponse(token)) .build() // Call showDialog, the dialog will be shown on top of the provided activity // and the task will complete when the dialog is closed. val result: Task<Int> = standardIntegrityManager.showDialog(dialogRequest) // Handle response code, call the Integrity API again to confirm that the // verdict issue has been resolved.Java
// Show dialog as indicated by the server @Nullable Integer showDialogType = yourServerResponse.integrityDialogTypeCode(); if (showDialogType == null) { return; } // Create dialog request StandardIntegrityDialogRequest dialogRequest = StandardIntegrityDialogRequest.builder() .setActivity(getActivity()) .setTypeCode(showDialogTypeCode) .setStandardIntegrityResponse(new StandardIntegrityResponse.TokenResponse(token)) .build(); // Call showDialog, the dialog will be shown on top of the provided activity // and the task will complete when the dialog is closed. Task<Integer> result = standardIntegrityManager.showDialog(dialogRequest); // Handle response code, call the Integrity API again to confirm that the // verdict issue has been resolved.Unity
// Initialize the V2 manager. Requires Play Integrity Unity Plugin v2.0.0 or // higher. var standardIntegrityManager = new StandardIntegrityManagerV2(); IEnumerator ShowDialogCoroutine() { int showDialogType = yourServerResponse.IntegrityDialogTypeCode(); PlayAsyncOperation<IntegrityDialogResponseCode, StandardIntegrityError> showDialogTask; using (var activity = UnityPlayerHelper.GetCurrentActivity()) { // Create a dialog request var dialogRequest = new StandardIntegrityDialogRequest(tokenResponse, activity, showDialogType); // Call showDialog with the request, the dialog will be shown on top of the // provided activity and complete when the dialog is closed. showDialogTask = standardIntegrityManager.ShowDialog(dialogRequest); } // Wait for PlayAsyncOperation to complete. yield return showDialogTask; // Handle response code, call the Integrity API again to confirm that the // verdict issue been resolved. }Unreal Engine
// .h void MyClass::OnShowDialogCompleted( EStandardIntegrityErrorCode Error, EIntegrityDialogResponseCode Response) { // Handle response code, call the Integrity API again to confirm that the // verdict issue has been resolved. } // .cpp void MyClass::RequestIntegrityToken() { UStandardIntegrityToken* Response = ... int TypeCode = YourServerResponse.integrityDialogTypeCode(); // Create a delegate to bind the callback function. FShowDialogStandardOperationCompletedDelegate Delegate; // Bind the completion handler (OnShowDialogCompleted) to the delegate. Delegate.BindDynamic(this, &MyClass::OnShowDialogCompleted); // Call ShowDialog with TypeCode which completes when the dialog is closed. Response->ShowDialog(TypeCode, Delegate); }Nativo
// Show dialog as indicated by the server int show_dialog_type = yourServerResponse.integrityDialogTypeCode(); if(show_dialog_type == 0){ return; } /// Create dialog request StandardIntegrityDialogRequest* dialog_request; StandardIntegrityDialogRequest_create(&dialog_request); StandardIntegrityDialogRequest_setTypeCode(dialog_request, show_dialog_type); StandardIntegrityDialogRequest_setActivity(dialog_request, activity); StandardIntegrityDialogRequest_setStandardIntegrityToken(dialog_request, token_response); /// Call showDialog with the dialog request. The dialog will be shown on top /// of the provided activity and complete when the dialog is closed by the /// user. StandardIntegrityDialogResponse* dialog_response; StandardIntegrityErrorCode error_code = StandardIntegrityManager_showDialog(dialog_request, &dialog_response); /// Use polling to wait for the async operation to complete. Note, the polling /// shouldn't block the thread where the StandardIntegrityManager is running. IntegrityDialogResponseCode response_code = INTEGRITY_DIALOG_RESPONSE_UNKNOWN; while (error_code == STANDARD_INTEGRITY_NO_ERROR) { error_code = StandardIntegrityDialogResponse_getResponseCode(dialog_response, &response_code); if(response_code != INTEGRITY_DIALOG_RESPONSE_UNKNOWN){ break; } } /// Free memory StandardIntegrityDialogRequest_destroy(dialog_request); StandardIntegrityDialogResponse_destroy(dialog_response); /// Handle response code, call the Integrity API again to confirm that the /// verdict issues have been resolved.A caixa de diálogo aparece na parte de cima da atividade fornecida. Quando o usuário fecha a caixa de diálogo, a tarefa é concluída com um código de resposta.
(Opcional) Solicite outro token para mostrar outras caixas de diálogo. Se você fizer solicitações padrão, será necessário ativar o provedor de token novamente para receber um novo veredito.
Solicitar uma caixa de diálogo de integridade para corrigir uma exceção do lado do cliente
Se uma solicitação da API Integrity falhar com um StandardIntegrityException
(API padrão) ou IntegrityServiceException (API clássica) e a
exceção for corrigível, use as caixas de diálogo GET_INTEGRITY ou
GET_STRONG_INTEGRITY para corrigir o erro.
As etapas abaixo descrevem como usar a caixa de diálogo GET_INTEGRITY
para corrigir um erro corrigível do lado do cliente informado pela API Integrity.
Verifique se a exceção retornada de uma solicitação de API Integrity pode ser corrigida.
Kotlin
private fun isExceptionRemediable(exception: ExecutionException): Boolean { val cause = exception.cause if (cause is StandardIntegrityException && cause.isRemediable) { return true } return false }Java
private boolean isExceptionRemediable(ExecutionException exception) { Throwable cause = exception.getCause(); if (cause instanceof StandardIntegrityException integrityException && integrityException.isRemediable()) { return true; } return false; }Unity
private bool IsExceptionRemediable(StandardIntegrityError error) { // Check if the operation resulted in a remediable error if (error != null && error.ErrorCode != StandardIntegrityErrorCode.NoError && error.IsRemediable) { return true; } return false; }Nativo
bool IsErrorRemediable(StandardIntegrityToken* token) { /// Check if the error associated with the token is remediable bool isRemediable = false; if(StandardIntegrityToken_getIsRemediable(response, &isRemediable) == STANDARD_INTEGRITY_NO_ERROR){ return isRemediable; } return false; }Se a exceção for remediável, solicite a caixa de diálogo
GET_INTEGRITYusando a exceção retornada. A caixa de diálogo vai aparecer sobre a atividade fornecida, e a tarefa retornada será concluída com um código de resposta depois que o usuário fechar a caixa de diálogo.Kotlin
private fun showDialog(exception: StandardIntegrityException) { // Create a dialog request val standardIntegrityDialogRequest = StandardIntegrityDialogRequest.builder() .setActivity(activity) .setType(IntegrityDialogTypeCode.GET_INTEGRITY) .setStandardIntegrityResponse(ExceptionDetails(exception)) .build() // Request dialog val responseCode: Task<Int> = standardIntegrityManager.showDialog(standardIntegrityDialogRequest) }Java
private void showDialog(StandardIntegrityException exception) { // Create a dialog request StandardIntegrityDialogRequest standardIntegrityDialogRequest = StandardIntegrityDialogRequest.builder() .setActivity(this.activity) .setType(IntegrityDialogTypeCode.GET_INTEGRITY) .setStandardIntegrityResponse(new ExceptionDetails(exception)) .build(); // Request dialog Task<Integer> responseCode = standardIntegrityManager.showDialog(standardIntegrityDialogRequest); }Unity
// Initialize the V2 manager. Requires Play Integrity Unity Plugin v2.0.0 or // higher. var standardIntegrityManager = new StandardIntegrityManagerV2(); IEnumerator ShowDialogToFixError(StandardIntegrityError error) { PlayAsyncOperation<IntegrityDialogResponseCode, StandardIntegrityError> showDialogTask; using (var activity = UnityPlayerHelper.GetCurrentActivity()) { // Create a dialog request using the error var dialogRequest = new StandardIntegrityDialogRequest(error, activity, GET_INTEGRITY_DIALOG); // Request dialog showDialogTask = standardIntegrityManager.ShowDialog(dialogRequest); } // Wait for PlayAsyncOperation to complete. yield return showDialogTask; }Nativo
private void showDialogToFixError(StandardIntegrityToken* token) { /// If the token request failed, and the underlying error is not fixable /// then return early if(isErrorRemediable(token)) { return; } /// Create dialog request StandardIntegrityDialogRequest* dialog_request; StandardIntegrityDialogRequest_create(&dialog_request); StandardIntegrityDialogRequest_setTypeCode(dialog_request, kGetIntegrityDialogTypeCode); StandardIntegrityDialogRequest_setActivity(dialog_request, activity); StandardIntegrityDialogRequest_setStandardIntegrityToken(dialog_request, token_response); /// Call showDialog with the dialog request. The dialog will be shown on /// top of the provided activity and complete when the dialog is closed by /// the user. StandardIntegrityDialogResponse* dialog_response; StandardIntegrityErrorCode error_code = StandardIntegrityManager_showDialog(dialog_request, &dialog_response); /// Use polling to wait for the async operation to complete. /// Note, the polling shouldn't block the thread where the /// StandardIntegrityManager is running. IntegrityDialogResponseCode response_code = INTEGRITY_DIALOG_RESPONSE_UNKNOWN; while (error_code == STANDARD_INTEGRITY_NO_ERROR) { error_code = StandardIntegrityDialogResponse_getResponseCode(response, &response_code); if(response_code != INTEGRITY_DIALOG_RESPONSE_UNKNOWN){ break; } } /// Free memory StandardIntegrityDialogRequest_destroy(dialog_request); StandardIntegrityDialogResponse_destroy(dialog_response); }Se o código de resposta retornado indicar sucesso, a próxima solicitação de um token de integridade será bem-sucedida sem exceções. Se você fizer solicitações padrão, será necessário ativar o provedor de token novamente para receber um novo veredito.
Códigos de caixas de diálogo de integridade
GET_LICENSED (código de tipo 1)
Problema de veredito
Essa caixa de diálogo é adequada para dois problemas:
- Acesso não autorizado:
appLicensingVerdict: "UNLICENSED". Isso significa que a conta de usuário não tem direito de acesso ao app, o que pode acontecer se o usuário tiver feito o sideload ou adquirido o app em outra app store que não seja o Google Play. - App adulterado:
appRecognitionVerdict: "UNRECOGNIZED_VERSION". Isso significa que o binário do app foi modificado ou não é uma versão reconhecida pelo Google Play.
Correção
Você pode mostrar a caixa de diálogo GET_LICENSED para pedir que o usuário adquira o
app original no Google Play. Essa caixa de diálogo única aborda os dois cenários:
- Para um usuário sem licença, ele concede uma licença do Google Play. Isso permite que o usuário receba atualizações do app pelo Google Play.
- Para um usuário com uma versão do app adulterada, ele orienta a instalação do app não modificado do Google Play.
Quando o usuário conclui a caixa de diálogo, as verificações de integridade subsequentes retornam
appLicensingVerdict: "LICENSED" e
appRecognitionVerdict: "PLAY_RECOGNIZED".
Exemplo de UX
CLOSE_UNKNOWN_ACCESS_RISK (código de tipo 2)
Problema de veredito
Quando environmentDetails.appAccessRiskVerdict.appsDetected contém
"UNKNOWN_CAPTURING" ou "UNKNOWN_CONTROLLING", isso significa que há outros apps
(não instalados pelo Google Play ou pré-carregados na partição do sistema pelo fabricante
do dispositivo) em execução no dispositivo que podem estar capturando a tela ou
controlando o dispositivo.
Correção
Você pode mostrar a caixa de diálogo CLOSE_UNKNOWN_ACCESS_RISK para pedir que o usuário feche
todos os apps desconhecidos que possam estar capturando a tela ou controlando o dispositivo.
Se o usuário tocar no botão Close all, todos esses apps serão fechados.
Exemplo de UX
CLOSE_ALL_ACCESS_RISK (código de tipo 3)
Problema de veredito
Quando environmentDetails.appAccessRiskVerdict.appsDetected contém
"KNOWN_CAPTURING", "KNOWN_CONTROLLING","UNKNOWN_CAPTURING" ou
"UNKNOWN_CONTROLLING", isso significa que há apps em execução no dispositivo que
podem estar capturando a tela ou controlando o dispositivo.
Correção
Você pode mostrar a caixa de diálogo CLOSE_ALL_ACCESS_RISK para pedir que o usuário feche todos
os apps que podem estar capturando a tela ou controlando o dispositivo. Se o
usuário tocar no botão Close all, todos esses apps serão fechados no dispositivo.
Exemplo de UX
GET_INTEGRITY (código de tipo 4)
Problema de veredito
Essa caixa de diálogo é adequada para qualquer um dos seguintes problemas:
Integridade do dispositivo fraca: quando o
deviceRecognitionVerdictnão contémMEETS_DEVICE_INTEGRITY, o dispositivo pode não ser um dispositivo Android genuíno e certificado. Isso pode acontecer, por exemplo, se o carregador de inicialização do dispositivo estiver desbloqueado ou se o SO Android carregado não for uma imagem certificada do fabricante.Acesso não autorizado:
appLicensingVerdict: "UNLICENSED". Isso significa que a conta de usuário não tem direito de acesso ao app, o que pode acontecer se o usuário tiver feito o sideload ou adquirido o app em outra app store que não seja o Google Play.App adulterado:
appRecognitionVerdict: "UNRECOGNIZED_VERSION". Isso significa que o binário do app foi modificado ou não é uma versão reconhecida pelo Google Play.Exceções do lado do cliente: quando ocorre uma exceção remediável durante uma solicitação de API Integrity. As exceções que podem ser corrigidas são exceções da API Integrity com códigos do erro como
PLAY_SERVICES_VERSION_OUTDATED,NETWORK_ERROR,PLAY_SERVICES_NOT_FOUNDetc. Use o métodoexception.isRemediable()para verificar se uma exceção pode ser corrigida pela caixa de diálogo.
Correção
A caixa de diálogo GET_INTEGRITY foi projetada para simplificar a experiência do usuário, lidando com várias etapas de correção em um único fluxo contínuo. Isso
evita que o usuário tenha que interagir com várias caixas de diálogo separadas para corrigir
problemas diferentes.
Quando você solicita a caixa de diálogo, ela detecta automaticamente quais problemas de veredicto estão presentes e fornece as etapas de correção adequadas. Isso significa que uma única solicitação de caixa de diálogo pode resolver vários problemas de uma só vez, incluindo:
- Integridade do dispositivo: se um problema de integridade do dispositivo for detectado, a caixa de diálogo vai
orientar o usuário a melhorar o status de segurança do dispositivo para atender aos
requisitos de um veredito
MEETS_DEVICE_INTEGRITY. - Integridade do app: se forem detectados problemas como acesso não autorizado ou adulteração do app, a caixa de diálogo vai direcionar os usuários para adquirir o app na Google Play Store e corrigir esses problemas.
- Exceções do lado do cliente: a caixa de diálogo verifica e tenta resolver os problemas que causaram uma exceção da API Integrity. Por exemplo, ele pode solicitar que o usuário atualize uma versão desatualizada do Google Play Services.
Exemplo de UX
GET_STRONG_INTEGRITY (código de tipo 5)
Problema de veredito
Essa caixa de diálogo foi projetada para corrigir todos os problemas que o
GET_INTEGRITY
resolve, com o recurso adicional de corrigir problemas que impedem que um dispositivo
receba um veredito MEETS_STRONG_INTEGRITY e corrigir problemas de veredito do
Play Protect.
Correção
O GET_STRONG_INTEGRITY foi projetado para simplificar a experiência do usuário, lidando com várias etapas de correção em um único fluxo contínuo. A caixa de diálogo
verifica automaticamente se há problemas de integridade aplicáveis ao endereço, incluindo:
- Integridade do dispositivo: se um problema de integridade do dispositivo for detectado, a caixa de diálogo vai
orientar o usuário a melhorar o status de segurança do dispositivo para atender aos
requisitos de um veredito
MEETS_STRONG_INTEGRITY. Status do Play Protect: se o
playProtectVerdictindicar um problema, a caixa de diálogo vai orientar o usuário para corrigi-lo:- Se o Play Protect estiver desativado (
playProtectVerdict == POSSIBLE_RISK), a caixa de diálogo vai solicitar que o usuário o ative e faça uma verificação de todos os apps no dispositivo. - Se apps nocivos forem detectados (
playProtectVerdict == MEDIUM_RISKouHIGH_RISK), a caixa de diálogo vai direcionar o usuário para desinstalá-los usando o Google Play Protect.
- Se o Play Protect estiver desativado (
Integridade do app: se problemas como acesso não autorizado ou adulteração do app forem detectados, a caixa de diálogo vai solicitar que o usuário adquira o app na Google Play Store para corrigir o problema.
Exceções do lado do cliente: a caixa de diálogo também tenta resolver os problemas que causaram uma exceção da API Integrity. Por exemplo, ele pode solicitar que o usuário ative o Google Play Services se ele estiver desativado. As exceções corrigíveis são exceções da API Integrity com códigos de erro como
PLAY_SERVICES_VERSION_OUTDATED,NETWORK_ERRORouPLAY_SERVICES_NOT_FOUND. Use o métodoexception.isRemediable()para verificar se um erro pode ser corrigido pela caixa de diálogo.
Exemplo de UX