Skip to content

Instantly share code, notes, and snippets.

@kkrishnan90
Last active September 8, 2021 13:24
Show Gist options
  • Select an option

  • Save kkrishnan90/f9b61c52850571fa3700fc043b06f53c to your computer and use it in GitHub Desktop.

Select an option

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.

@danbeo95

danbeo95 commented Nov 17, 2017

Copy link
Copy Markdown

here my login function:

 logIn(){
  	```
(<any>window).FirebasePlugin.verifyPhoneNumber("+841687072421",60, function(credential) {
    console.log(credential);
// ask user to input verificationCode:

}, function(error) {
console.error(error);
});
}
}

it log error "unknown error verifying number"
help me fix it!

@tahniat-ashraf

Copy link
Copy Markdown

Im facing window.FirebasePlugin.verifyPhoneNumber is not a function error even after following the guideline.
My Code :

 send() {

    (<any>window).FirebasePlugin.verifyPhoneNumber(
          "1234",
          60,
          (credential) => {
            console.log("SMS sent successfully !");
            console.log(credential);
            this.verificationId = credential.verificationId;
          },
          error => {
            console.error(error);
          })
    
  }

Can anyone help me fix it?

@w4r10

w4r10 commented Jan 10, 2018

Copy link
Copy Markdown

to all who face window.FirebasePlugin.verifyPhoneNumber is not a function you need to install the cordova-plugin-firebase using ionic cordova plugin add https://github.com/jestcastro/cordova-plugin-firebase.git --save , if you installed it using ionic cordova plugin add cordova-plugin-firebase you will get the error above .
after that of course you need sign your app using apksigner sign --ks key.jks app.apk with the same SHA1 Hash you written in your firebase console otherwise you end up blocked and getting the following error ERROR_APP_NOT_AUTHORIZED.

@AITSRD

AITSRD commented Feb 8, 2018

Copy link
Copy Markdown

hi w4r10,

I install the cordova-plugin-firebase using ionic cordova plugin add https://github.com/jestcastro/cordova-plugin-firebase.git --save in my ionic 3 project & It is working now well in debug mode but after releasing the app a warning appear.

WARNING: META-INF/gradle-plugins/com.google.gms.google-services.properties not protected by si gnature. Unauthorized modifications to this JAR entry will not be detected. Delete or move the entry outside of META-INF/.

do you have any fixation to fix this?

@AITSRD

AITSRD commented Feb 8, 2018

Copy link
Copy Markdown

after this phone Auth doesn't work..

@prantikv

Copy link
Copy Markdown

This works in the browser but not on device.

@sunilkunapareddy

Copy link
Copy Markdown

what is the code for api provider ?

i generated SHA 1 from keytool command.. and copied it with firebase and don't know how to write the api provider code ?

please help me out

@Nitishreddy787

Copy link
Copy Markdown

what is the code for api provider ?
please upload api provider file also

@Vivek-abstract

Copy link
Copy Markdown

I am getting an error: Invalid Phone Number. I entered a phone number +91xxxxxxxxxx. Does anyone know how to solve it?

@Nitishreddy787

Copy link
Copy Markdown

help me i need api/provider code...
Thanks

@SamaludheenCignes

Copy link
Copy Markdown

This will work only for PWA?

@TKlarissa

Copy link
Copy Markdown

hi everyone..i have an issue when i enter the phone number and click on button..the app exit alone (unfortunately app has stopped is the message that appears) and in my console there is no error
...am testing on device

@TKlarissa

Copy link
Copy Markdown

please can some one help?

@TKlarissa

Copy link
Copy Markdown

@danbeo95 please i really need your help it is urgent ....i dont understand why when i enter the phone number the app will exit alone

@netse-ai

netse-ai commented May 9, 2018

Copy link
Copy Markdown

@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
Copy Markdown

Hello anyone can work on android ?

@vaishalivc

Copy link
Copy Markdown

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

@Mehulkb

Mehulkb commented Aug 7, 2018

Copy link
Copy Markdown

Hey can you send the apiProvider file?

@Khsed4

Khsed4 commented Jan 31, 2019

Copy link
Copy Markdown

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

@raunix

raunix commented Apr 4, 2020

Copy link
Copy Markdown

Where is the api file?

@itshazlan

Copy link
Copy Markdown

is your code working on Ionic version 4+ project ?

@raunix

raunix commented Apr 7, 2020

Copy link
Copy Markdown

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