電話番号を自動的に検証するには、確認フローのクライアント部分とサーバー部分の両方を実装する必要があります。このドキュメントでは、Android アプリにクライアント部分を実装する方法について説明します。
Android アプリで電話番号確認フローを開始するには、確認サーバーに電話番号を送信し、SMS Retriever API を呼び出して、アプリのワンタイム コードを含む SMS メッセージをリッスンします。メッセージを受信したら、ワンタイム コードをサーバーに送信して確認プロセスを完了します。
始める前に
アプリを準備するには、以下のセクションに示す手順を完了します。
アプリの前提条件
アプリのビルドファイルで次の値が使用されていることを確認します。
- minSdkVersion が 19 以降
- 28 以上の compileSdkVersion
アプリを構成する
プロジェクト レベルの build.gradle ファイルの buildscript
セクションと allprojects
セクションの両方に、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:20.5.0'
implementation 'com.google.android.gms:play-services-auth-api-phone:18.0.1'
}
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
を呼び出して、成功リスナーと失敗リスナーを 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
インテントをアプリに明示的にブロードキャストします。この確認メッセージを受信するには、BroadcastReceiver
を使用します。
BroadcastReceiver
の onReceive
ハンドラで、インテント エクストラから検証メッセージのテキストを取得します。
/**
* 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:
// Get SMS message contents
String message = (String) extras.get(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;
}
}
}
}
下記の例のように、または次のように Context.registerReceiver
を使用して、この AndroidManifest.xml
をアプリの AndroidManifest.xml
ファイルでインテント フィルタ 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
定数の値)に登録します。BroadcastReceiver
<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. 確認メッセージからサーバーにワンタイム コードを送信する
確認メッセージのテキストが作成されたので、正規表現などのロジックを使用して、メッセージからワンタイム コードを取得します。ワンタイム コードの形式は、サーバーにそれをどのように実装したかによって異なります。
最後に、安全な接続を介してサーバーにワンタイム コードを送信します。サーバーが 1 回限りのコードを受け取ると、電話番号の確認が完了したと記録します。
省略可: Smart Lock for Passwords で電話番号を保存する
必要に応じて、ユーザーが電話番号を確認した後、Smart Lock for Passwords を使用してこの電話番号アカウントを保存するようにユーザーに促すことができます。これにより、電話番号を再入力または選択しなくても、他のアプリや他のデバイスで自動的に使用できるようになります。
Credential credential = new Credential.Builder(phoneNumberString)
.setAccountType("https://signin.example.com") // a URL specific to the app
.setName(displayName) // optional: a display name if available
.build();
Auth.CredentialsApi.save(apiClient, credential).setResultCallback(
new ResultCallback() {
public void onResult(Result result) {
Status status = result.getStatus();
if (status.isSuccess()) {
Log.d(TAG, "SAVE: OK"); // already saved
} else if (status.hasResolution()) {
// Prompt the user to save
status.startResolutionForResult(this, RC_SAVE);
}
}
});
ユーザーがアプリを再インストールするか新しいデバイスにインストールした後、ユーザーに電話番号を再度要求することなく、保存された電話番号を取得できます。
// On the next install, retrieve the phone number
mCredentialRequest = new CredentialRequest.Builder()
.setAccountTypes("https://signin.example.com") // the URL specific to the developer
.build();
Auth.CredentialsApi.request(apiClient, mCredentialRequest).setResultCallback(
new ResultCallback<CredentialRequestResult>() {
public void onResult(CredentialRequestResult credentialRequestResult) {
if (credentialRequestResult.getStatus().isSuccess()) {
credentialRequestResult.getCredential().getId(); // this is the phone number
}
}
});
// Then, initiate verification and sign the user in (same as original verification logic)