Verification SMS automatically with SMS Retriever API in Android

Posted By : Arun Kumar | 26-Aug-2019

When we implement automatic SMS verification in our app, the verification flow looks like this:

Automatically verify phone number then we should implement both clients as well as server portions of verification flow. SMS Retriever API is available on android devices with play services version 10.2 and so on.

Obtain the user's phone number :
 We can obtain the user's phone number in whatever way is appropriate for our app. Often, This is the better user experience to use the hint picker to prompt the user to choose from phone numbers stored on the device and avoid having to manually type a phone number,

//  a request for phone number 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 request_Code, int result_Code, Intent myData)

{
  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
      }
  }
}      
        

Start the SMS retriever : 
When you are ready to verify the user's phone number, get an instance of the SmsRetrieverClientobject, call start SmsRetriever, and attach success and failure listeners to the SMS retrieval task:

 SmsRetrieverClient client = SmsRetriever.getClient(this /* context */);

// Starts SmsRetriever, which waits for ONE matching SMS message until the timeout
// (5 minutes). The matching SMS message will be sent via a Broadcast Intent with
// action SmsRetriever#SMS_RETRIEVED_ACTION.
Task 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() {
  @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
    // ...
  }
});

 

Send the phone number to our server :
After you have obtained the user's phone number and started to listen for SMS messages, send the user's phone number to our verification server using any method (usually with an HTTPS POST request).

our server generates a verification message and sends it by SMS to the phone number you specified. 

When our server receives a request to verify a phone number, first construct the verification message that you will send to the user's device. This message must:

Be no longer than 140 bytes
Contain a one-time code that the client sends back to our server to complete the verification flow 
Include an 11-character hash string that identifies our app
Otherwise, the contents of the verification message can be whatever you choose. It is helpful to create a message from which you can easily extract the one-time code later on. For example, a valid verification message might look like the following:

<#> our ExampleApp code is: 123ABC78


FA+9qCX9VSu

Receive verification messages : 
When a verification message is received on the user's device, Play services explicitly broadcast to our app an SmsRetriever.SMS_RETRIEVED_ACTION Intent, which contains the text of the message. Use a BroadcastReceiver to receive this verification message.

In the BroadcastReceiver's onReceive handler, get the text of the verification message from the Intent's extras:

 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 our server.
          break;
        case CommonStatusCodes.TIMEOUT:
          // Waiting for SMS timed out (5 minutes)
          // Handle the error ...
          break;
      }
    }
  }
}         
        

          

        
Register this BroadcastReceiver with the intent filtercom.google.android.gms.auth.api.phone.SMS_RETRIEVED (the value of the SmsRetriever.SMS_RETRIEVED_ACTION constant) in our app's AndroidManifest.xml file, as in the following example, or dynamically using Context.registerReceiver

Send the one-time code from the verification message to our server :
Now that you have the text of the verification message, use a regular expression or some other logic to get the one-time code from the message. The format of the one-time code depends on how you implemented them in our server.

Finally, send the one-time code to our server over a secure connection. When our server receives the one-time code, it records that the phone number has been verified.

About Author

Author Image
Arun Kumar

He is very energetic, wonderful and enthusiastic, with amazing Brain!. He tries to achieve near perfection in his work, be it code quality or design of user interface. He is able to deliver his work before specified deadlines and norms.He is rising talent

Request for Proposal

Name is required

Comment is required

Sending message..