透過 Android 應用程式要求簡訊驗證

如要自動驗證電話號碼,您必須同時導入驗證流程的用戶端和伺服器端。本文說明如何在 Android 應用程式中實作用戶端部分。

如要在 Android 應用程式中啟動電話號碼驗證流程,請將電話號碼傳送至驗證伺服器,並呼叫 SMS Retriever API,開始監聽含有應用程式單次驗證碼的簡訊。收到訊息後,請將單次驗證碼傳回伺服器,完成驗證程序。

如要讓應用程式做好準備,請完成下列各節的步驟。

應用程式必要條件

請確認應用程式的版本檔案使用下列的值:

  • minSdkVersion 為 19 以上
  • compileSdkVersion 為 28 以上

設定應用程式

在專案層級 build.gradle 檔案中,請同時在 buildscript 和 allprojects 區段中納入 Google Maven 存放區和 Maven 中央存放區:

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

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

將 SMS Retriever API 的 Google Play 服務依附元件新增至模組的 Gradle 建構檔案,通常為 app/build.gradle:

dependencies {
  implementation 'com.google.android.gms:play-services-auth:22.0.0'
  implementation 'com.google.android.gms:play-services-auth-api-phone:18.3.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
      }
  }
}

啟動簡訊擷取器

準備好驗證使用者的電話號碼時,請取得 SmsRetrieverClient 物件的例項、呼叫 startSmsRetriever,並將成功和失敗事件監聽器附加至簡訊擷取工作:

// 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 using 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
    // ...
  }
});

簡訊擷取工作會監聽最多五分鐘,尋找含有應用程式專屬識別字串的簡訊。

將電話號碼傳送至伺服器

取得使用者的電話號碼並開始監聽簡訊後,請使用任何方法 (通常是 HTTPS POST 要求) 將使用者的電話號碼傳送至驗證伺服器。

伺服器會產生驗證訊息,並透過簡訊傳送至您指定的電話號碼。請參閱「在伺服器上執行簡訊驗證」。

接收驗證訊息

當使用者的裝置收到驗證訊息時,Play 服務會明確向應用程式廣播 SmsRetriever.SMS_RETRIEVED_ACTION 意圖,其中包含訊息文字。請使用BroadcastReceiver接收這則驗證訊息。

在 BroadcastReceiver 的 onReceive 處理常式中,從意圖的額外項目取得驗證訊息的文字 (以及寄件者地址,選用):

/**
  *   BroadcastReceiver to wait for SMS messages. This can be registered either
  *   in the AndroidManifest or at runtime. Filters 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,請使用下列指令:

  • 意圖篩選器: 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>

將驗證訊息中的單次驗證碼傳送至伺服器

取得驗證訊息的文字後,請使用規則運算式或其他邏輯,從訊息中取得動態密碼。一次性代碼的格式取決於您在伺服器中的導入方式。

最後,透過安全連線將一次性驗證碼傳送至伺服器。伺服器收到一次性驗證碼後,會記錄電話號碼已通過驗證。