Skip to content

Instantly share code, notes, and snippets.

@kkrishnan90
Last active September 8, 2021 13:24
  • Star 11 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save kkrishnan90/f9b61c52850571fa3700fc043b06f53c to your computer and use it in GitHub Desktop.
Firebase Phone Auth using Ionic V3 - Sending and reading OTP

General Steps to be followed as a flow process to complete Firebase Phone OTP Auth in Ionic V3

Step 1 : Get the phone number through input from the user. Step 2 : Pass this phone number to the firebase and receive a callback with verification ID. Step 3 : Pass on this verification ID through navParams to the next page where the user will enter the OTP sent to the entered mobile number. Step 4 : Verify the OTP that is sent with firebase for success() or failure() .

STEP 1 & 2 & 3

phone-verification.html

<ion-content padding>
  <div class="img_container">
    <img src="assets/img/web_logo.png">
  </div>
  <div id="recaptcha-container"></div>
  
  <div class="img_container">
    <img src="assets/img/web_text.png">
  </div>
  <h2> Let's get to know you better </h2>
  <ion-item class="input_item">
    <ion-input type="number" placeholder="Mobile number (Ex: +91xxxxxxxxxx)" [(ngModel)]="phoneNumber" ></ion-input>
  </ion-item>
</ion-content>
<ion-footer no-shadow>
	<button ion-button color="app_color" block class="btn_login" (click)='signIn(phoneNumber)'>PROCEED</button>
</ion-footer>

phone-verification.ts

import { ApiProvider } from './../../providers/api/api';
import { Component } from '@angular/core';
import { IonicPage, NavParams, AlertController, NavController } from 'ionic-angular';
import firebase from 'firebase';
import {Firebase} from '@ionic-native/firebase';

@IonicPage()
@Component({
  selector: 'page-phone-verification',
  templateUrl: 'phone-verification.html',
})
export class PhoneVerificationPage {
  public recaptchaVerifier: firebase.auth.RecaptchaVerifier;
  verificationId: any = '';
  phoneNumber: any = '';
  countryCode: any = '';
  result: any;
  constructor(public navCtrl: NavController,private api: ApiProvider, public navParams: NavParams, private alertCtrl: AlertController,public firebase: Firebase) {
  }
  
  ionViewDidLoad() {
    this.recaptchaVerifier = new firebase.auth.RecaptchaVerifier('recaptcha-container'); 
    console.log('ionViewDidLoad PhoneVerificationPage');
  }

  OtpScreen() {
    this.countryCode = '+' + this.phoneNumber.substring(0, 2);
    this.phoneNumber = this.phoneNumber.substring(2, 13);
    console.log(this.countryCode, this.phoneNumber); 
  }


  signIn(phoneNumber: number) { //Step 2 - Pass the mobile number for verification
    this.api.presentLoader('Sending OTP to your mobile number');
    let number =this.phoneNumber;
    (<any>window).FirebasePlugin.verifyPhoneNumber(number, 60, (credential) =>{
    console.log(credential);
    this.api.dismissLoader();
    var verificationId = credential.verificationId;
    this.navCtrl.push('OtpPage',{verificationid: verificationId}); //This is STEP 3 - passing verification ID to OTP Page
    }, (error) =>{
      //this.eer = error;
      this.api.dismissLoader();
      this.api.presentToast('Failed to send OTP. Try again');
      console.error(error);
    });
  }
}

STEP 4

Otp.html

<ion-content padding>
  <div class="img_container">
    <img src="assets/img/web_logo.png">
  </div>
  <div class="typography_container">
    <img src="assets/img/web_text.png">
  </div>
  <h3>Type the OTP sent your mobile</h3>
  <div class="otp_container">
   
    <ion-item>
      <ion-input type="text" placeholder="Enter OTP sent to your mobile" [(ngModel)]="otp"></ion-input>
    </ion-item>
  </div>
</ion-content>

<ion-footer no-shadow>
    <button ion-button color="app_color" block class="btn_login" (click)='roleSelection()'>PROCEED</button>
</ion-footer>

Otp.ts

import { ApiProvider } from './../../providers/api/api';
import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
import firebase from 'firebase';
import { Firebase } from '@ionic-native/firebase';


@IonicPage()
@Component({
  selector: 'page-otp',
  templateUrl: 'otp.html',
})
export class OtpPage {
  verification_id: any;
  otp:string='';
  constructor(public navCtrl: NavController, private api: ApiProvider,public navParams: NavParams) {
    this.verification_id = this.navParams.get('verificationid');
  }

  ionViewDidLoad() {
    console.log('ionViewDidLoad OtpPage');
  }

  roleSelection() {
    this.api.presentLoader('Verifying your OTP');
    var signInCredential = firebase.auth.PhoneAuthProvider.credential(this.verification_id,this.otp);
    firebase.auth().signInWithCredential(signInCredential).then(()=>{    
      console.log(signInCredential);
      setTimeout(()=>{
        this.api.dismissLoader();
        this.api.presentToast('OTP Verified');
      },2000);
      this.navCtrl.setRoot('RoleSelectionPage');
    }).catch(()=>{
      this.api.dismissLoader();
      this.api.presentSimplesAlert('OTP Failed','Failed to verify OTP');
      console.log('Erorr in OTP');
    });
    
  }
}

Thats it ! Implement and let me know your feedbacks in the comment below. I would be happy to resolve your queries if any.

@netse-ai
Copy link

netse-ai commented May 9, 2018

@TKlarissa I have the same problem. App quits unexpectedly. Also, I believe that this does not work on a device period since Recaptcha is not supported.

@ags-21ct
Copy link

Hello anyone can work on android ?

@vaishalivc
Copy link

@kkrishnan90 Can you provide plugin which you used for (window).FirebasePlugin.verifyPhoneNumber) method..??

@Mehulkb
Copy link

Mehulkb commented Aug 7, 2018

Hey can you send the apiProvider file?

@Khsed4
Copy link

Khsed4 commented Jan 31, 2019

I wonder why they give this project 10 stars? The codes are incomplete. Where is apiProvider class? Without it the codes are useless.

@raunix
Copy link

raunix commented Apr 4, 2020

Where is the api file?

@itshazlan
Copy link

is your code working on Ionic version 4+ project ?

@raunix
Copy link

raunix commented Apr 7, 2020

No I am using Ionic 3.9.2 version

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment