In the Part1 tutorial, you learned how to send SMS OTP to the custom mobile number which is entered by the user. In this tutorial, we are going to automatically receive OTP SMS and verify it.

This tutorial starts with otp-receive page. So go to the otp-receive folder

Step1:

Open the otp-receive.html file and create an input field to enter the OTP. And create a button with a click event to process the received OTP.

<ion-item>
<ion-label floating>Enter OTP</ion-label>
<ion-input type="number" [(ngModel)]="otp"></ion-input>
</ion-item>

<button ion-button (click)="verifyOTP()">Verify</button>

Step2:

To receive SMS programmatically, we need to write more code. That's not simple. But I will guide you, how to do that in a simple way. To receive SMS we need permission. So import Android permission to the otp-receive.ts file.

import { AndroidPermissions } from '@ionic-native/android-permissions';

Import HTTP, NavController, AlertController classes to otp-receive.ts file.

import { IonicPage,NavController,Platform,AlertController,NavParams } from 'ionic-angular';
import {Http, Headers } from '@angular/http';
import 'rxjs/add/operator/map';

Create a variable for SMS and document

declare var SMS:any;
declare var document:any;

SMS is used to hold the Cordova SMS object reference. And the document is used to add the onSMSArrive event listener.

Step3:

Create variable to store the mobile number and otp.

otp='';
mobile='';

Step4:

Create reference variable using the constructor.

constructor(public alertCtrl: AlertController,
public platform:Platform,
public androidPermissions: AndroidPermissions,
public http:Http,
public navCtrl:NavController,
public navParams: NavParams)
{
}

Get mobile number from home page.

this.mobile=this.navParams.get('mobile');

Step5:

Create a function to check whether you have permission to read SMS using the Android permission class. If you don't have permission, then request SMS read permission. 

checkPermission()
{
this.androidPermissions.PERMISSION.READ_SMS).then(
success => {
    
//if permission granted
this.receiveSMS();
},
err =>{
   
this.androidPermissions.PERMISSION.READ_SMS).
then(success=>{
this.receiveSMS();
},
err=>{
console.log("cancelled")
});
});
  
this.androidPermissions.PERMISSION.READ_SMS]);
  
}

If you have permission or permission granted by request, then call the startWatch function using the receiveSMS(), which will monitor the incoming message.

receiveSMS()
{
      
if(SMS) SMS.startWatch(function(){
console.log('watching started');
}, function(){
console.log('failed to start watching');
});
}

Step6:

Add the SMS monitor event to the constructor.

document.addEventListener('onSMSArrive', function(e){
var sms = e.data;
  
console.log("received sms "+JSON.stringify( sms ) );
  
if(sms.address=='HP-611773') //look for your message address
{
this.otp=sms.body.substr(0,4);
this.stopSMS();
this.verify_otp();
}   
});

The above code will look for incoming messages. If a message is received, then it will look for message sender. If message sender address is matched with your sender id, then it will take the otp from the message body. Then it will call the stop SMS monitoring function and will call the otp verification function.

Step7:

SMS stop and otp verification function code.

stopSMS()
{
if(SMS) SMS.stopWatch(function(){
console.log('watching stopped');
}, function(){
console.log('failed to stop watching');
});
}



verifyOTP()
{
console.log("verify otp");
if(this.mobile.length==0)
{
let alert = this.alertCtrl.create({
title: 'OTP Required!',
subTitle: 'Please enter your OTP and proceed',
buttons: ['OK']
});
alert.present();
}
else
{
this.http.get('http://192.168.0.100/nexmosms/verify_otp.php?mobile'+this.mobile+'&otp='+this.otp)
.map(res => res.json())
.subscribe(res => {
        
console.log(JSON.stringify(res));
//write your logic once otp validation is done
        
}, (err) => {
console.log("failed");
});
}
}

Step8:

Add the Android platform and run using the below command.

ionic cordova platform add android
ionic cordova run android

That's all. You are done.


APK Tested Device:

Moto G4 Plus

Please note. I have note stored my OTP in any database. And I have not caught to OTP on my server side to verify it. I leaving this part to you. You can implement this functionality in your own way. 

Nexmo PHP Reference

https://github.com/Nexmo/nexmo-php


For other programming languages.

https://developer.nexmo.com/tools

To know more about the messaging

https://developer.nexmo.com/api/sms

The above link contains many sample code for different languages. This will be very helpful to learn more about the messaging using the Nexmo.

Summary:

In this tutorial, you learned how to send OTP SMS to the custom mobile number and automate the received SMS OTP verification using the Nexmo PHP API and Ionic Framework.

Get full source code using.

https://github.com/bharathirajatut/ionic3/tree/master/SMSOTPVerificationAutomate

Ionic App versions are very important when developing applications. Why because Ionic is changing rapidly. So all the code you browse/see on the blog won't work if it is not the suitable Ionic version. So check the version before using the Ionic code. Below is the Ionic 3 information while testing the app code.

cli packages: (/usr/local/lib/node_modules)

    @ionic/cli-utils  : 1.19.0
    ionic (Ionic CLI) : 3.19.0

global packages:

    cordova (Cordova CLI) : 7.1.0

local packages:

    @ionic/app-scripts : 3.1.6
    Cordova Platforms  : android 6.3.0
    Ionic Framework    : ionic-angular 3.9.2

System:

    ios-sim : 5.0.13
    Node    : v6.10.0
    npm     : 5.6.0
    OS      : macOS High Sierra
    Xcode   : Xcode 9.1 Build version 9B55