Phone Authentication firebase in Ionic with cordova-plugin-firebase

#1

I am trying to implement login in my ionic v3 application by the firebase phone authentication service.

I’ve read several tutorials. Between them:

1- https://javebratt.com/firebase-phone-authentication/

2- https://github.com/jestcastro/cordova-plugin-firebase#f778505942bbf7518df75545c6a6b32efa4d5229

The comments in link 1 teach how to use the cordova-plugin-firebase of link 2. I tried to do the documentation. I did everything exactly the same, as it is said in the links.

Yet, When I use the function ( window).FirebasePlugin.getVerificationID, from link 2, gives the error: ERROR TypeError: Can not read property ‘getVerificationID’ of undefined

I did exactly the same. And I’ve been trying to solve this problem for a few days. Does anyone have a solution?

#2

well I went further, but I’ve got:

error: unknown error verifying number

about your thing.

  1. did you install that plugin with:
ionic cordova plugin add https://github.com/jestcastro/cordova-plugin-firebase.git --save
  1. when app is running on device and you have google dev tools open, type in console (to see if it is there)
window

and check if there is FirebasePlugin and under that getVerificationID -> the getVerificationID should be a function

Did anyone used this firebase phone auth and succeeded ? Since Twitter Digits will soon retire and this should be ‘official’ support for phone verification…

#3

Hi sajtempler, you did it?

#4

not really, I mean I still get:

error: unknown error verifying number

for some reason. Tomorrow I’ll be checking that out with my friend who is fluent with Java, maybe we’ll figure something out.

#5

he did: https://market.ionic.io/starters/ionfirebaseaccountkitphoneauth

but is $15.00

#6

but is only android platform. :confused:

#7

okay I made it guys.

here’s what I’ve done.

I assume that you have just added platform android, and can build app.
Then install:

ionic cordova plugin add https://github.com/jestcastro/cordova-plugin-firebase.git

then configure your code as explained in docs. Here is my own code:

This can be done more clearly but it is just proof of concept

(registerPhone method is binded to template)

    private registerPhone(): void {
        let phone = '+48' + this.phoneNumber.value;

        console.log('LoginPage registerPhone() phone', phone);

        (<any>window).FirebasePlugin.getVerificationID(phone, id => {
            console.log("verificationID: " + id);
            this.verificationId = id;
            this.showPrompt();
        }, error => {
            console.log("error: " + error);
        });
    }

    private verifyCode(code): void {
        console.log(code);

        let credential = firebase.auth.PhoneAuthProvider.credential(this.verificationId, code);

        firebase.auth().signInWithCredential(credential).then((res) => {
            console.log('SCC', res);
            this.doLogin()
        })
    }

    private skip(): void {
        this.doLogin();
    }

    private showPrompt() {
        let prompt = this.alertCtrl.create({
            title: 'Verify',
            message: 'Type code that was received via SMS',
            inputs: [
                {
                    name: 'code',
                    placeholder: 'Code'
                },
            ],
            buttons: [
                {
                    text: 'Cancel',
                    handler: data => {
                        return;
                    }
                },
                {
                    text: 'Verify',
                    handler: data => {
                        this.verifyCode(data.code);
                    }
                }
            ]
        });
        prompt.present();
    }

    private doLogin() {
        this.event.publish('set_root', TabsPage);
    }

Then:
in platforms/android/cordova-plugin-firebase should be a file dev-build.gradle . Change its’s content to:

buildscript {
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath 'com.google.gms:google-services:3.1.0'
    }
}
repositories {
      dependencies {
          maven {
              url "https://maven.google.com" // Google's Maven repository
          }
    }
}
dependencies {
    compile 'me.leolin:ShortcutBadger:1.1.4@aar'
    compile 'com.google.firebase:firebase-crash:11.2.0'
    compile 'com.google.firebase:firebase-auth:11.2.0'
}

don’t forget to configure Firebase. And in Firebase Console add SHA-1 for auth. HERE is explained how to get one.

Hope this will help. Cheers

#8

didn’t work :x

[ERROR] An error occurred while running cordova build android (exit code 1):

    ANDROID_HOME=C:\android
    JAVA_HOME=C:\Program Files\Java\jdk1.8.0_121
    Subproject Path: CordovaLib
    Incremental java compilation is an incubating feature.
    :preBuild UP-TO-DATE
    :preDebugBuild UP-TO-DATE
    :checkDebugManifest
    :CordovaLib:preBuild UP-TO-DATE
    :CordovaLib:preDebugBuild UP-TO-DATE
    :CordovaLib:checkDebugManifest
    :CordovaLib:prepareDebugDependencies
    :CordovaLib:compileDebugAidl
    :CordovaLib:compileDebugNdk UP-TO-DATE
    :CordovaLib:compileLint
    :CordovaLib:copyDebugLint UP-TO-DATE
    :CordovaLib:mergeDebugShaders
    :CordovaLib:compileDebugShaders
    :CordovaLib:generateDebugAssets
    :CordovaLib:mergeDebugAssets
    :CordovaLib:mergeDebugProguardFiles UP-TO-DATE
    :CordovaLib:packageDebugRenderscript UP-TO-DATE
    :CordovaLib:compileDebugRenderscript
    :CordovaLib:generateDebugResValues
    :CordovaLib:generateDebugResources
    :CordovaLib:packageDebugResources
    :CordovaLib:processDebugManifest
    :CordovaLib:generateDebugBuildConfig
    :CordovaLib:processDebugResources
    :CordovaLib:generateDebugSources
    :CordovaLib:incrementalDebugJavaCompilationSafeguard
    :CordovaLib:compileDebugJavaWithJavac
    :CordovaLib:compileDebugJavaWithJavac - is not incremental (e.g. outputs have changed, no previous execution,
    etc.).
    Note: Some input files use or override a deprecated API.
    Note: Recompile with -Xlint:deprecation for details.
    :CordovaLib:processDebugJavaRes UP-TO-DATE
    :CordovaLib:transformResourcesWithMergeJavaResForDebug
    :CordovaLib:transformClassesAndResourcesWithSyncLibJarsForDebug
    :CordovaLib:mergeDebugJniLibFolders
    :CordovaLib:transformNative_libsWithMergeJniLibsForDebug
    :CordovaLib:transformNative_libsWithSyncJniLibsForDebug
    :CordovaLib:bundleDebug
    :prepareAndroidCordovaLibUnspecifiedDebugLibrary
    :preReleaseBuild UP-TO-DATE
    :CordovaLib:preReleaseBuild UP-TO-DATE
    :CordovaLib:checkReleaseManifest
    :CordovaLib:prepareReleaseDependencies
    :CordovaLib:compileReleaseAidl
    :CordovaLib:compileReleaseNdk UP-TO-DATE
    :CordovaLib:copyReleaseLint UP-TO-DATE
    :CordovaLib:mergeReleaseShaders
    :CordovaLib:compileReleaseShaders
    :CordovaLib:generateReleaseAssets
    :CordovaLib:mergeReleaseAssets
    :CordovaLib:mergeReleaseProguardFiles UP-TO-DATE
    :CordovaLib:packageReleaseRenderscript UP-TO-DATE
    :CordovaLib:compileReleaseRenderscript
    :CordovaLib:generateReleaseResValues
    :CordovaLib:generateReleaseResources
    :CordovaLib:packageReleaseResources
    :CordovaLib:processReleaseManifest
    :CordovaLib:generateReleaseBuildConfig
    :CordovaLib:processReleaseResources
    :CordovaLib:generateReleaseSources
    :CordovaLib:incrementalReleaseJavaCompilationSafeguard
    :CordovaLib:compileReleaseJavaWithJavac
    :CordovaLib:compileReleaseJavaWithJavac - is not incremental (e.g. outputs have changed, no previous execution,
    etc.).
    Note: Some input files use or override a deprecated API.
    Note: Recompile with -Xlint:deprecation for details.
    :CordovaLib:processReleaseJavaRes UP-TO-DATE
    :CordovaLib:transformResourcesWithMergeJavaResForRelease
    :CordovaLib:transformClassesAndResourcesWithSyncLibJarsForRelease
    :CordovaLib:mergeReleaseJniLibFolders
    :CordovaLib:transformNative_libsWithMergeJniLibsForRelease
    :CordovaLib:transformNative_libsWithSyncJniLibsForRelease
    :CordovaLib:bundleRelease
    :prepareComAndroidSupportSupportCompat2520Library FAILED

    FAILURE: Build failed with an exception.

    * What went wrong:
    Execution failed for task ':prepareComAndroidSupportSupportCompat2520Library'.
    > Could not expand ZIP
    'C:\android\extras\android\m2repository\com\android\support\support-compat\25.2.0\support-compat-25.2.0.aar'.

    * Try:
    Run with
    BUILD FAILED

    Total time: 17.745 secs
    --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.
    Error: cmd: Command failed with exit code 1 Error output:
    Note: Some input files use or override a deprecated API.
    Note: Recompile with -Xlint:deprecation for details.
    Note: Some input files use or override a deprecated API.
    Note: Recompile with -Xlint:deprecation for details.

    FAILURE: Build failed with an exception.

    * What went wrong:
    Execution failed for task ':prepareComAndroidSupportSupportCompat2520Library'.
    > Could not expand ZIP
    'C:\android\extras\android\m2repository\com\android\support\support-compat\25.2.0\support-compat-25.2.0.aar'.

    * Try:
    Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.
#9

try updating sdk tools
newest is :
26.0.2

and AndroidSupporRepository

#10

What did you do with or without recaptcha?
did you use any additional features? How to Facebook AccountKit?

#11

I went here

and took jestcastro (#325) pull request, then adjusted it as I described.
Cordova plugin doesn’t require reCaptcha, which was a pain for JS version. No additional features used.

#12

As Firebase just add a new update for supporting Firebase Auth service to Cordova project.

You should just use cordova plugin for Firebase Auth easier than before

Check this link of Firebase Authenticate Using OAuth Providers with Cordova

I add the Facebook and Google login followed the steps here, they worked fine.

#13

Hi Sajtempler,
Thank you for devoting your time to implement phone authentication, I fllowed all the steps and the code you put, but in my android phone I have this error invalid action.
this’s my code :
1- app.module.ts :
import { BrowserModule } from ‘@angular/platform-browser’;
import { ErrorHandler, NgModule } from ‘@angular/core’;
import { IonicApp, IonicErrorHandler, IonicModule } from ‘ionic-angular’;
import { SplashScreen } from ‘@ionic-native/splash-screen’;
import { StatusBar } from ‘@ionic-native/status-bar’;

import { MyApp } from ‘./app.component’;
import { HomePage } from ‘…/pages/home/home’;

import { Firebase } from ‘@ionic-native/firebase’;

@NgModule({
declarations: [
MyApp,
HomePage
],
imports: [
BrowserModule,
IonicModule.forRoot(MyApp)
],
bootstrap: [IonicApp],
entryComponents: [
MyApp,
HomePage
],
providers: [
StatusBar,
SplashScreen,
Firebase,
{provide: ErrorHandler, useClass: IonicErrorHandler}
]
})
export class AppModule {}

2-- home.ts (login)
import { Component } from ‘@angular/core’;
import { NavController, AlertController } from ‘ionic-angular’;

import { Firebase } from ‘@ionic-native/firebase’;
import firebase from ‘firebase’;

@Component({
selector: ‘page-home’,
templateUrl: ‘home.html’
})
export class HomePage {

constructor(public navCtrl: NavController, public alertCtrl: AlertController,
public firebase: Firebase) { }

public phoneNumber: number;
public verificationId: any;
public showerror : any = ‘ok’;

public registerPhone(): void {
let phone = ‘+213’ + this.phoneNumber;

console.log('LoginPage registerPhone() phone', phone);

(<any>window).FirebasePlugin.getVerificationID(phone, id => {
  console.log("verificationID: " + id);
  this.verificationId = id;
  this.showPrompt();
}, error => {
  this.showerror = error;
  console.log("error: " + error);
});

}

public verifyCode(code): void {
console.log(code);

let credential = firebase.auth.PhoneAuthProvider.credential(this.verificationId, code);

firebase.auth().signInWithCredential(credential).then((res) => {
  console.log('SCC', res);
  this.doLogin()
})

}

public showPrompt() {
let prompt = this.alertCtrl.create({
title: ‘Verify’,
message: ‘Type code that was received via SMS’,
inputs: [
{
name: ‘code’,
placeholder: ‘Code’
},
],
buttons: [
{
text: ‘Cancel’,
handler: data => {
return;
}
},
{
text: ‘Verify’,
handler: data => {
this.verifyCode(data.code);
}
}
]
});
prompt.present();
}

public doLogin() {
console.log(‘ok’);
}

}

Thanks in advance for the help.

#14

Hi,

make sure you have checked phone method in your firebase console, as follows:

#15

Yes the Phone option is enable, but i get error invalid action :

.

#16

Hi sajtempler,
This is my project, i removed plugins and dependencies, cause size of plugins and platform, please if you have time do npm install and install others needful, please can you provide your mail to send you my project to help me.

#17

i get the same invalid action,please help me.my email:beodan95@gmail.com

#18

I am also facing the same issue. Saying invalid action. Need a working sample code urgently :frowning:

#19

For anyone getting “Invalid action” at (< any >window).FirebasePlugin.getVerificationID("+…, I finally made it work in my app. (@serenity, @01687072421, @aka25, etc.)

Just replaced the method:
(< any >window).FirebasePlugin.getVerificationID("+123…", id => { …

for this:
(< any >window).FirebasePlugin.verifyPhoneNumber("+123…", 60, (credential) =>{
console.log("verificationID: " + credential.verificationId);
}, function(error) {
console.error(error);
});

1 Like
#20

My ionic app crash when the registerPhone() function runs.
What can i do for it ?