На этой странице описывается, как решать проблемы, связанные с вердиктами о добросовестности.
При запросе токена целостности вы можете отобразить пользователю диалоговое окно Google Play. Вы можете отобразить это диалоговое окно, если в результате проверки целостности обнаружена одна или несколько проблем. Диалоговое окно отображается поверх вашего приложения и предлагает пользователю устранить причину проблемы. После закрытия диалогового окна вы можете убедиться в устранении проблемы, отправив ещё один запрос к Integrity API.
Запросить диалог о целостности
Когда клиент запрашивает токен целостности, можно использовать метод, предлагаемый в StandardIntegrityToken (стандартный API) и IntegrityTokenResponse (классический API): showDialog(Activity activity, int integrityDialogTypeCode)
.
Ниже описано, как использовать API Play Integrity для отображения диалогового окна с запросом исправления с помощью кода диалога GET_LICENSED . Другие коды диалоговых окон, которые может запросить ваше приложение, перечислены после этого раздела.
Запросите токен целостности из вашего приложения и отправьте его на сервер. Вы можете использовать стандартный или классический запрос.
Котлин
// 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())
Ява
// 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());
Единство
// 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);
Родной
/// 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));
На сервере расшифруйте токен целостности и проверьте поле
appLicensingVerdict
. Оно может выглядеть примерно так:// Licensing issue { ... accountDetails: { appLicensingVerdict: "UNLICENSED" } }
Если токен содержит
appLicensingVerdict: "UNLICENSED"
, отправьте клиенту приложения запрос на отображение диалогового окна лицензирования:Котлин
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 }
Ява
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; }
Единство
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; }
Родной
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; }
В своем приложении вызовите
showDialog
с запрошенным кодом, полученным с вашего сервера:Котлин
// Show dialog as indicated by the server val showDialogType: Int? = yourServerResponse.integrityDialogTypeCode() if (showDialogType != null) { // Call showDialog with type code, the dialog will be shown on top of the // provided activity and complete when the dialog is closed. val integrityDialogResponseCode: Task<Int> = tokenResponse.showDialog(activity, showDialogType) // Handle response code, call the Integrity API again to confirm that // verdicts have been resolved. }
Ява
// Show dialog as indicated by the server @Nullable Integer showDialogType = yourServerResponse.integrityDialogTypeCode(); if (showDialogType != null) { // Call showDialog with type code, the dialog will be shown on top of the // provided activity and complete when the dialog is closed. Task<Integer> integrityDialogResponseCode = tokenResponse.showDialog(activity, showDialogType); // Handle response code, call the Integrity API again to confirm that // verdicts have been resolved. }
Единство
IEnumerator ShowDialogCoroutine() { int showDialogType = yourServerResponse.IntegrityDialogTypeCode(); // Call showDialog with type code, the dialog will be shown on top of the // provided activity and complete when the dialog is closed. var showDialogTask = tokenResponse.ShowDialog(showDialogType); // Wait for PlayAsyncOperation to complete. yield return showDialogTask; // Handle response code, call the Integrity API again to confirm that // verdicts have been resolved. }
Unreal Engine
// .h void MyClass::OnShowDialogCompleted( EStandardIntegrityErrorCode Error, EIntegrityDialogResponseCode Response) { // Handle response code, call the Integrity API again to confirm that // verdicts have 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); }
Родной
// Show dialog as indicated by the server int show_dialog_type = yourServerResponse.integrityDialogTypeCode(); if (show_dialog_type != 0) { /// Call showDialog with type code, the dialog will be shown on top of the /// provided activity and complete when the dialog is closed. StandardIntegrityErrorCode error_code = IntegrityTokenResponse_showDialog(response, activity, show_dialog_type); /// Proceed to polling iff error_code == STANDARD_INTEGRITY_NO_ERROR if (error_code != STANDARD_INTEGRITY_NO_ERROR) { /// Remember to call the *_destroy() functions. return; } /// Use polling to wait for the async operation to complete. /// Note, the polling shouldn't block the thread where the IntegrityManager /// is running. IntegrityDialogResponseCode* response_code; error_code = StandardIntegrityToken_getDialogResponseCode(response, response_code); if (error_code != STANDARD_INTEGRITY_NO_ERROR) { /// Remember to call the *_destroy() functions. return; } /// Handle response code, call the Integrity API again to confirm that /// verdicts have been resolved. }
Диалог отображается поверх предоставленного действия. Когда пользователь закрывает диалог, задача завершается с кодом ответа .
(Необязательно) Запросите ещё один токен для отображения дальнейших диалоговых окон. При выполнении стандартных запросов необходимо повторно прогреть поставщика токена для получения нового вердикта.
Коды диалога целостности
GET_LICENSED (код типа 1)
Вопрос о вердикте
Этот диалог уместен в двух случаях:
- Несанкционированный доступ :
appLicensingVerdict: "UNLICENSED"
. Это означает, что у учётной записи пользователя нет прав на ваше приложение. Это может произойти, если пользователь загрузил его из сторонних источников или приобрёл его не в Google Play, а в магазине приложений. - Приложение изменено :
appRecognitionVerdict: "UNRECOGNIZED_VERSION"
. Это означает, что исполняемый файл вашего приложения был изменён или его версия не распознаётся Google Play.
Ремедиация
Вы можете отобразить диалоговое окно GET_LICENSED
, чтобы предложить пользователю приобрести оригинальное приложение из Google Play. Этот диалог решает оба сценария:
- Пользователю без лицензии предоставляется лицензия Play. Это позволяет получать обновления приложений из Google Play.
- Пользователям с измененной версией приложения предлагается установить немодифицированное приложение из Google Play.
Когда пользователь завершает диалог, последующие проверки целостности возвращают appLicensingVerdict: "LICENSED"
и appRecognitionVerdict: "PLAY_RECOGNIZED"
.
Пример UX

CLOSE_UNKNOWN_ACCESS_RISK (код типа 2)
Вопрос о вердикте
Если environmentDetails.appAccessRiskVerdict.appsDetected
содержит "UNKNOWN_CAPTURING"
или "UNKNOWN_CONTROLLING"
, это означает, что на устройстве запущены неизвестные приложения, которые могут захватывать экран или управлять устройством.
Ремедиация
Вы можете отобразить диалоговое окно CLOSE_UNKNOWN_ACCESS_RISK
, чтобы предложить пользователю закрыть все неизвестные приложения, которые могут делать снимки экрана или управлять устройством. Если пользователь нажмет кнопку Close all
, все такие приложения будут закрыты.
Пример UX

CLOSE_ALL_ACCESS_RISK (код типа 3)
Вопрос о вердикте
Если environmentDetails.appAccessRiskVerdict.appsDetected
содержит любое из значений "KNOWN_CAPTURING"
, "KNOWN_CONTROLLING"
, "UNKNOWN_CAPTURING"
или "UNKNOWN_CONTROLLING"
, это означает, что на устройстве запущены приложения, которые могут захватывать экран или управлять устройством.
Ремедиация
Вы можете отобразить диалоговое окно CLOSE_ALL_ACCESS_RISK
, предлагающее пользователю закрыть все приложения, которые могут делать снимки экрана или управлять устройством. Если пользователь нажмет кнопку Close all
, все такие приложения будут закрыты на устройстве.
Пример UX
