Ionic 4 read SMS plugin for OTP Verification - ionic-framework

I am developing the ionic4 app, to auto verification or whenever I will get SMS my app has to read that message. for this I used 'Cordova plugin add Cordova-plugin-SMS' but it is not working. i declared 'declare var window: any; and declare var SMS: any;' nothing has worked. it showing "java.lang.ClassNotFoundException: com.rjfun.cordova.sms.SMSPlugin" in Android, in the web while developing it showing " TypeError: Cannot read property 'listSMS' of undefined". can any one help me to solve this issue

There is one plugin which could solve your problem. Named cordova-plugin-sms-receive.
This will help to read sms when any phone received and you can do whatever you want.
https://www.npmjs.com/package/cordova-plugin-sms-receive

That plugin enables sending an SMS from the app, not receiving an SMS.
To get data from an SMS to your app, you could pass it as args using deeplinks. This would required the user to tap a link in the SMS. I am not aware of a way to have SMS data fed to your app automatically, and I would think it is not possible as it would be a security risk.
A custom URL scheme is the simplest way to do that (e.g. mycoolapp://some-path?p1=data1&p2=data2.
App Links (Android > 6.0) and Universal Links (iOS > 9.0) are more powerful but may be unnecessary and are not as well supported. It really depends on your use case.
Ionic has a community maintained plugin for this which I use and does the job, albeit with a workaround needed here and there. Branch.io's plugin is also an option but I haven't used it.

very nice question ... you need to use cordova plugin for that. Below are the
First you need to install Android Permission Ionic Native Plugin.
run these two commands first to install Android Permission Plugin.
ionic cordova plugin add cordova-plugin-android-permissions
npm install #ionic-native/android-permissions
Add android-permissions to your app's Module.
import { AndroidPermissions} from '#ionic-native/android-permissions';
#NgModule({
providers: [
AndroidPermissions
]
})
export class AppModule { }
Check permissions on page
import { AndroidPermissions } from '#ionic-native/android-permissions';
export class HomePage {
constructor(public androidPermissions: AndroidPermissions) { }
ionViewWillEnter()
{
this.androidPermissions.checkPermission(this.androidPermissions.PERMISSION.READ_SMS).then(
success => console.log('Permission granted'),
err => this.androidPermissions.requestPermission(this.androidPermissions.PERMISSION.READ_SMS)
);
this.androidPermissions.requestPermissions([this.androidPermissions.PERMISSION.READ_SMS]);
}
}
After allowing Read SMS permission now you need to install cordova-plugin-sms. Run this command for install it.
ionic cordova plugin add cordova-sms-plugin
npm install #ionic-native/sms
and in your page while reading SMS -
place this in top before declare class
declare var SMS:any;
place below inside class
ionViewDidEnter()
{
this.platform.ready().then((readySource) => {
if(SMS) SMS.startWatch(()=>{
console.log('watching started');
}, Error=>{
console.log('failed to start watching');
});
document.addEventListener('onSMSArrive', (e:any)=>{
var sms = e.data;
console.log(sms);
});
});
}

You can use this Ionic/Cordova plugin for Auto OTP verification and this will not ask the user for SMS read Permissions.
Plugin: https://github.com/hanatharesh2712/ionic-native-sms-retriever-plugin-master
Demo App: https://github.com/hanatharesh2712/sms-plugin-test

Related

Ionic 3 Notification

I want to use notification with my app. I have checked ionic native and find some information.
First;
Local Notification
Second;
Push
What do I want to do? I am using MySQL Database and I have two tables users and points. When I add points for one user, I want to send notification for only this user. How can I do this? Which can I use service?
As per your required I suggest you to use Push Notifications using FCM.
push notifications help to send notification into two or more ionic apps.
please follow these steps.
go to 'http://console.firebase.google.com' and create an android app make sure that app package name also mention in config.xml file.
Install the Cordova and Ionic Native plugins in App:
ionic cordova plugin add cordova-plugin-fcm
npm install --save #ionic-native/fcm
use this code in your 'app.component.ts' file with in initializeApp
/getToken generates a device token that helps you to send notification on this device.you have to store this token in your database when app is open./
fcm.getToken().then(token=>{
console.log(token);
});
fcm.onNotification().subscribe(data=>{
if(data.wasTapped){
console.log("Received in background");
} else {
console.log("Received in foreground");
};
});
fcm.onTokenRefresh().subscribe(token=>{
console.log(token);
});
Now the real process that you have to follow for send notification
/here is you have to add device token that is you have store in your database and your firebase api key./
let body = {
"notification":{
"title":"New Notification has arrived",
"body":"Notification Body",
"sound":"default",
"click_action":"FCM_PLUGIN_ACTIVITY",
"icon":"fcm_push_icon"
},
"data":{
"param1":"value1",
"param2":"value2"
},
"to":"Device token/ID",
"priority":"high",
"restricted_package_name":""
}
let options = new HttpHeaders().set('Content-Type','application/json');
this.http.post("https://fcm.googleapis.com/fcm/send",body,{
headers: options.set('Authorization', 'key=YourAuthToken'),
}).subscribe();
hope this is helpful for you.
Thank You.
Push notification works the same way as local notification with a minor difference. Push notifications require connectivity and a server infrastructure of some kind to send the notification. With local notification you can trigger the notification with conditions. You will get the notification even if the app is closed and you’re offline. And having both notifications won’t cause implications.
In your case, you should go with Push Notification.If in future if you want to change the parameter to send notification it will be easy for you to maintain.No need to update the app
You can use FCM- Firebase Cloud Messaging on server side and in client side you can use PhoneGap push plugins to generate device token
here are the plugins
<plugin name="phonegap-plugin-push" source="npm" spec="1.8.4">
<variable name="SENDER_ID" value="XXXXXXX" />
</plugin>

Issue with register device in MFP8.0

We are developing ionic app with mfp8.0. We have tried to register our device for push notification by using the following code,
function isPushSupported() {
MFPPush.isPushSupported(
function(successResponse) {
alert("Push Supported: " + successResponse);
registerDevice();
}, function(failureResponse) {
alert("Failed to get push support status");
}
);
}
function registerDevice() {
WLAuthorizationManager.obtainAccessToken("push.mobileclient").then(
MFPPush.registerDevice(
null,
function(successResponse) {
alert("Successfully registered");
},
function(failureResponse) {
alert("Failed to register device:" + JSON.stringify(failureResponse));
}
)
);
}
Not able to register the device now. While getting inside the registerDevice() function App is getting stopped.
Actually, We are getting this error recently. Before that the same code was working fine for us.
I have referred the documentation. But, I am not getting the solution.Link which I have reffered is,
https://github.com/MobileFirst-Platform-Developer-Center/PushNotificationsCordova/blob/release80/www/js/index.js
https://mobilefirstplatform.ibmcloud.com/tutorials/en/foundation/8.0/notifications/handling-push-notifications/
Note:
GCM recommeded to make use of FCM now, refer the following link,
https://developers.google.com/cloud-messaging/
Actually, after register my device with FCM credentails only I am facing the issue.
Anyone help will be Appreciated!!!
Please make sure you are following the correct instructions. The instructions are layed out in the following page: https://mobilefirstplatform.ibmcloud.com/tutorials/en/foundation/8.0/notifications/sending-notifications/
Visit the Firebase Console.
Create a new project and provide a project name.
Click on the Settings "cog wheel" icon and select Project settings.
Click the Cloud Messaging tab to generate a Server API Key and a Sender ID. and click Save.

Send user to page on mobile app when clicking email link

I have just started an Ionic 2 mobile app.
I am setting up an update password process where a user can enter their email, click a "send password update email" button which then emails them a link. They can click that link which takes them to a page where they can update their password.
How do I send them a link in their email that when clicked on will open up the app and take them to a specific page?
Even more complicated is that I have a web app also. So if I'm sending them an email, should I show update password on website and update password on mobile app links? Or should I just add a link to the website?
In order to open the mobile app from a link, you need to integrate a cordova plugin called cordova-plugin-customurlscheme. With this plugin you can register a custom url "protocol" that is unique to your app (eg. myAwesomeApp://register?token=123). After installing the plugin with your custom url, clicking on any link starting with myAwesomeApp:// will open your app and also trigger a function hooked on the window object called handleOpenUrl which accepts the url as param. Inside there you can do your routing, depending on the url param.
let self = this;
(<any>window).handleOpenURL = function handleOpenURL(url) {
setTimeout(() => {
if (url && url.indexOf('\register') !== -1) {
let token = URLHelper.getParameterByName(url, 'token');
self.setAsRoot(ConfirmEmailPage, { activationToken: token });
}
}, 0);
};
As for dealing with your web app, what you could do is the following (this is what I am currently doing):
Host online a page (say www.myAwesomeWebsite.com/register?token=123) that checks to see if the user is coming from a mobile device (iOS or Android more specifically). If so on page load redirect them to your myAwesomeApp://register?token=123 link and have a button saying install app from app store with a link to your mobile app. If the user has the app, the app will be opened by the redirect, if they don't they will get an alert saying link cannot be found or sth and after clicking ok they will see the install App from app store button. If the user is not coming from a mobile device, just redirect them to your web app myAwesomeWebApp.com/register?token=123.
Another option is to use a third party service for deep linking like branch
Hope that helps.
EDIT: Since I posted this answer Ionic team has come with their own plugin for deep linking that kind of simplifies some of the hooking up inside your app. Their detailed blog post can be found here. In essence you install their plugin:
cordova plugin add ionic-plugin-deeplinks --variable URL_SCHEME=ionichats --variable DEEPLINK_SCHEME=https --variable DEEPLINK_HOST=ionic-hats.com
and then hook to it like so:
import {Component, ViewChild} from '#angular/core';
import {Platform, Nav, ionicBootstrap} from 'ionic-angular';
import {Deeplinks} from 'ionic-native';
import {AboutPage} from './pages/about/about';
import {HatDetailPage} from './pages/hat/hat';
#Component({
template: '<ion-nav [root]="rootPage"></ion-nav>',
})
class MyApp {
#ViewChild(Nav) nav:Nav;
constructor(private _platform: Platform) {}
ngAfterViewInit() {
this._platform.ready().then(() => {
Deeplinks.routeWithNavController(this.nav, {
'/about-us': AboutPage,
'/hats/:hatId': HatDetailPage
});
});
}
});
ionicBootstrap(MyApp);
Note that although this improves the plugin interfacing a bit, it does not change the fact that you have to use some other mechanism to handle deep links in conjunction with your web app.

Getting error unsupported_response_type

I am working on login with google functionality with $cordovaOauth.google plugin. But I am getting unsupported_response_type error.
$cordovaOauth.google("MY_APP_ID", ["https://www.googleapis.com/auth/urlshortener", "https://www.googleapis.com/auth/userinfo.email"]).then(function (result) {
console.log(JSON.stringify(result));
alert(JSON.stringify(result));
$scope.gdata = result;
}, function (error) {
console.log(error);
});
Where I am making mistake !?
Yes because $cordovaOauth plugin loading webview so you must need web clientID from Google API. And that will not work for ionic ( Mobile app ) so you need to do following things.
First
You need to use schema for your app to give internal URL like google:// or twitter://
Reference : http://mcgivery.com/using-custom-url-schemes-ionic-framework-app/
and provide that custom URL in Google redirect url ( This is not working all time as Google not accept custom URL but you can give it a try ).
Second and Working solution :
You need to create Google app with your app identifier and keytool.
For Android :
https://developers.google.com/identity/sign-in/android/start follow step second and provide your app name and unique identifier ( i.e dipesh.cool.com )
For iOS : 
https://developers.google.com/mobile/add?platform=ios&cntapi=signin
same information as mentioned for android.
Then you need to get REVERSED_CLIENT_ID value from the config file which download will be available once you are done with above two steps ( you can grab it from iOS config file it is easy to find from that file ).
And then simply run below command and code and you will have all working.
Command :
cordova plugin add cordova-plugin-googleplus --variable REVERSED_CLIENT_ID=GRAB_THIS_FROM_IOS_OR_ANDROID_CONFIG_FILE
Angular code :
$scope.GoogleLogin = function()
{
$scope.loaderShow('Google');
window.plugins.googleplus.login({},function (obj)
{
window.localStorage.setItem('signin', 'Google');
window.localStorage.setItem('g_uid', obj.userId);
window.localStorage.setItem('g_fname', obj.givenName);
window.localStorage.setItem('g_lname', obj.familyName);
window.localStorage.setItem('user_full_name', obj.displayName);
window.localStorage.setItem('g_email', obj.email);
window.localStorage.setItem('gotPdetails', 'false');
$scope.loaderHide();
$state.go('app.dashboard');
},
function (msg)
{
$scope.showAlert('Google signin Error<br/>'+msg);
$scope.loaderHide();
});
}

Implement Push notification in Android Phonegap app

Created UI using Angular and Ionic, and wrapper usign Phonegap, How can I have pushnotification in Android implemented.
Is there any effective and accurate library in Phonegap for Pushnotification Implemented.
Already using https://github.com/phonegap-build/PushPlugin, but getting some issues, like push notififcation not received, some time all notification coming at once.
First create a project in Google console
Enable GCM
Create a server api Key
use the following plugin
cordova plugin add phonegap-plugin-push --variable SENDER_ID="XXXXXXX"
replace the xxxxxx with your sender id
n your javascript add the following code for registering to GCM server it will give you a GCM id
var push = PushNotification.init({
android: {
senderID: "XXXXXXXX" //add your sender id here
},
ios: {
alert: "true",
badge: "true",
sound: "true"
},
windows: {}
});
push.on('registration', function(data) {
consol.log(data.registrationId); //this function give registration id from the GCM server if you dont want to see it please comment it
document.getElementById("gcm_id").value= data.registrationId; //showing registration id in our app. If it shows our registration process is suscess
//$("#gcm_id").val(data.registrationId); if you are using jquery
});
Send a message using GCM HTTP connection server protocol:
https://gcm-http.googleapis.com/gcm/send
Content-Type:application/json
Authorization:key=YOUR SERVER KEY
{
"to": "GCM ID",
"data": {
"message": "This is a GCM Topic Message!",
}
}
for more details..
http://phonegaptut.com/2016/05/31/how-to-send-push-notifications-in-phonegap-application/
I was having the same problem lately, using Ionic and Cordova (not Phonegap, but should work the same).
I ended up using this library for local push notifications https://github.com/Wizcorp/phonegap-plugin-localNotifications
They worked pretty well except the PN would not start the app on Android, but I opened a pull request with a fix for that.
If you encounter the same problem, you might also use my fork of this plugin which has this fix already included.
You should be using ngCordova's Push Plugin for this.
From the docs:
Allows your application to receive push notifications. To receive notifications in your controllers or services, listen for pushNotificationReceived event.
As Push Notification is a native feature, so to integrate Push in PhoneGap Android application you have to make a plugin that will communicate with Android Native code.
You can go through with Sample application available on Git Hub.
Please also follow the necessary steps require for it mentioned in ReadME file.