Automatic SMS Verification with the SMS Retriever API
This sample code is in JAVA, As per Google's new policy with the SMS Retriever API, you can perform SMS-based user verification in your Android app automatically, without requiring the user to manually type verification codes, and without requiring any extra app permissions.
The SMS Retriever API is available only on Android devices with Play services version 10.2 and newer.
The standard SMS format is given blow.
<#> Your ExampleApp code is: 123ABC78
FA+9qCX9VSu
SMS alwayse starts with <#> sign and have a hash key FA+9qCX9VSu to identify your app it is generated with your app's package id. You just need to get this has key from app and share with your server. In next few steps you will see how to create hash keys.
// Add at app level gradle file
implementation 'androidx.appcompat:appcompat:1.1.0'
implementation 'com.google.android.gms:play-services-base:17.1.0'
implementation 'com.google.android.gms:play-services-identity:17.0.0'
implementation 'com.google.android.gms:play-services-auth:17.0.0'
implementation 'com.google.android.gms:play-services-auth-api-phone:17.1.0'
// Note: If you have migrated your code to AndroidX than add this for LocalBroadCastManager
implementation 'androidx.localbroadcastmanager:localbroadcastmanager:1.0.0'
// Add at project level gradle file
classpath 'com.google.gms:google-services:4.2.0'
AppSignatureHashHelper class is responsible to get Hash key associated with your app as per your packege id. This is only one time required to get your app's hash key it would always be same unless you are changing app's package id.
// Inside Main Activity
Log.d(TAG, "HashKey: " + appSignatureHashHelper.getAppSignatures().get(0));
// Inside log cat Apps Hash Key: qzwS5M4KQ5H
Declare this SMSReceiver in your app's manifest file in side application tag.
<receiver
android:name=".SMSReceiver"
android:exported="true">
<intent-filter>
<action android:name="com.google.android.gms.auth.api.phone.SMS_RETRIEVED" />
</intent-filter>
</receiver>
Create SMSReceiver class that will listen SMS and extract code and create OTPReceiveListener that will communicate with Activities/Fragments.
public interface OTPReceiveListener {
void onOTPReceived(String otp);
void onOTPTimeOut();
void onOTPReceivedError(String error);
}
}
Create SMSReceiver listener and Initiate SmsRetrieverClient.
private void startSMSListener() {
try {
smsReceiver = new SMSReceiver();
smsReceiver.setOTPListener(this);
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(SmsRetriever.SMS_RETRIEVED_ACTION);
this.registerReceiver(smsReceiver, intentFilter);
SmsRetrieverClient client = SmsRetriever.getClient(this);
Task<Void> task = client.startSmsRetriever();
task.addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void aVoid) {
// API successfully started
}
});
task.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
// Fail to start API
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
You will receive OTP in call back methods implemented in you Activity/Fragment.
@Override
public void onOTPReceived(String otp) {
}
@Override
public void onOTPTimeOut() {
}
@Override
public void onOTPReceivedError(String error) {
}
// 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
}
}
}
Clone or download the project open it with Android Studio compile and run it will work.