این صفحه نحوه استفاده از 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'
۱. دریافت شماره تلفن کاربر
اگر شماره تلفن کاربر را ندارید، قبلاز شروع کردن جریان درستیسنجی پیامکی، آن را درخواست کنید.
میتوانید شماره تلفن کاربر را به روشی که برای برنامهتان مناسب است دریافت کنید. اگر این اطلاعات برای ایجاد حساب کاربر لازم نبود، انتخابگر اشاره Smart Lock برای گذرواژهها را برای کمک به کاربر در تکمیل شماره تلفنش درنظر بگیرید. برای استفاده از انتخابگر راهنمایی:
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
}
// ...
}
}
جاوا
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;
// ...
}
}
۲. شروع گوش دادن به پیامهای ورودی
سپس، برای شروع گوش دادن به پیامهای ورودی، روش startSmsUserConsent() مربوط به SMS User Consent API را فراخوانی کنید. اگر شماره تلفنی را که پیامک از آن ارسال میشود میدانید، آن را مشخص کنید (درغیراینصورت، null را ارسال کنید). با این کار، SMS User Consent API فقط برای پیامهای ارسالشده از این شماره فعال میشود.
برای شروع گوش دادن:
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 */)
جاوا
// 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 */);
وقتی منتظر دریافت پیامکهای ورودی هستید، میتوانید از سیستم درستیسنجیتان بخواهید کد درستیسنجی را به شماره تلفن کاربر که در مرحله اول دریافت کردید ارسال کند.
در پنج دقیقه بعدی، وقتی دستگاه پیامکی حاوی کد یکبارمصرف دریافت میکند، «خدمات Play» قصدی را به برنامه شما ارسال میکند تا از کاربر برای خواندن پیام اجازه بگیرد. پیام فقط درصورتی همهفرستی را راهاندازی میکند که این معیارها را داشته باشد:
- پیام حاوی رشته الفباعددی ۴ تا ۱۰ نویسهای با حداقل یک عدد است.
- اگر شماره تلفن فرستنده را مشخص کرده باشید، پیام از آن شماره ارسال شده است.
این همهفرستیها را با گیرنده همهفرستیای مدیریت کنید که اجازه SEND_PERMISSION را دارد و به هدفهای SMS_RETRIEVED_ACTION پاسخ میدهد. برای ایجاد و
ثبت گیرنده رویداد ثبتشده:
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)
}
جاوا
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، از کاربر درخواست میکنید
اجازه دسترسی یکباره برای خواندن محتوای پیام بدهد.
۳. دریافت کد درستیسنجی از پیام
در روش onActivityResult()، پاسخ کاربر به درخواستتان برای اجازه را مدیریت کنید. اگر کد نتیجه RESULT_OK را دریافت کردید، کاربر اجازه خواندن محتوای پیام را داده است و میتوانید نوشتار پیام را از هدف دریافت کنید.
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.
}
}
}
جاوا
@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;
}
}
وقتی نوشتار پیام را دریافت کردید، میتوانید کد درستیسنجی را تجزیه کنید و فرم را بهطور خودکار تکمیل کنید یا بهطریق دیگری جریان درستیسنجی را تکمیل کنید.