ขอความยินยอมแบบครั้งเดียวเพื่ออ่านรหัสยืนยันทาง SMS

หน้านี้จะอธิบายวิธีใช้ SMS User Consent API เพื่อขอความยินยอมจากผู้ใช้ ให้อ่านข้อความยืนยันทาง SMS เพียงข้อความเดียว หากผู้ใช้ยินยอม API จะแสดงผล ข้อความซึ่งคุณรับรหัสยืนยันและ โปรดทำตามขั้นตอนการยืนยันให้เสร็จสมบูรณ์

ติดตั้งการอ้างอิง

รวมคอมโพเนนต์การตรวจสอบสิทธิ์ของบริการ Google 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. ดูหมายเลขโทรศัพท์ของผู้ใช้

หากไม่มีหมายเลขโทรศัพท์ของผู้ใช้ ให้ขอหมายเลขดังกล่าวก่อนเริ่ม SMS ขั้นตอนการยืนยัน

คุณสามารถขอรับหมายเลขโทรศัพท์ของผู้ใช้ได้ด้วยวิธีที่เหมาะสมกับ แอป ลองใช้ ตัวเลือกคำแนะนำ Smart Lock สำหรับรหัสผ่าน เพื่อช่วยให้ผู้ใช้กรอกหมายเลขโทรศัพท์หากไม่จำเป็น ในการสร้างบัญชีของผู้ใช้ วิธีใช้ตัวเลือกคำแนะนำ

KotlinJava
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() ของ SMS User Consent API เพื่อเริ่ม กำลังฟังข้อความขาเข้า ถ้าคุณทราบหมายเลขโทรศัพท์ที่ส่ง SMS เริ่มต้น ให้ระบุข้อความ (มิฉะนั้นก็ให้ส่งผ่าน null) ทำให้ SMS User Consent API จะทริกเกอร์เฉพาะข้อความจากหมายเลขนี้เท่านั้น

วิธีเริ่มฟัง

KotlinJava
// 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 ขาเข้าแล้ว คุณจะรับการยืนยันได้ ระบบจะส่งรหัสยืนยันไปยังหมายเลขโทรศัพท์ของผู้ใช้ซึ่งคุณได้ป้อนเข้าไป ขั้นตอนแรก

ในช่วง 5 นาทีต่อจากนี้ เมื่ออุปกรณ์ได้รับข้อความ SMS ที่มี รหัสแบบใช้ครั้งเดียว บริการ Google Play จะประกาศ Intent ไปยังแอปของคุณ เพื่อขออนุญาตอ่านข้อความจากผู้ใช้ ข้อความจะทริกเกอร์การออกอากาศ เฉพาะเมื่อเป็นไปตามเกณฑ์ต่อไปนี้

  • ข้อความมีสตริงที่เป็นตัวอักษรและตัวเลขคละกัน 4-10 อักขระโดยมีอย่างน้อย 1 ตัว หมายเลข
  • หากคุณระบุหมายเลขโทรศัพท์ของผู้ส่ง ข้อความนั้นมาจากผู้ส่ง หมายเลข

จัดการการออกอากาศเหล่านี้ด้วย Broadcast Receiver ที่มี SEND_PERMISSION และตอบสนองต่อ Intent SMS_RETRIEVED_ACTION ได้ หากต้องการสร้างและ ลงทะเบียน Broadcast Receiver:

KotlinJava
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 ผู้ใช้ได้รับสิทธิ์ สิทธิ์ในการอ่านเนื้อหาของข้อความ และคุณจะได้รับข้อความดังกล่าว จากความตั้งใจ

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

เมื่อได้รับข้อความแล้ว คุณสามารถแยกวิเคราะห์รหัสยืนยันและ กรอกแบบฟอร์มอัตโนมัติ หรือดำเนินการตามขั้นตอนการยืนยันให้เสร็จสมบูรณ์