Cordova Plugin Purchase - redirect after successful subscription - ios

I am using this plugin (https://github.com/j3k0/cordova-plugin-purchase) to handle a in app subscription.
iap.validator = "https://validator.fovea.cc/v1/validate?appName=XXX";
//initiate initInAppPurchase function
useEffect(() => {
const init = async () => {
await initInAppPurchase();
}
init();
}, []);
//if on an ios or android device, then get product info
const initInAppPurchase = () => {
if ((isPlatform('ios')) || (isPlatform('android'))) {
iap.verbosity = iap.DEBUG;
iap.register({
id: "tpmonthly",
alias: "Monthly",
type: iap.PAID_SUBSCRIPTION
});
iap.ready(() => {
let product = iap.get('Monthly');
setPrice(product.price)
setProduct(product)
})
iap.refresh();
}
}
//if user clicks purchase button
const purchaseProduct = () => {
if (product.owned) {
alert('A subscription is currently active.')
} else {
iap.order('Monthly').then(() => {
iap.when("tpmonthly").approved((p: IAPProduct) => {
p.verify();
});
iap.when("tpmonthly").verified((p: IAPProduct) => {
p.finish();
history.push("/ios-signup/");
});
})
}
}
return (
<Button size="large" variant="outlined" onClick={purchaseProduct}>Subscribe Monthly for {productPrice}</Button>
);
What I am hoping to get is that once the subscription is verified that it then redirects the app to /ios-signup/ .. this is not happening.
Is this code correct? And why would it not redirect after p.finish?

Related

Service worker and payment Handlers

I created a service worker for a payment manager. When I checked the server is installed but I do not see the payment methods installed on the browser.
i added the event install fetch and load but i can't show the payment methods register in browser..
Any help please
My installer is
navigator.serviceWorker.register('sw.js').then(() => {
return navigator.serviceWorker.ready;
}).then((registration) => {
if (!registration.paymentManager) {
console.log('No payment handler capability in this browser. Is chrome://flags/#service-worker-payment-apps enabled?');
return;
}
if (!registration.paymentManager.instruments) {
return;
}
registration.paymentManager.instruments
.set('instrument-key', {
name: 'Chrome uses name and icon from the web app manifest',
enabledMethods: ['https://...'],
method: 'https://...',
})
.then(() => {
registration.paymentManager.instruments.get('instrument-key').then((instrument) => {
}).catch(...
})
My server worker
let payment_request_event;
let resolver;
let client;
const addResourcesToCache = async (resources) => {
const cache = await caches.open("v1");
await cache.addAll(resources);
};
self.addEventListener('install', event => {
event.waitUntil(
addResourcesToCache([
"/",
"/index.html",
])
);
console.log(`SW: Event fired: ${event.type}`);
console.dir(event);
});
self.addEventListener('activate', event => {
console.dir(event);
});
self.addEventListener('fetch', event => {
event.respondWith(fetch(event.request));
});
self.addEventListener('canmakepayment', e => {
console.log('canmakepayment', e);
e.respondWith(true);
});
self.addEventListener('paymentrequest', async e => {
console.log(e)
payment_request_event = e;
e.respondWith(resolver.promise);
// Open the checkout page.
try {
// Open the window and preserve the client
client = await e.openWindow('https://...html');
...

WebRTC - how to switch between getUserMedia and getDisplayMedia tracks inside RTCPeerConnection

I'm trying to develop an app where users can can video call to each other and share their screens using WebRTC technology. I have succeed with either video call or screen sharing app and now I'm trying to make it to be able to switch between getUserMedia and getDisplayMedia on button click during a call inside the same RTCPeerConnection but it doesn't work.
This is how I thought it could work:
function onLogin(success) {
var configuration = { offerToReceiveAudio: true, offerToReceiveVideo: true, "iceServers" : [ { "url" : "stun:stun.1.google.com:19302" } ] };
myConnection = window.RTCPeerConnection ? new RTCPeerConnection(configuration, { optional: [] }) : new RTCPeerConnection(configuration, { optional: [] });
myConnection.onicecandidate = function (event) {
console.log("onicecandidate");
if (event.candidate) send({ type: "candidate", candidate: event.candidate });
};
myConnection.ontrack=function(e){
try{remoteVideo.src = window.webkitURL?window.webkitURL.createObjectURL(e.streams[0]):window.URL.createObjectURL(e.streams[0])}
catch(err){remoteVideo.srcObject=e.streams[0]}
}
myConnection.ondatachannel=openDataChannel
openDataChannel();
startAVStream();
//startSStream()
};
function startAVStream(enable){
if(sStream)sStream.getTracks().forEach( function (track) {
try{myConnection.removeTrack( track, sStream );}
catch(e){}
} );
navigator.mediaDevices.getUserMedia({ video: true, audio: true }).then(s => {
if(!avStream){
avStream = s;
avStream.getTracks().forEach( function (track) {
myConnection.addTrack( track, avStream );
} );
}
}, function (error) { console.log(error); });
}
function startSStream(enable){
if(avStream)avStream.getTracks().forEach( function (track) {
try{myConnection.removeTrack( track, avStream );}
catch(e){}
} );
navigator.mediaDevices.getDisplayMedia({ video: true }).then(s => {
if(!sStream){
sStream = s;
sStream.getTracks().forEach( function (track) {
myConnection.addTrack( track, sStream );
} );
}
}, function (error) { console.log(error); });
}
Can anyone tell me how I can switch between tracks inside the same RTCPeerConnection or should I create 2 separate RTCPeerConnection - one for video/audio streaming and another for screen sharing?
Any help appreciated! Thanks!
You could use RTCRtpSender.replaceTrack to splice the screen capture track. This doesn't require renegotiation, and therefore has very low latency.
let newstream = navigator.mediaDevices.getDisplayMedia({});
let newtrack = newstream.getTracks()[1];
if(newtrack.kind !== 'video')
throw new Error('Eek!?');
pc.getSenders().forEach(async s => {
if(s.track && s.track.kind === 'video')
await s.replaceTrack(newtrack);
});
The test for s.track not being null deals with the case where you previously called replaceTrack(..., null).
shareScreen = () =>{
const success = (stream) => {
window.localStream = stream
// this.localVideoref.current.srcObject = stream
// localStream.replaceStream(stream);
this.setState({
localStream: stream
})
Object.values(this.state.peerConnections).forEach(pc => {
pc.getSenders().forEach(async s => {
console.log("s.track ",s.track);
if(s.track && s.track.kind === 'video'){
stream.getTracks().forEach(track => {
// pc.addTrack(track, this.state.localStream)
s.replaceTrack(track);
});
}
});
});
}
const failure = (e) => {
console.log('getUserMedia Error: ', e)
}
navigator.mediaDevices.getDisplayMedia({ cursor: true }).then(success).catch(failure)}

IOS Notification Permission alert does not show

SDK Version: 39.0.0
Platforms(Android/iOS/web/all): All
I am not getting accept or decline notifications permissions alert when loading my app in production.
I have tried clearing certificates and keys and allowing expo to add everything from a clean slate, but still no luck. I am starting to think maybe it’s my code which is the reason why the alert doesn’t get fired.
import Constants from "expo-constants";
import * as Notifications from "expo-notifications";
import { Permissions } from "expo-permissions";
import { Notifications as Notifications2 } from "expo";
Notifications.setNotificationHandler({
handleNotification: async () => ({
shouldShowAlert: true,
shouldPlaySound: true,
shouldSetBadge: false
})
});
export default class LoginScreen extends React.Component {
state = {
email: "",
password: "",
notification: {},
errorMessage: null
};
async componentDidMount() {
this.registerForPushNotificationsAsync();
//Notifications.addNotificationReceivedListener(this._handleNotification);
Notifications2.addListener(data => {
this.setState({ notification: data });
});
Notifications.addNotificationResponseReceivedListener(
this._handleNotificationResponse
);
}
_handleNotification = notification => {
this.setState({ notification: notification });
};
_handleNotificationResponse = response => {
console.log(response);
};
handleLogin = async () => {
try {
const { email, password } = this.state;
const expoPushToken = await Notifications.getExpoPushTokenAsync();
console.log(expoPushToken);
const userinfo = await firebase
.auth()
.signInWithEmailAndPassword(email, password);
console.log("user ID ", userinfo.user.uid);
await firebase
.firestore()
.collection("users")
.doc(userinfo.user.uid.toString())
.update({
expo_token: expoPushToken["data"]
})
.then(function() {
console.log("token successfully updated!");
})
.catch(function(error) {
// The document probably doesn't exist.
console.error("Error updating document: ", error);
});
} catch (error) {
console.log("=======Error in login", error);
this.setState({ errorMessage: error.message });
}
};
registerForPushNotificationsAsync = async () => {
if (Constants.isDevice) {
const { status: existingStatus } = await Permissions.getAsync(
Permissions.NOTIFICATIONS
);
let finalStatus = existingStatus;
if (existingStatus !== "granted") {
const { status } = await Permissions.askAsync(
Permissions.NOTIFICATIONS
);
finalStatus = status;
}
if (finalStatus !== "granted") {
alert("Failed to get push token for push notification!");
return;
}
const token = await Notifications.getExpoPushTokenAsync();
console.log(token);
//this.setState({ expoPushToken: token });
} else {
alert("Must use physical device for Push Notifications");
}
if (Platform.OS === "android") {
Notifications.setNotificationChannelAsync("default", {
name: "default",
importance: Notifications.AndroidImportance.MAX,
vibrationPattern: [0, 250, 250, 250],
lightColor: "#FF231F7C"
});
}
};
import { Permissions } from "expo-permissions";
should of been
import * as Permissions from 'expo-permissions';
Sometimes we all make simple mistakes.

don't display notification in ios device when use react-native-fcm

i'm using from react-native-fcm for recieve pushNotification and do all config in this document(https://github.com/evollu/react-native-fcm)
in ios device only recieve notification and call notificationListener that checked by console.log but dont display notification message and alert even test FCM.presentLocalNotification for show local notification still dont show notification
async componentDidMount() {
if (Platform.OS === 'ios') {
try {
const result = await FCM.requestPermissions({ badge: false, sound: true, alert: true });
} catch (e) {
console.error(e);
}
FCM.getFCMToken().then(token => {
if (token !== undefined) {
// this.props.onChangeToken(token);
} else {
console.log('TOKEN (getFCMToken)', 'null');
}
});
// FCM.getAPNSToken().then(token => {
// this.props.onAPNToken(token);
// });
FCM.getInitialNotification().then(notif => {
console.log('INITIAL NOTIFICATION', notif);
});
this.notificationListener = FCM.on(FCMEvent.Notification, async (notif) => {
console.log(" >> notificationListener: ", notif)
if (notif.local_notification) return;
FCM.presentLocalNotification({
body: 'tdtydt',
priority: "high",
title: 'notif.fcm.title',
sound: "default",
show_in_foreground: true,
local_notification: true,
icon: "ic_launcher",
status: "400"
});
});
this.refreshTokenListener = FCM.on(FCMEvent.RefreshToken, token => {
console.log('TOKEN (refreshUnsubscribe)', token);
this.props.onChangeToken(token);
});
FCM.enableDirectChannel();
this.channelConnectionListener = FCM.on(FCMEvent.DirectChannelConnectionChanged, (data) => {
console.log(`direct channel connected${data}`);
});
setTimeout(() => {
FCM.isDirectChannelEstablished().then(d => console.log('isDirectChannelEstablished', d));
}, 500);
}

stripe create user firebase cloud functions

I am attempting to create a stripe user upon user creation for firebase, I keep receiving this error (error displayed below). the code for the function is also displayed below. if I need to post the database structure I will do so, I currently do not have any structure for stripe customer (this might be where issue occurs). if anyone can assist I would greatly appreciate it.
Error:
Error: Reference.child failed: First argument was an invalid path = "/stripe_customers/${data.uid}/customer_id". Paths must be non-empty strings and can't contain ".", "#", "$", "[", or "]"
at Object.exports.validatePathString (/user_code/node_modules/firebase-admin/node_modules/#firebase/database/dist/cjs/src/core/util/validation.js:282:15)
at Object.exports.validateRootPathString (/user_code/node_modules/firebase-admin/node_modules/#firebase/database/dist/cjs/src/core/util/validation.js:293:13)
at Reference.child (/user_code/node_modules/firebase-admin/node_modules/#firebase/database/dist/cjs/src/api/Reference.js:72:30)
at Database.ref (/user_code/node_modules/firebase-admin/node_modules/#firebase/database/dist/cjs/src/api/Database.js:60:54)
at stripe.customers.create.then (/user_code/index.js:41:29)
at tryCatcher (/user_code/node_modules/stripe/node_modules/bluebird/js/release/util.js:16:23)
at Promise._settlePromiseFromHandler (/user_code/node_modules/stripe/node_modules/bluebird/js/release/promise.js:512:31)
at Promise._settlePromise (/user_code/node_modules/stripe/node_modules/bluebird/js/release/promise.js:569:18)
at Promise._settlePromise0 (/user_code/node_modules/stripe/node_modules/bluebird/js/release/promise.js:614:10)
at Promise._settlePromises (/user_code/node_modules/stripe/node_modules/bluebird/js/release/promise.js:693:18)
at Async._drainQueue (/user_code/node_modules/stripe/node_modules/bluebird/js/release/async.js:133:16)
at Async._drainQueues (/user_code/node_modules/stripe/node_modules/bluebird/js/release/async.js:143:10)
at Immediate.Async.drainQueues (/user_code/node_modules/stripe/node_modules/bluebird/js/release/async.js:17:14)
at runCallback (timers.js:672:20)
at tryOnImmediate (timers.js:645:5)
at processImmediate [as _immediateCallback] (timers.js:617:5)
Functions:
'use strict';
const functions = require('firebase-functions');
const admin = require('firebase-admin');
const logging = require('#google-cloud/logging')();
admin.initializeApp(functions.config().firebase);
const stripe = require('stripe')(functions.config().stripe.token);
const currency = functions.config().stripe.currency || 'USD';
//[START chargecustomer]
//charge the stripe customer whenever an amount is written to the realtime database
exports.createStripeCharge = functions.database.ref('/stripe_customers/{userId}/charges/{id}').onWrite((event) => {
const val = event.data.val();
if (val === null || val.id || val.error) return null;
return admin.database().ref(`/stripe_customers/${event.params.userId}/customer_id`).once('value').then((snapshot) => {
return snapshot.val();
}).then((customer) => {
const amount = val.amount;
const idempotency_key = event.params.id;
let charge = {amount, currency, customer};
if (val.source !== null) charge.source = val.source;
return stripe.charges.create(charge, {idempotency_key});
}).then((response) => {
return event.data.adminRef.set(response);
}).catch((error) => {
return event.data.adminRef.child('error').set(userFacingMessage(error));
}).then(() => {
return reportError(error, {user: events.params.userId});
});
});
// [end chargecustomer]]
// when user is created register them with stripe
exports.createStripeCustomer = functions.auth.user().onCreate((event) => {
const data = event.data;
return stripe.customers.create({
email: data.email,
}).then((customer) => {
return admin.database().ref(`/stripe_customers/${data.uid}/customer_id`).set(customer.id);
});
});
// add a payment source (card) for a user by writing a stripe payment source token to realtime database
exports.addPaymentSource =. functions.database.ref('/stripe_customers/{userId}/sources/{pushId}/token').onWrite((event) => {
const source = event.data.val();
if (sourve === null) return null;
return admin.database.ref(`/stripe_customers/${event.params.userId}/customer_id`).once('value').then((snapshot) => {
return snapshot.val();
}).then((customer) => {
return stripe.customers.createSource(customer, {source});
}).then((response) => {
return event.data.adminRef.parent.set(response);
}, (error) => {
return event.data.adminRef.parent.child('error').set(userFacingMessage(error));
}).then(() => {
return reportError(error, {user: event.params.userId});
});
});
// when a user deletes their account, clean up after the
exports.cleanupUser = functions.auth.user().onDelete((event) => {
return admin.database().ref(`/stripe_customers/${event.data.uid}`).once('value').then((snapshot) => {
return snapshot.val();
}).then((customer) => {
return stripe.customers.del(customer.customer_id);
}).then(() => {
return admin.database().ref(`/stripe_customers/${event.data.uid}`).remove();
});
});
function reportError(err, context = {}) {
const logName = 'errors';
const lof = logging.log(logName);
const metadata = {
resource: {
type: 'cloud_function',
labels: {function_name: process.env.FUNCTION_NAME},
},
};
const errorEvent = {
message: err.stack,
serviceContext: {
service: process.env.FUNCTION_NAME,
resourceType: 'cloud_function',
},
context: context,
};
return new Promise((resolve, reject) => {
log.write(log.entry(metadata, errorEvent), (error) => {
if (error) {
reject(error);
}
resolve();
});
});
}
// end [reportError]
// sanitize the error message for the user
function userFacingMessage(error) {
returnerror.type ? error.message : 'an error occurred, developers have been altered';
}
Database Structure:
In your code you have this:
ref('/stripe_customers/${event.params.userId}/customer_id')
this ${event.params.userId} should give you the value of the wildcard, but since you are using ' it is including the $ in the path also. So you need to change it like this:
ref(`/stripe_customers/${event.params.userId}/customer_id`)
by changing ' to `

Resources