ขอการยืนยันทาง SMS ในแอป Android

หากต้องการยืนยันหมายเลขโทรศัพท์โดยอัตโนมัติ คุณต้องใช้ทั้งส่วนไคลเอ็นต์และส่วนเซิร์ฟเวอร์ของขั้นตอนการยืนยัน เอกสารนี้อธิบายวิธี ใช้ส่วนไคลเอ็นต์ในแอป Android

หากต้องการเริ่มขั้นตอนการยืนยันหมายเลขโทรศัพท์ในแอป Android ให้ส่งหมายเลขโทรศัพท์ไปยังเซิร์ฟเวอร์ยืนยันและเรียกใช้ SMS Retriever API เพื่อเริ่มฟังข้อความ SMS ที่มีรหัสแบบครั้งเดียวสำหรับแอป หลังจากได้รับข้อความแล้ว ให้ส่งรหัสแบบครั้งเดียวกลับไปยังเซิร์ฟเวอร์เพื่อดำเนินการยืนยันให้เสร็จสมบูรณ์

หากต้องการเตรียมแอป ให้ทำตามขั้นตอนในส่วนต่อไปนี้

ข้อกำหนดเบื้องต้นของแอป

ตรวจสอบว่าไฟล์บิลด์ของแอปใช้ค่าต่อไปนี้

  • minSdkVersion 19 ขึ้นไป
  • compileSdkVersion 28 ขึ้นไป

กำหนดค่าแอป

ในไฟล์ build.gradle ระดับโปรเจ็กต์ ให้รวมที่เก็บ Maven ของ Google และที่เก็บ Maven Central ไว้ทั้งในส่วน buildscript และ allprojects

buildscript {
    repositories {
        google()
        mavenCentral()
    }
}

allprojects {
    repositories {
        google()
        mavenCentral()
    }
}

เพิ่มทรัพยากร Dependency ของ Google Play services สำหรับ SMS Retriever API ลงในไฟล์บิลด์ Gradle ของโมดูล ซึ่งโดยทั่วไปคือ app/build.gradle

dependencies {
  implementation 'com.google.android.gms:play-services-auth:21.4.0'
  implementation 'com.google.android.gms:play-services-auth-api-phone:18.2.0'
}

1. รับหมายเลขโทรศัพท์ของผู้ใช้

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

// Construct a request for phone numbers and show the picker
private void requestHint() {
    HintRequest hintRequest = new HintRequest.Builder()
            .setPhoneNumberIdentifierSupported(true)
            .build();

    PendingIntent intent = Auth.CredentialsApi.getHintPickerIntent(
            apiClient, hintRequest);
    startIntentSenderForResult(intent.getIntentSender(),
            RESOLVE_HINT, null, 0, 0, 0);
}

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

2. เริ่มตัวดึงข้อมูล SMS

เมื่อพร้อมยืนยันหมายเลขโทรศัพท์ของผู้ใช้แล้ว ให้รับอินสแตนซ์ของออบเจ็กต์ SmsRetrieverClient เรียกใช้ startSmsRetriever และแนบ Listener ที่สำเร็จและ ล้มเหลวกับงานการดึงข้อมูล SMS

// Get an instance of SmsRetrieverClient, used to start listening for a matching
// SMS message.
SmsRetrieverClient client = SmsRetriever.getClient(this /* context */);

// Starts SmsRetriever, which waits for ONE matching SMS message until timeout
// (5 minutes). The matching SMS message will be sent via a Broadcast Intent
// with action SmsRetriever#SMS_RETRIEVED_ACTION.
Task<Void> task = client.startSmsRetriever();

// Listen for success/failure of the start Task. If in a background thread, this
// can be made blocking using Tasks.await(task, [timeout]);
task.addOnSuccessListener(new OnSuccessListener<Void>() {
  @Override
  public void onSuccess(Void aVoid) {
    // Successfully started retriever, expect broadcast intent
    // ...
  }
});

task.addOnFailureListener(new OnFailureListener() {
  @Override
  public void onFailure(@NonNull Exception e) {
    // Failed to start retriever, inspect Exception for more details
    // ...
  }
});

งานการดึงข้อมูล SMS จะรอข้อความ SMS นานสูงสุด 5 นาที ซึ่งมีสตริงที่ไม่ซ้ำกันที่ระบุแอปของคุณ

3. ส่งหมายเลขโทรศัพท์ไปยังเซิร์ฟเวอร์

หลังจากได้รับหมายเลขโทรศัพท์ของผู้ใช้และเริ่มรอรับข้อความ SMS แล้ว ให้ส่งหมายเลขโทรศัพท์ของผู้ใช้ไปยังเซิร์ฟเวอร์ยืนยันโดยใช้วิธีใดก็ได้ (โดยปกติจะใช้คำขอ HTTPS POST)

เซิร์ฟเวอร์จะสร้างข้อความยืนยันและส่งทาง SMS ไปยังหมายเลขโทรศัพท์ที่คุณระบุ ดูทำการยืนยันทาง SMS ในเซิร์ฟเวอร์

4. รับข้อความยืนยัน

เมื่อได้รับข้อความยืนยันในอุปกรณ์ของผู้ใช้ บริการ Play จะ ออกอากาศSmsRetriever.SMS_RETRIEVED_ACTION Intent ไปยังแอปของคุณอย่างชัดเจน ซึ่งมีข้อความ ใช้ BroadcastReceiver เพื่อรับ ข้อความยืนยันนี้

ในตัวแฮนเดิลของ BroadcastReceiver onReceive ให้รับข้อความของ ข้อความยืนยัน (และอีเมลของผู้ส่งหากต้องการ) จากส่วนพิเศษของ Intent

/**
  * BroadcastReceiver to wait for SMS messages. This can be registered either
  * in the AndroidManifest or at runtime.  Should filter Intents on
  * SmsRetriever.SMS_RETRIEVED_ACTION.
  */
public class MySMSBroadcastReceiver extends BroadcastReceiver {

  @Override
  public void onReceive(Context context, Intent intent) {
    if (SmsRetriever.SMS_RETRIEVED_ACTION.equals(intent.getAction())) {
      Bundle extras = intent.getExtras();
      Status status = (Status) extras.get(SmsRetriever.EXTRA_STATUS);

      switch(status.getStatusCode()) {
        case CommonStatusCodes.SUCCESS:
          // (Optional) Get SMS Sender address - only available in
          // GMS version 24.20 onwards, else it will return null
          String senderAddress = extras.getString(SmsRetriever.EXTRA_SMS_ORIGINATING_ADDRESS);
          // Get SMS message contents
          String message = extras.getString(SmsRetriever.EXTRA_SMS_MESSAGE);
          // Extract one-time code from the message and complete verification
          // by sending the code back to your server.
          break;
        case CommonStatusCodes.TIMEOUT:
          // Waiting for SMS timed out (5 minutes)
          // Handle the error ...
          break;
      }
    }
  }
}

ลงทะเบียน BroadcastReceiver นี้ด้วยตัวกรอง Intent com.google.android.gms.auth.api.phone.SMS_RETRIEVED (ค่าของค่าคงที่ SmsRetriever.SMS_RETRIEVED_ACTION) และสิทธิ์ com.google.android.gms.auth.api.phone.permission.SEND (ค่าของค่าคงที่ SmsRetriever.SEND_PERMISSION) ในไฟล์ AndroidManifest.xml ของแอป ดังตัวอย่างต่อไปนี้ หรือแบบไดนามิกโดยใช้ Context.registerReceiver

<receiver android:name=".MySMSBroadcastReceiver" android:exported="true"
          android:permission="com.google.android.gms.auth.api.phone.permission.SEND">
    <intent-filter>
        <action android:name="com.google.android.gms.auth.api.phone.SMS_RETRIEVED"/>
    </intent-filter>
</receiver>

5. ส่งรหัสแบบใช้ครั้งเดียวจากข้อความยืนยันไปยังเซิร์ฟเวอร์

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

สุดท้าย ให้ส่งรหัสแบบใช้ครั้งเดียวไปยังเซิร์ฟเวอร์ผ่านการเชื่อมต่อที่ปลอดภัย เมื่อ เซิร์ฟเวอร์ได้รับรหัสแบบใช้ครั้งเดียว เซิร์ฟเวอร์จะบันทึกว่าหมายเลขโทรศัพท์ ได้รับการยืนยันแล้ว