How to get back from InAppBrowser in Ionic 4 - ionic-framework

I am using Inappbrowser for payment gateway.
How to come back from InAppBrowser to our app after successfully done payment.

Here is my code.
browser.on('loadstart').subscribe((e) => {
let compareURL = "https://myurl.com/folder_name/filename.php?CODE=XXXXX";
console.log(e.url);
if(e.url === compareURL){
this.navCtrl.setRoot(ConfirmationPage, {
orderId: this.orderId
})
browser.close();
console.log('browser closed');
}
}, err => {
console.error(err);
});

Related

Use Observable and HttpClient in Ionic 3 app

What I want is to make GET http request in my provider, wrap http call in Observable.create and return Observable object, then in my component, resolve that Observable. I tried something, can someone tell me if it is ok (I can't test at the moment so don't know if it works)? If it's not ok, can someone guide me what is the best practice in Ionic 3, to do http call and handle response (success, failure)?
In provider:
public getUsers(credentials):Observable<any> {
if("some custom condition not satisfied")
return Observable.throw("ERROR);
return Observable.create(observer => {
this.http.get(API_URL + '/users').subscribe(
(response) => {
observer.next(response);
observer.complete();
},
(error)=> {
return Observable.throw(error);
});
});
}
then in component:
this.myProvider.login().subscribe(response => {
if (response.status == 403) {
this.loading.dismiss();
console.log("Access denied");
}
this.loading.dismiss();
this.nav.setRoot('MainPage');
},
error => {
this.loading.dismiss();
console.log(error);
});

Ionic - Facebook Native Ads Error 1001 (No fill)

My facebook native ads integration code is like below.
var that = this;
this.platform.ready().then(() => {
if(FacebookAds)
{
//FacebookAds.setOptions({
//isTesting: true,
//deviceHash: 'fe645f07-9801-41fe-a430-xxxxxxxxxxx'
//},(s)=>(console.log("settings are OK.")),(e)=>(console.log("Settings are not loaded...")));
FacebookAds.createNativeAd('xxxxxxxxx',
(eee) => {
document.addEventListener("onAdLoaded", (data) =>{
console.log(data);
let temp: any = data;
if(temp.adType == "native")
{
this.startFB = 1;
document.getElementById('adIcon').setAttribute("src", decodeURIComponent(temp.adRes.icon.url));
document.getElementById('adCover').setAttribute("src", decodeURIComponent(temp.adRes.coverImage.url));
document.getElementById('adTitle').innerHTML = temp.adRes.title;
document.getElementById('adBody').innerHTML = temp.adRes.body;
document.getElementById('adSocialContext').innerHTML = temp.adRes.socialContext;
document.getElementById('adBtn').innerHTML = temp.adRes.buttonText;
that.updateXY(0, 0);
}
});
document.addEventListener('onAdFailLoad', (data) => {
console.log(data);
//alert('error: ' + data);
});
},
(err) => console.log(err)
);
}
});
When I run this code without test mode, I get 1001 error code.
When I run this code with test mode, No error but load data comes empty.
Not: I test code in real device and I login as test user to Facebook app in this device.
Do you have any advice?

ionic push notification when app is in foreground

I am making a ionic 3 app. I want notifications to appear even when app is in foreground. I have tried using FCM Plugin I'm getting notifications only when app is in background.
Home.ts
import { AngularFireDatabase } from 'angularfire2/database';
import { Component } from '#angular/core';
import { NavController } from 'ionic-angular';
import firebase from 'firebase';
declare var FCMPlugin;
#Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
firestore = firebase.database().ref('/pushtokens');
firemsg = firebase.database().ref('/messages');
constructor(public navCtrl: NavController,public afd:AngularFireDatabase) {
this.tokensetup().then((token)=>{
this.storeToken(token);
})
}
ionViewDidLoad() {
FCMPlugin.onNotification(function (data) {
if (data.wasTapped) {
//Notification was received on device tray and tapped by the user.
alert(JSON.stringify(data));
} else {
//Notification was received in foreground. Maybe the user needs to be notified.
alert(JSON.stringify(data));
}
});
FCMPlugin.onTokenRefresh(function (token) {
alert(token);
});
}
tokensetup(){
var promise = new Promise((resolve,reject)=>{
FCMPlugin.getToken(function(token){
resolve(token);
},(err)=>{
reject(err);
});
})
return promise;
}
storeToken(token){
this.afd.list(this.firestore).push({
uid: firebase.auth().currentUser.uid,
devtoken: token
}).then(()=>{
alert('Token stored')
}).catch(()=>{
alert('Token not stored');
})
// this.afd.list(this.firemsg).push({
// sendername:'adirzoari',
// message: 'hello for checking'
// }).then(()=>{
// alert('Message stored');
// }).catch(()=>{
// alert('message not stored');
// })
}
}
the function cloud for notifications
var functions = require('firebase-functions');
var admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
var wrotedata;
exports.Pushtrigger = functions.database.ref('/messages/{messageId}').onWrite((event) => {
wrotedata = event.data.val();
admin.database().ref('/pushtokens').orderByChild('uid').once('value').then((alltokens) => {
var rawtokens = alltokens.val();
var tokens = [];
processtokens(rawtokens).then((processedtokens) => {
for (var token of processedtokens) {
tokens.push(token.devtoken);
}
var payload = {
"notification":{
"title":"From" + wrotedata.sendername,
"body":"Msg" + wrotedata.message,
"sound":"default",
},
"data":{
"sendername":wrotedata.sendername,
"message":wrotedata.message
}
}
return admin.messaging().sendToDevice(tokens, payload).then((response) => {
console.log('Pushed notifications');
}).catch((err) => {
console.log(err);
})
})
})
})
function processtokens(rawtokens) {
var promise = new Promise((resolve, reject) => {
var processedtokens = []
for (var token in rawtokens) {
processedtokens.push(rawtokens[token]);
}
resolve(processedtokens);
})
return promise;
}
it works only when the app in the background. but when i exit from the app and it's not in the background I don't get any notification.
You need to edit the FCM Plugin files. I found the solution only for android now.
I use https://github.com/fechanique/cordova-plugin-fcm this FCM plugin for android and ios in cordova.
You need to edit file MyFirebaseMessagingService.java line 53(line no be may be differ).
In this file there is a method onMessageReceived at the end of the method there is a line which is commented, this line calling an another method i.e. sendNotification(....).
sendNotification(remoteMessage.getNotification().getTitle(), remoteMessage.getNotification().getBody(), data);
You have to uncomment this line and change last parameter from remoteMessage.getData() to data (data variable is already there in the code).
And comment this line FCMPlugin.sendPushPayload( data );
Now you are good to go. Now you are able to receive notification even when app is opened (foreground), you will receive the banner (floating) notifications.
If you found anything for IOS please let me know!!!
I am using firebase plugin for ionic 3.
There is a check if notification data contain "notification_foreground" or not and save it in variable foregroundNotification.
if(data.containsKey("notification_foreground")){
foregroundNotification = true;
}
then it create showNotification variable which decide if we need to show notification or not and pass this to the sendMessage (show notification function).
if (!TextUtils.isEmpty(body) || !TextUtils.isEmpty(title) || (data != null && !data.isEmpty())) {
boolean showNotification = (FirebasePlugin.inBackground() || !FirebasePlugin.hasNotificationsCallback() || foregroundNotification) && (!TextUtils.isEmpty(body) || !TextUtils.isEmpty(title));
sendMessage(data, messageType, id, title, body, showNotification, sound, vibrate, light, color, icon, channelId, priority, visibility);
}
your payload should contain notification_foreground, notification_title and notification_body.

Vue.js 2 and auth0 authentication resulting with 'nonce'

I am trying to implement auth0 in my Vue.js 2 application.
I followed this link to implement the auth0 lock:
https://github.com/auth0-samples/auth0-vue-samples/tree/master/01-Login
This is my application in Login.vue:
HTML:
<div v-show="authenticated">
<button #click="logout()">Logout</button>
</div>
<div v-show="!authenticated">
<button #click="login()">Login</button>
</div>
Javascript:
function checkAuth() {
return !!localStorage.getItem('id_token');
}
export default {
name: 'login',
data() {
return {
localStorage,
authenticated: false,
secretThing: '',
lock: new Auth0Lock('clientId', 'domain')
}
},
events: {
'logout': function() {
this.logout();
}
},
mounted() {
console.log('mounted');
var self = this;
Vue.nextTick(function() {
self.authenticated = checkAuth();
self.lock.on('authenticated', (authResult) => {
console.log(authResult);
console.log('authenticated');
localStorage.setItem('id_token', authResult.idToken);
self.lock.getProfile(authResult.idToken, (error, profile) => {
if (error) {
console.log(error);
return;
} else {
console.log('no error');
}
localStorage.setItem('profile', JSON.stringify(profile));
self.authenticated = true;
});
});
self.lock.on('authorization_error', (error) => {
console.log(error);
});
});
},
methods: {
login() {
this.lock.show();
},
logout() {
localStorage.removeItem('id_token');
localStorage.removeItem('profile');
this.authenticated = false;
}
}
}
I am pretty sure that it already worked, but suddenly it doesnt work anymore.
My callbacks defined in auth0: http://127.0.0.1:8080/#/backend/login
That is also how I open the login in my browser.
When I login it I only get this in my localStorage:
Key: com.auth0.auth.14BK0_jsJtUZMxjiy~3HBYNg27H4Xyp
Value: {"nonce":"eKGLcD14uEduBS-3MUIQdupDrRWLkKuv"}
I also get redirected to http://127.0.0.1:8080/#/ so I do not see any network requests.
Does someone know where the problem is?
I ran the demo from auth0 with my Domain/Client and it worked without any problem.
Obviously I do not get any errors back in my console.
Atfer research I finally found the answer to my problem.
The reason, why it is not working is because my vue-router does not use the HTML5 History Mode (http://router.vuejs.org/en/essentials/history-mode.html).
To have it working without the history mode, I had to disable the redirect in my lock options and to disable auto parsing the hash:
lock: new Auth0Lock(
'clientId',
'domain', {
auth: {
autoParseHash: false,
redirect: false
}
}
)
Reference: https://github.com/auth0/lock

$cordovaPushV5 onNotification not firing

I am trying to implement push notifications in Ionic V1 using $cordovaPushV5 but I am not able to get to work. I am able to get the device registration ID but when I test notifications using Firebase Cloud Messaging, it doesnt work. Below is app.js code -
// ionic Starter App
// angular.module is a global place for creating, registering and retrieving Angular modules
// 'starter' is the name of this angular module example (also set in a <body> attribute in index.html)
// the 2nd parameter is an array of 'requires'
// 'starter.controllers' is found in controllers.js
var app = angular.module('starter', ['ionic', 'ngCordova'])
.run(function ($ionicPlatform, $cordovaPushV5, $rootScope, $cordovaLocalNotification) {
$ionicPlatform.ready(function () {
// hide the accessory bar by default (remove this to show the accessory bar above the keyboard
// for form inputs)
if (cordova.platformId === 'ios' && window.cordova && window.cordova.plugins && window.cordova.plugins.Keyboard) {
cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
cordova.plugins.Keyboard.disableScroll(true);
}
if (window.StatusBar) {
// org.apache.cordova.statusbar required
window.StatusBar.styleLightContent();
}
console.log('app.js');
var options = {
android: {
senderID: "981686413111"
},
ios: {
alert: "true",
badge: "true",
sound: "true"
},
windows: {}
};
$cordovaPushV5.initialize(options).then(function (result) {
// start listening for new notifications
$cordovaPushV5.onNotification();
// start listening for errors
$cordovaPushV5.onError();
// register to get registrationId
$cordovaPushV5.register().then(function (registrationId) {
// save `registrationId` somewhere;
console.log(registrationId);
localStorage.setItem('deviceID', registrationId);
}, function (err) {
console.log(err);
});
});
$rootScope.$on('$cordovaPushV5:notificationReceived', function (event, data) {
console.log(data);
});
$rootScope.$on('$cordovaPushV5:errorOccurred', function (event, error) {
console.log("notification error occured");
console.log("event object: ", event);
console.log("error object: ", error);
});
$cordovaPushV5.finish().then(function (result) {
// OK finished - works only with the dev-next version of pushV5.js in ngCordova as of February 8, 2016
}, function (err) {
// handle error
console.log('finish error');
});
//$cordovaPushV5.unregister();
});
});
//# sourceMappingURL=app.js.map
Here is my screenshot of FCM history -
FCM History
I follow the following links to implement -
https://github.com/yafraorg/yafra/wiki/Blog-Ionic-PushV5
What am I missing ?