在 Android 应用中请求短信验证

要自动验证电话号码,您必须同时实现客户端和 验证流程的服务器部分。本文档介绍了如何 在 Android 应用中实现客户端部分。

要在 Android 应用中启动电话号码验证流程,您需要发送 您的验证服务器发送到您的验证服务器,并调用 SMS Retriever API 以开始 监听包含您的应用一次性代码的短信。在您之后 收到消息后,您需要将一次性代码发送回您的服务器以完成操作 验证流程。

准备工作

为了让您的应用做好准备,请完成以下部分中的步骤。

应用要满足的前提条件

确保您应用的 build 文件使用以下值:

  • minSdkVersion 为 19 或更高版本
  • compileSdkVersion 28 或更高版本

配置您的应用

在项目级 build.gradle 文件中,添加 Google 的 Maven 制品库Maven 中央代码库buildscriptallprojects 部分:

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

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

添加 Google Play 服务依赖项 将 SMS Retriever API 添加到模块的 Gradle build 文件中, 通常为 app/build.gradle

dependencies {
  implementation 'com.google.android.gms:play-services-auth:21.2.0'
  implementation 'com.google.android.gms:play-services-auth-api-phone:18.1.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. 启动短信检索器

当您准备好验证用户的电话号码时,请获取 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 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
    // ...
  }
});

短信检索任务最长会监听 5 分钟的短信 ,其中包含用于标识您的应用的唯一字符串。

3. 将电话号码发送到您的服务器

在获得用户的电话号码并开始监听短信后 消息,请使用任何 方法(通常使用 HTTPS POST 请求)。

您的服务器生成一条验证消息,并将其通过短信发送给手机 。请参阅在服务器上执行短信验证

4. 接收验证邮件

在用户设备上收到验证消息后,Play 服务 向您的应用明确广播 SmsRetriever.SMS_RETRIEVED_ACTION intent, ,其中包含消息文本。使用BroadcastReceiver接收 此验证邮件。

BroadcastReceiveronReceive 处理程序中,获取 从 Intent 的 extra:

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

向 intent 过滤器注册此 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>

5. 将验证邮件中的一次性验证码发送到您的服务器

现在您已经获得了验证邮件的文本,请使用正则表达式 或其他某种逻辑,用于从消息中获取一次性代码。该 一次性代码取决于您在服务器中实现它们的方式。

最后,通过安全连接将一次性代码发送到您的服务器。时间 您的服务器收到该一次性代码后,它会记录该电话号码 已经过验证。