درخواست رضایت یک بار برای خواندن کد تأیید پیامکی

در این صفحه نحوه استفاده از SMS User Consent API برای درخواست رضایت کاربر برای خواندن یک پیام تأیید صحت پیامک توضیح داده شده است. در صورت رضایت کاربر، API متن پیام را برمی‌گرداند که می‌توانید کد تأیید را دریافت کرده و فرآیند تأیید را تکمیل کنید.

وابستگی ها را نصب کنید

جزء تأیید اعتبار خدمات Play را در فایل build.gradle برنامه خود قرار دهید:

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. شماره تلفن کاربر را دریافت کنید

اگر شماره تلفن کاربر را ندارید، قبل از شروع جریان تأیید پیامک، آن را درخواست کنید.

می توانید شماره تلفن کاربر را به روشی که برای برنامه شما مناسب است به دست آورید. اگر این اطلاعات برای ایجاد حساب کاربری مورد نیاز نبود ، از انتخابگر راهنمایی Smart Lock for Passwords استفاده کنید تا به کاربر کمک کند شماره تلفن خود را پر کند. برای استفاده از انتخابگر اشاره:

کاتلین

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
            }
        // ...
    }
}

جاوا

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. شروع به گوش دادن به پیام های دریافتی کنید

سپس، متد startSmsUserConsent() API رضایت کاربر SMS را فراخوانی کنید تا به پیام‌های دریافتی گوش دهید. اگر شماره تلفنی را می‌دانید که پیامک از آن منشأ می‌گیرد، آن را مشخص کنید (در غیر این صورت، null ارسال کنید). به این ترتیب، API رضایت کاربر پیامک فقط روی پیام‌های این شماره فعال می‌شود.

برای شروع گوش دادن:

کاتلین

// 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 */)

جاوا

// 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 */);

هنگامی که به پیام‌های SMS دریافتی گوش می‌دهید، می‌توانید از سیستم تأیید خود بخواهید کد تأیید را به شماره تلفن کاربر که در مرحله اول دریافت کرده‌اید ارسال کند.

برای پنج دقیقه آینده، هنگامی که دستگاه یک پیام کوتاه حاوی یک کد یکبار مصرف دریافت می‌کند، خدمات Play به برنامه شما ارسال می‌کند تا از کاربر اجازه خواندن پیام را بخواهد. یک پیام تنها در صورتی پخش را فعال می کند که این معیارها را داشته باشد:

  • پیام حاوی یک رشته الفبایی 4 تا 10 کاراکتری با حداقل یک عدد است.
  • اگر شماره تلفن فرستنده را مشخص کرده باشید، پیام توسط آن شماره ارسال شده است.

این پخش‌ها را با یک گیرنده پخش که دارای مجوز SEND_PERMISSION است و به اهداف SMS_RETRIEVED_ACTION پاسخ می‌دهد، مدیریت کنید. برای ایجاد و ثبت گیرنده پخش:

کاتلین

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)
}

جاوا

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);
}

با شروع یک فعالیت برای EXTRA_CONSENT_INTENT ، از کاربر می‌خواهید برای یک بار اجازه خواندن محتوای پیام را دریافت کند.

3. کد تأیید را از یک پیام دریافت کنید

در متد onActivityResult() ، پاسخ کاربر به درخواست مجوز شما را مدیریت کنید. اگر کد نتیجه RESULT_OK را دریافت کنید، کاربر اجازه خواندن محتوای پیام را می دهد و می توانید متن پیام را از intent دریافت کنید.

کاتلین

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.
            }
    }
}

جاوا

@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;
    }
}

پس از دریافت متن پیام، می‌توانید کد تأیید را تجزیه کنید و فرم را به‌طور خودکار پر کنید یا جریان تأیید را تکمیل کنید.