このページでは、SMS User Consent API を使用して、1 通の SMS 確認メッセージの読み取りに対するユーザーの同意をリクエストする方法について説明します。ユーザーが同意すると、API はメッセージのテキストを返します。このテキストから確認コードを取得して、確認プロセスを完了できます。
依存関係のインストール
アプリの build.gradle ファイルに Play 開発者サービス Auth コンポーネントを含めます。
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 for Passwords のヒント選択ツールを使用して、ユーザーが電話番号を入力できるようにすることをおすすめします。ヒント選択ツールを使用するには:
Kotlin
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
}
// ...
}
}
Java
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. 着信メッセージのリッスンを開始する
次に、SMS User Consent API の startSmsUserConsent()
メソッドを呼び出して、着信メッセージのリッスンを開始します。SMS メッセージの送信元となる電話番号がわかっている場合は、その番号を指定します(わからない場合は null を渡します)。これにより、SMS ユーザーの同意 API は、この番号からのメッセージに対してのみトリガーされます。
リッスンを開始するには:
Kotlin
// 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 */)
Java
// 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 分間、デバイスが 1 回限りのコードを含む SMS メッセージを受信すると、Play 開発者サービスは、メッセージの読み取り許可を求めるプロンプトを表示するインテントをアプリにブロードキャストします。メッセージがブロードキャストをトリガーするのは、次の条件を満たす場合のみです。
- メッセージに、少なくとも 1 つの数字を含む 4 ~ 10 文字の英数字文字列が含まれている。
- 送信者の電話番号を指定した場合、メッセージはその番号から送信されたものである。
これらのブロードキャストは、SEND_PERMISSION 権限を持ち、SMS_RETRIEVED_ACTION
インテントに応答するブロードキャスト レシーバで処理します。ブロードキャスト レシーバを作成して登録するには:
Kotlin
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)
}
Java
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 のアクティビティを開始すると、メッセージの内容を読み取るための 1 回だけのアクセス許可を求めるプロンプトがユーザーに表示されます。
3. メッセージから確認コードを取得する
onActivityResult() メソッドで、権限のリクエストに対するユーザーの応答を処理します。結果コードが RESULT_OK の場合、ユーザーはメッセージの内容を読み取る権限を付与しています。インテントからメッセージ テキストを取得できます。
Kotlin
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.
}
}
}
Java
@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;
}
}
メッセージ テキストを取得したら、確認コードを解析してフォームに自動入力するか、確認フローを完了します。