Wysyłanie prośby o jednorazową zgodę na odczytanie kodu weryfikacyjnego z SMS-a

Z tego artykułu dowiesz się, jak za pomocą interfejsu SMS User Consent API prosić użytkownika o zgodę na przeczytanie pojedynczej wiadomości weryfikacyjnej SMS. Jeśli użytkownik wyrazi zgodę, interfejs API zwraca tekst wiadomości, z którego można uzyskać kod weryfikacyjny i przejść proces weryfikacji.

Instalowanie zależności

Umieść komponent uwierzytelniania Usług Google Play w pliku build.gradle aplikacji:

implementation 'com.google.android.gms:play-services-auth:17.0.0'
implementation 'com.google.android.gms:play-services-auth-api-phone:17.4.0'

1. Uzyskaj numer telefonu użytkownika

Jeśli nie masz numeru telefonu użytkownika, poproś o niego przed rozpoczęciem procesu weryfikacji SMS-em.

Numer telefonu użytkownika możesz uzyskać w sposób odpowiedni dla Twojej aplikacji. Możesz skorzystać z selektora wskazówek Smart Lock na hasła, aby ułatwić użytkownikowi podanie numeru telefonu, jeśli te informacje nie były wymagane do utworzenia konta użytkownika. Aby użyć selektora podpowiedzi:

Kotlin

private val CREDENTIAL_PICKER_REQUEST = 1  // Set to an unused request code

// Construct a request for phone numbers and show the picker
private fun requestHint() {
    val hintRequest = HintRequest.Builder()
        .setPhoneNumberIdentifierSupported(true)
        .build()
    val credentialsClient = Credentials.getClient(this)
    val intent = credentialsClient.getHintPickerIntent(hintRequest)
    startIntentSenderForResult(
        intent.intentSender,
        CREDENTIAL_PICKER_REQUEST,
        null, 0, 0, 0
    )
}

public override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
    super.onActivityResult(requestCode, resultCode, data)
    when (requestCode) {
        CREDENTIAL_PICKER_REQUEST ->
            // Obtain the phone number from the result
            if (resultCode == Activity.RESULT_OK && data != null) {
                val credential = data.getParcelableExtra<Credential>(Credential.EXTRA_KEY)
                // credential.getId();  <-- will need to process phone number string
            }
        // ...
    }
}

Java

private static final int CREDENTIAL_PICKER_REQUEST = 1;  // Set to an unused request code

// Construct a request for phone numbers and show the picker
private void requestHint() throws IntentSender.SendIntentException {
    HintRequest hintRequest = new HintRequest.Builder()
            .setPhoneNumberIdentifierSupported(true)
            .build();
    PendingIntent intent = Credentials.getClient(this).getHintPickerIntent(hintRequest);
    startIntentSenderForResult(intent.getIntentSender(),
            RESOLVE_HINT, null, 0, 0, 0);
}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    switch (requestCode) {
        case CREDENTIAL_PICKER_REQUEST:
            // Obtain the phone number from the result
            if (resultCode == RESULT_OK) {
                Credential credential = data.getParcelableExtra(Credential.EXTRA_KEY);
                // credential.getId();  <-- will need to process phone number string
            }
            break;
        // ...
    }
}

2. Zacznij nasłuchiwać wiadomości przychodzących

Następnie wywołaj metodę startSmsUserConsent() interfejsu SMS User Consent API, aby rozpocząć nasłuchiwanie wiadomości przychodzących. Jeśli znasz numer telefonu, z którego pochodzi SMS-a, podaj go (w przeciwnym razie przekaż null). Dzięki temu interfejs SMS User Consent API będzie się uruchamiać tylko dla wiadomości z tego numeru.

Aby zacząć słuchać:

Kotlin

// Start listening for SMS User Consent broadcasts from senderPhoneNumber
// The Task<Void> will be successful if SmsRetriever was able to start
// SMS User Consent, and will error if there was an error starting.
val task = SmsRetriever.getClient(context).startSmsUserConsent(senderPhoneNumber /* or null */)

Java

// Start listening for SMS User Consent broadcasts from senderPhoneNumber
// The Task<Void> will be successful if SmsRetriever was able to start
// SMS User Consent, and will error if there was an error starting.
Task<Void> task = SmsRetriever.getClient(context).startSmsUserConsent(senderPhoneNumber /* or null */);

Kiedy będziesz odsłuchiwać przychodzące SMS-y, system weryfikacyjny może wysłać kod weryfikacyjny na numer telefonu użytkownika, który został podany w pierwszym kroku.

Gdy urządzenie otrzyma SMS-a z jednorazowym kodem, przez następne 5 minut Usługi Google Play będą przesyłać do Twojej aplikacji intencję z prośbą o pozwolenie na jej przeczytanie. Wiadomość aktywuje transmisję tylko wtedy, gdy spełnia te kryteria:

  • Wiadomość zawiera ciąg 4–10 znaków alfanumerycznych i co najmniej 1 cyfrę.
  • Jeśli podano numer telefonu nadawcy, wiadomość została wysłana z tego numeru.

Obsługuj te komunikaty za pomocą odbiornika, który ma uprawnienia SEND_PERMISSION i reaguje na intencje SMS_RETRIEVED_ACTION. Aby utworzyć i zarejestrować odbiornik:

Kotlin

private val SMS_CONSENT_REQUEST = 2  // Set to an unused request code
private val smsVerificationReceiver = object : BroadcastReceiver() {
    override fun onReceive(context: Context, intent: Intent) {
        if (SmsRetriever.SMS_RETRIEVED_ACTION == intent.action) {
            val extras = intent.extras
            val smsRetrieverStatus = extras?.get(SmsRetriever.EXTRA_STATUS) as Status

            when (smsRetrieverStatus.statusCode) {
                CommonStatusCodes.SUCCESS -> {
                    // Get consent intent
                    val consentIntent = extras.getParcelable<Intent>(SmsRetriever.EXTRA_CONSENT_INTENT)
                    try {
                        // Start activity to show consent dialog to user, activity must be started in
                        // 5 minutes, otherwise you'll receive another TIMEOUT intent
                        startActivityForResult(consentIntent, SMS_CONSENT_REQUEST)
                    } catch (e: ActivityNotFoundException) {
                        // Handle the exception ...
                    }
                }
                CommonStatusCodes.TIMEOUT -> {
                    // Time out occurred, handle the error.
                }
            }
        }
    }
}

override fun onCreate(savedInstanceState: Bundle?) {
    // ...

    val intentFilter = IntentFilter(SmsRetriever.SMS_RETRIEVED_ACTION)
    registerReceiver(smsVerificationReceiver, SmsRetriever.SEND_PERMISSION, intentFilter)
}

Java

private static final int SMS_CONSENT_REQUEST = 2;  // Set to an unused request code
private final BroadcastReceiver smsVerificationReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        if (SmsRetriever.SMS_RETRIEVED_ACTION.equals(intent.getAction())) {
            Bundle extras = intent.getExtras();
            Status smsRetrieverStatus = (Status) extras.get(SmsRetriever.EXTRA_STATUS);

            switch (smsRetrieverStatus.getStatusCode()) {
                case CommonStatusCodes.SUCCESS:
                    // Get consent intent
                    Intent consentIntent = extras.getParcelable(SmsRetriever.EXTRA_CONSENT_INTENT);
                    try {
                        // Start activity to show consent dialog to user, activity must be started in
                        // 5 minutes, otherwise you'll receive another TIMEOUT intent
                        startActivityForResult(consentIntent, SMS_CONSENT_REQUEST);
                    } catch (ActivityNotFoundException e) {
                        // Handle the exception ...
                    }
                    break;
                case CommonStatusCodes.TIMEOUT:
                    // Time out occurred, handle the error.
                    break;
            }
        }
    }
};

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    // ...

    IntentFilter intentFilter = new IntentFilter(SmsRetriever.SMS_RETRIEVED_ACTION);
    registerReceiver(smsVerificationReceiver, SmsRetriever.SEND_PERMISSION, intentFilter);
}

Rozpoczynając aktywność dotyczącą EXTRA_CONSENT_INTENT, prosisz użytkownika o jednorazowe uprawnienie do odczytu treści wiadomości.

3. Uzyskiwanie kodu weryfikacyjnego z wiadomości

W metodzie onActivityResult() przetwórz odpowiedź użytkownika na Twoją prośbę o uprawnienia. Jeśli otrzymasz kod wyniku RESULT_OK, użytkownik przyznał użytkownikowi uprawnienia do odczytu treści wiadomości, dzięki czemu możesz pobrać tekst wiadomości z intencji.

Kotlin

public override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
    super.onActivityResult(requestCode, resultCode, data)
    when (requestCode) {
        // ...
        SMS_CONSENT_REQUEST ->
            // Obtain the phone number from the result
            if (resultCode == Activity.RESULT_OK && data != null) {
                // Get SMS message content
                val message = data.getStringExtra(SmsRetriever.EXTRA_SMS_MESSAGE)
                // Extract one-time code from the message and complete verification
                // `message` contains the entire text of the SMS message, so you will need
                // to parse the string.
                val oneTimeCode = parseOneTimeCode(message) // define this function

                // send one time code to the server
            } else {
                // Consent denied. User can type OTC manually.
            }
    }
}

Java

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    switch (requestCode) {
        // ...
        case SMS_CONSENT_REQUEST:
            if (resultCode == RESULT_OK) {
                // Get SMS message content
                String message = data.getStringExtra(SmsRetriever.EXTRA_SMS_MESSAGE);
                // Extract one-time code from the message and complete verification
                // `sms` contains the entire text of the SMS message, so you will need
                // to parse the string.
                String oneTimeCode = parseOneTimeCode(message); // define this function

                // send one time code to the server
            } else {
                // Consent canceled, handle the error ...
            }
            break;
    }
}

Po otrzymaniu tekstu wiadomości możesz przeanalizować kod weryfikacyjny i automatycznie wypełnić formularz lub dokończyć proces weryfikacji.