How to Implement Automatic SMS verification While Developing an E-commerce App (Tutorial)

sms-verification-android

Are you an entrepreneur or startup who is looking to create your own Android mobile app with SMS verification feature, then this Android app development guide will help you to include SMS verification feature in your mobile app development project.

In this android app tutorial, we have shared step by step process to implement automatic SMS verification using SMS Retriever API in Android mobile app. Before that, let’s first understand what is SMS verification process?

What is SMS Verification process?

Earlier, when users had to login into e-commerce or finance or shopping-related app on the Android platform, they had to enter the mobile number to receive an OTP. Then they had to copy the verification code received through SMS, go back to the app and enter that code to log in successfully.

For overcoming this tedious process, Google introduced the message center functionality to automatically fetch a verification code sent via SMS within an app.

How to include automatic SMS verification feature in your E-Commerce app?

The purpose of creating this SMS verification demo is to allow an Android app to detect and verify a verification code sent on a user’s smartphone using SMS Retriever API. It is useful in fetching the verification code directly from the mobile phone.

After Google introduced an automatic SMS verification feature, they found some cases of mobile data access. Using the SMS verification feature, some Android apps were accessing users’ call logs as well as SMS logs in an unauthorized way. Due to this critical data security issue, Google has to abandon the feature for a while.

So, to provide the same functionality in a much secure way; recently Google has made some important changes in its policy, by restricting the access permissions. Now, the android users will choose which app they want to allow accessing their call logs or SMS logs. This way, the apps that are authorized to access logs can be able to send OTP on mobile phone & verify it automatically with SMS Retriever API. Thus, the user won’t require to manually copy & enter the code every time. So let’s follow these given steps to implement the code in an Android app.

Step: 1

Add the dependency in-app level Gradle file: 

implementation 'com.google.android.gms:play-services-auth:16.0.1'
implementation 'com.google.android.gms:play-services-auth-api-phone:16.0.0'


Step: 2

Add SMS receiver broadcast in AndroidMenifest.xml file

Register Broadcast for SMS Retrieval

<receiver
       android:name=".receiver.MySMSBroadcastReceiver"
       android:exported="true">
   <intent-filter>
       <action android:name="com.google.android.gms.auth.api.phone.SMS_RETRIEVE" />
   </intent-filter>
</receiver>


Step: 3

Start SMS Receiver activity to initiate the request for OTP

val client = SmsRetriever.getClient(this)
val task = client.startSmsRetriever()
task.addOnSuccessListener {
   tvOtp.text = "Waiting for the OTP"
   Toast.makeText(this, "SMS Retriever starts", Toast.LENGTH_LONG).show()
}

task.addOnFailureListener {
   tvOtp.text = "Cannot Start SMS Retriever"
   Toast.makeText(this, "Error", Toast.LENGTH_LONG).show()
}


Step: 4

Get SMS format & verification code in MySMSBroadcastReceiver

class MySMSBroadcastReceiver : BroadcastReceiver() {

   private var otpReceiveInterface: OTPReceiveInterface ? = null

   fun setOnOtpListeners(otpReceiveInterface: OTPReceiveInterface){
       this.otpReceiveInterface = otpReceiveInterface
   }

   override fun onReceive(context: Context?, intent: Intent?) {
       if (SmsRetriever.SMS_RETRIEVED_ACTION == intent?.action) {
           val extras = intent.extras
           val status = extras!!.get(SmsRetriever.EXTRA_STATUS) as Status

           when (status.statusCode) {
               CommonStatusCodes.SUCCESS -> {
                   var otp: String = extras.get(SmsRetriever.EXTRA_SMS_MESSAGE) as String

                   if (otpReceiveInterface != null) {

                       otp = otp.replace("<#> Your otp code is : ", "").split("\n".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()[0]
                       //otp = otp.replace("<#> Your otp code is: ", "")
                       //You can filter OTP here & send to activity                   }
               }

               CommonStatusCodes.TIMEOUT ->
                   if (otpReceiveInterface != null) {
                   //SMS retriving timeout, you can notify activity for same           }
       }

   }
}

Now

if you want to use hintRequestIntent to retrieve user’s contact number from the phone then:

Step: 1

setup googleApiClient

//set google api client for hint request
mGoogleApiClient = GoogleApiClient.Builder(this)
   .addConnectionCallbacks(this)
   .enableAutoManage(this, this)
   .addApi(Auth.CREDENTIALS_API)
   .build()


Step: 2

Request for numberHint by calling this method:

//get available number in user phone
private fun getHintPhoneNumber(){
   val hintRequest = HintRequest.Builder()
       .setPhoneNumberIdentifierSupported(true)
       .build()
   val intent = Auth.CredentialsApi.getHintPickerIntent(
       mGoogleApiClient, hintRequest
   )
   startIntentSenderForResult(intent.intentSender, RESOLVE_HINT, null, 0, 0, 0)
}


Step: 3

get the selected number in onActivityResult like:

override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
   super.onActivityResult(requestCode, resultCode, data)

   //Result if we want hint number
   if (requestCode == RESOLVE_HINT) {
       if (resultCode == Activity.RESULT_OK) {

           var credential: Credential = data!!.getParcelableExtra(Credential.EXTRA_KEY)
           // credential.getId();  <-- will need to process phone number string
       }
   }

}

How to test the demo:

NOTE: From Server, SMS format should follow:-
A) prefix: <#>
B) content: Your OTP code is: 45678
C) postfix: application key hash from your key store (Debug, Release)

For example:
<#> Your OTP code is: 45678

OutPut

 

Technology Used

Tool: Android Studio v3.3.1 with API 28 (Pie 9.0), SDK
Language: Kotlin, XML


Conclusion

With the new Play Store policy update, Google now lets Android app users choose which they want to allow accessing their SMS or call logs. The above SMS Retriever API example is useful for various B2C service providers who are directly dealing with their customers. Businesses from finance, e-commerce, and the fashion industry may find this feature more useful for their mobile apps.

With the help of this Android tutorial, we have learned how to integrate SMS Retriever API in Android app. You can get the source of this android app tutorial from Github.

As Google is rejecting those android apps from submitting on the Play Store, which isn’t complying to its current app policy. So, to avoid rejection of your own Android app on Google Play store, you must include the automatic SMS verification feature using SMS Retriever API Android. If you are looking to integrate automatic SMS verification process in your android app development project, feel free to contact our experienced android app developers.

This page was last edited on February 27th, 2019, at 8:17.
 
 

Have an App Idea?

Get your free consultation now

Leave a Reply

Your email address will not be published. Required fields are marked *