I am new to mobile app development and ionic 2. I get the google authentication working fine for a web app using angularfire2 but that doesn't work on a mobile device (yet?).
I am using ionic 2 version 2.0.0-beta.35 and firebase 3.2.1
Searching led me to the understanding that for the time being I need to use the google+ plugin for cordova, which I have installed.
I am trying this method in my ts code:
loginWithGooglePlugin()
{
return Observable.create(observer =>
{
// note for iOS the googleplus plugin requires ENABLE_BITCODE to be turned off in the Xcode
window.plugins.googleplus.login(
{
'scopes': 'profile email', // optional, space-separated list of scopes, If not included or empty, defaults to `profile` and `email`.
'webClientId': '_google_client_app_id_.apps.googleusercontent.com',
'offline': true, // optional, but requires the webClientId - if set to true the plugin will also return a serverAuthCode, which can be used to grant offline access to a non-Google server
},
function (authData)
{
console.log('got google auth data:', JSON.stringify(authData, null, 2));
let provider = firebase.auth.GoogleAuthProvider.credential(authData.idToken, authData.accessToken);
firebase.auth().signInWithCredential(provider).then((success) =>
{
console.log('success!', JSON.stringify(success, null, 2));
observer.next(success);
}, (error) =>
{
console.log('error', JSON.stringify(error, null, 2))
});
},
function (msg)
{
this.error = msg;
}
);
});
}
But the compiler keeps complaining about two things:
1. window.plugins is unknown. How can I convince ts that it's there?
There is no credential on the GoogleAuthProvider object. Searching yielded this link: firebase docs which says there was a method getCredential, which is not recognized either.
My typings seem to be fine. GoogleAuthProvider itself is recognized.
How can I fix this?
Actually, this is a bug in the typescript definitions. The Firebase team has been notified and is working on a fix. In the meantime use the following workaround:
(<any> firebase.auth.GoogleAuthProvider).credential
In my Ionic2 RC1 + Firebase3.5 + AngularFire2.beta5 project I had the same problem... Google Auth with Popup worked in Browser but not in my Android .APK
Firstly, I add 192.168.1.172 to my Firebase Console authorized domain list and <allow-navigation href="http://192.168.1.172:8100"/> to my config.xml.
After this, I found that installing Cordova InAppBrowser plugin solves my problem definitively.
I didn't need to modify my code, only plug and play, exactly like David East says in his Social login with Ionic blog.
Related
how does this package (razorpay_flutter 1.3.4) works in flutter. In the official docs it says (This flutter plugin is a wrapper around our Android and iOS SDKs.) how exactly does this package manage to integrate in flutter. Does it install the official android or iOS SDK while runtime or in app build time
Is there a way to use Native SDK in our flutter app
Trying to understand how to use the razor pay SDK properly.
Here is very easy way to implement RazorPay in Flutter app, just follow below steps.
add dependency in your pubspec.yaml.(https://pub.dev/packages/razorpay_flutter)
Feel some details for payment and Add your api key, here is example of that.
var options = {
'key': '<YOUR_KEY_HERE>',
'amount': 100,
'name': 'Acme Corp.',
'description': 'Fine T-Shirt',
'prefill': {
'contact': '8888888888',
'email': 'test#razorpay.com'
}
};
Now we have to open RazorPay Screen and go for pay and here is example of open razorpay screen.
_razorpay.open(options);
I Hope this solution can be work.
I need to add those to Android files:
android:usesCleartextTraffic="true" and <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
But I'm using managed workflow and I don't know how to add those lines to app.json file.
I did this plugin which seems to work:
const { createRunOncePlugin, withAndroidManifest } = require('#expo/config-plugins');
const withAndroidManifestHavingBetterSecuritySettings = config => {
return withAndroidManifest(config, config => {
const androidManifest = config.modResults.manifest;
const mainApplication = androidManifest.application[0];
if(process.env.CHANNEL !== 'dev') {
androidManifest.$ = {
...androidManifest.$,
'xmlns:tools': 'http://schemas.android.com/tools',
};
mainApplication.$['tools:replace'] = 'android:usesCleartextTraffic';
mainApplication.$['android:usesCleartextTraffic'] = 'false';
}
return config;
});
};
module.exports = createRunOncePlugin(
withAndroidManifestHavingBetterSecuritySettings,
'withAndroidManifestHavingBetterSecuritySettings',
'1.0.0'
);
I had many issues related to merging of AndroidManifest files when "developmentClient": true in my eas.json file (related to me dev eas profile). I believe that it's related to the fact that the debug/AndroidManifest is a higher priority manifest than main/AndroidManifest (not sure though). So my solution was not to ignore the changes when building the dev profile. Hardening security settings in development builds do not seem useful anyhow.
So I struggled with this problem for a while now and the only solution I could come up with was setting the minimum sdk version of the android app from 21 to 28. This is not ideal as my application now does not support old android devices, but doing this defaults the usesClearTextTraffic flag to false.
If your app works fine while developing in expo, but after generating the APK some functions don't work, try this. In my case the APK crashed on login, but building in development with expo was working fine. The problem was that traffic is encrypted so that's why I ended up here trying to set clear text traffic. The problem in my case was with expoPushToken, in the APK it throws an exception I wasn't catching (building with expo worked fine as I said before, no exception). So, if the exception happens just catch it and set the token to empty string.
So, I had this:
import * as Notifications from "expo-notifications";
export async function getDevicePushTokenForAPP() {
const pushToken = await Notifications.getExpoPushTokenAsync();
return pushToken.data;
}
So then, I added the try and catch:
export async function getDevicePushTokenForAPP() {
try {
const pushToken = await Notifications.getExpoPushTokenAsync();
return pushToken.data;
} catch (e) {
return "";
}
}
Now if you build the APK again (expo build:android) it should work fine, in my case login worked. But please note this is for testing purposes only, I needed the APK to quickly show it to the client. (Note that you will need the bundle, not the apk, when uploading to the Playstore). This is a quick fix for you to test the APK; but with no token, push notifications won't work. The final fix is to add firebase to your project, it's mandatory now, so add firebase and with the firebase unique ID, your push notification will work in your APK.
My conclusion is that expo uses its own ID to communicate with firebase, that's why it works while developing but the APK doesn't go through expo and tries to connect to firebase directly, but crashes because there's no ID.
You should update your app.json like that:
"android": {
"usesCleartextTraffic": true,
uses-permission android:name
},
Is #react-native-firebase/admob deprecated? or just.. Why it doesn't work?
I am using #react-native-firebase/admob (https://rnfb-docs.netlify.app/admob/usage).
Everything works fine before to use "admob()". When I add admob() to the code appears this error:
"TypeError: (0, _admob.default) is not a function"
Do someone know why?
My code below (basic usage):
import React from 'react';
import { Text, View} from 'react-native';
import admob, { MaxAdContentRating } from '#react-native-firebase/admob';
import { InterstitialAd, RewardedAd, BannerAd, TestIds } from '#react-native-
firebase/admob';
import { BannerAdSize} from '#react-native-firebase/admob';
class App extends React.Component{
componentDidMount(){
// this was taked of official page: https://rnfb-docs.netlify.app/admob/usage#installation
admob()
.setRequestConfiguration({
// Update all future requests suitable for parental guidance
maxAdContentRating: MaxAdContentRating.PG,
// Indicates that you want your content treated as child-directed for purposes of COPPA.
tagForChildDirectedTreatment: true,
// Indicates that you want the ad request to be handled in a
// manner suitable for users under the age of consent.
tagForUnderAgeOfConsent: true,
})
.then(() => {
// Request config successfully set!
});
}
render(){
return(
<View style={{
alignItems:"center",
justifyContent:"center",
height:"100%"}}>
<Text style={{color:"black"}}>
Hola
</Text>
<BannerAd
unitId={TestIds.BANNER}
size={BannerAdSize.FULL_BANNER} />
</View>
)
}
}
export default App;
Despite #CodeJoe Answer, I still got confused by different Documentations for the React Native Firebase that where around, hence I spend lots of time and energy to get around it.
I open an issue here where is confirmed that Google removed the AdMob Package since v11.5.0.
AdMob is no longer in Firebase APIs, so this module no longer wraps it, there is no documentation to correct.
However it did exist as recently as v11.5.0 here and if you browse the repository at that point, you may consider the e2e tests for AdMob at the time a primer on "How To Use AdMob" https://github.com/invertase/react-native-firebase/tree/0217bff5cbbf233d7915efb4dbbdfe00e82dff23/packages/admob/e2e
Please, don't be like me and check the correct Documentation and website:
Correct
https://rnfirebase.io
Wrong Wrong Wrong, this refers to an older verison
https://rnfb-docs.netlify.app
The internet has a long memory, so there are stale copies of the docs out and about yes, but rnfirebase.io is always the official and current doc site
Admob was removed completely from the firebase ecosystem by Google so it does not exist here no. There are some community packages for it, our v11.5 version that has it, and we hope to peel our implementation out and update it for the community but it takes time and we are unfortunately still backlogged on official firebase apis, so it has not happened yet
So for AdMob solution I would use another Library, and use react-native-firebase for the Solutions that they currently provide
Alternative Library (August 2021)
DISCLAIMER
React Native Firebase is a great library still for the other packages they provide (Firebase, Analitycs...) and the Admob version 11.5 is still a solution. These are just suggestion for alternatives for Admob.
react-native-admob-alpha Simple and fresh library, recently updated.
react-native-admob-native-ads Another brand new library, they implement Admob Native Advanced Ads.
Expo AdMob (Available also for bare React-Native Projects)
To complete your searching I'll add that Admob is removed from React Native Firebase and there is no plan to implement it again. Only re-host code on an external repository.
Last supported version is 11.5.0
It means if you would like to use RN Firebase Admob before re-host you need to use all other services (like RNF analytics) with this version.
For more info please check https://github.com/invertase/react-native-firebase/issues/5329#issuecomment-843272057
Remember to use
dependencies{
"#react-native-firebase/admob": "11.5.0",
"#react-native-firebase/app": "11.5.0",
}
instead of
dependencies{
"#react-native-firebase/admob": "^11.5.0",
"#react-native-firebase/app": "^11.5.0",
}```
I could solve it.
SOLVED
Just check in the file "package.json" that packages of firebase has the same version, example:
dependencies{
"#react-native-firebase/admob": "^11.5.0",
"#react-native-firebase/app": "^11.5.0"
}
TIP
Works to similars errors.
I am able to use 11.5.0 downgrade trick in react native 0.65.1 for my RewardedAds. I edited the package.json file as said. It didn't work but I managed to run it in a different way:
Close any running react-native related terminals. Uninstall #react-native-firebase/app.
npm uninstall #react-native-firebase/app
Install the #react-native-firebase/app version 11.5.0 directly with this command.
npm install #react-native-firebase/app#11.5.0
After the installation, go to package.json>dependencies and do both packages versions the same(11.5.0) and remove ^.
"#react-native-firebase/admob": "11.5.0",
"#react-native-firebase/app": "11.5.0",
Start the react-native with fresh cache then run-android.
npx react-native start --reset-cache
npx react-native run-android
In My ionic Cordova Application, I am using In App Purchase Plugin: https://github.com/j3k0/cordova-plugin-purchase
Here is the method that I use to initialise store:
storekit.init({
debug: true, // Enable IAP messages on the console
ready: service.IAP.onReady,
purchase: service.IAP.onPurchase,
restore: service.IAP.onRestore,
error: service.IAP.onError
});
This Initialization works fine with iOS and all the products loading fine as well, But Android device does not load In Purchase.
I guess, For android there is a different initialization method.
I have added plugin in app:
cordova plugin add cc.fovea.cordova.purchase --variable BILLING_KEY="<BILLING_KEY>"
Please help.
Firstly, when I was using it, the npm version was a little buggy on android. Try removing it and adding it from Git.
cordova plugin add https://github.com/j3k0/cordova-plugin-purchase.git --variable BILLING_KEY="MIIB...AQAB"
Secondly, it looks like you are maybe using some older syntax. The doco for this plugin doesnt really have very good version control. There are different versions of doco all over the net. I think this is the latest version.
This is my initialisation code. See if it works for you too.
products = ["my.test.product"];
for (var i = 0; i < products.length; i++) {
if (window.store) {
store.register({
id: products[i],
alias: 'alias '+i,
type: store.NON_CONSUMABLE
});
}
}
// When everything goes as expected, it's time to celebrate!
if (window.store) store.ready(function() {
console.log("\\o/ STORE READY \\o/");
});
// After we've done our setup, we tell the store to do
// it's first refresh. Nothing will happen if we do not call store.refresh()
if (window.store) store.refresh();
You can also send the store object to console.log to have a good look at it in chrome debugger.
Oh, and if you have more than one app, make sure you are using the correct BILLING_KEY by removing and readding the plugin.
Good Luck!
I'm running example code (found below) through phonegap build to produce an android apk.
https://github.com/phonegap-build/FacebookConnect/blob/master/example/Simple/index.html
When I try to log into facebook through the app on an android device (with the facebook app installed), I get this error:
Invalid android_key parameter J4INwYsuTyQ_LJc1d3WZ2HReg7M does not match any allowed android key. Configure your app key hashes at http://developers.facebook.com/apps/'app id'
I have copy-pasted this key into the key hashes section of my app's android settings but it still throws the same error when I try to log in using the app.
How can I get this app to log into facebook successfully?
OR: What is another way to enable an android app to log into facebook using phonegap?
Here are some things I have done:
In my facebook app's settings:
Set 'Package name' to the 'widget id' found in my phonegap config.xml.
Set 'Class name' to the Package name with '.ProjectActivity' appended to it.
Enabled 'Single Sign on' and disabled 'Deep linking'.
Made the app open to the public (through the 'Status & Review' section.
In my phonegap config.xml (found in the /www directory in phonegap project):
Entered APP_ID as the ID found in my facebook app dashboard
Entered APP_NAME as the 'Namespace' found in my facebook app settings
In my phonegap build app settings:
Made a keystore (using this answer: https://stackoverflow.com/a/19315975/1696114) and used it to generate a release apk.
I think you should use facebook phonegap plugin as your authentication.
Download and install into your cordova project.
https://github.com/phonegap/phonegap-facebook-plugin
Use this command to install it.
cordova plugin add https://github.com/phonegap/phonegap-facebook-plugin.git --variable APP_ID="xxxxxxxxxxxxx" --variable APP_NAME=“xxxxxxxx”
Then setup your facebook app here:
http://developers.facebook.com/apps/
Then make sure you have this script in your project.
cdv-plugin-fb-connect.js
facebook-js-sdk.js
After that, paste this code into your main script
if ((typeof cordova == 'undefined') && (typeof Cordova == 'undefined')) alert('Cordova variable does not exist. Check that you have included cordova.js correctly');
if (typeof CDV == 'undefined') alert('CDV variable does not exist. Check that you have included cdv-plugin-fb-connect.js correctly');
if (typeof FB == 'undefined') alert('FB variable does not exist. Check that you have included the Facebook JS SDK file.');
FB.Event.subscribe('auth.login', function(response) {
//alert('auth.login event');
});
FB.Event.subscribe('auth.logout', function(response) {
//alert('auth.logout event');
});
FB.Event.subscribe('auth.sessionChange', function(response) {
//alert('auth.sessionChange event');
});
FB.Event.subscribe('auth.statusChange', function(response) {
//alert('auth.statusChange event');
});
function getSession() {
alert("session: " + JSON.stringify(FB.getSession()));
}
function getLoginStatus() {
FB.getLoginStatus(function(response) {
if (response.status == 'connected') {
alert('logged in');
} else {
alert('not logged in');
}
});
}
var friendIDs = [];
var fdata;
function logout() {
FB.logout(function(response) {
alert('logged out');
window.location.replace("#login");
});
}
function login() {
FB.login(
function(response) {
if (response.authResponse) {
alert('logged in');
FB.api('/me', function(me) {
if (me.id) {
localStorage.id = me.id;
localStorage.email = me.email;
localStorage.name = me.name;
window.location.replace("#home");
}
else {
alert('No Internet Connection. Click OK to exit app');
navigator.app.exitApp();
}
});
} else {
alert('not logged in');
}
}, {
scope: "email"
});
}
document.addEventListener('deviceready', function() {
try {
//alert('Device is ready! Make sure you set your app_id below this alert.');
FB.init({
appId: "appid",
nativeInterface: CDV.FB,
useCachedDialogs: false
});
document.getElementById('data').innerHTML = "";
} catch (e) {
alert(e);
}
}, false);
use login() to login . Enjoy!!
I successfully made an app which can log into facebook by using the phonegap-facebook-plugin and by building my cordova/phonegap project locally.
I made a new cordova project and added the android platform for this project, following the instructions here: http://docs.phonegap.com/en/3.4.0/guide_overview_index.md.html#Overview
In doing this I discovered I had made my previous project using an older cordova version (3.1) un-intentionally and that I hadn't installed the cordova command line interface. There may have been other issues with the way I made my first project.
I then added the phonegap-facebook-plugin found here: https://github.com/phonegap/phonegap-facebook-plugin using this command (from my project location):
cordova plugin add https://github.com/phonegap/phonegap-facebook-plugin.git --variable APP_ID="xxxxxxxxxxxxx" --variable APP_NAME=“xxxxxxxx”
(replacing APP_ID value with my facebook app id and APP_NAME value with my app's namespace).
I then replaced my index.html with the example index file found at the phonegap-facebook-plugin github page + /blob/master/example/Simple/index.html (replacing the app_id value with my app id).
I then ran the app straight to my android device using:
cordova run android
In this app, I'm able to use the interface provided by the example to login, post to my own or friends' walls etc. Using this new project (with updated cordova version) I may be able to use phonegap build but I haven't tried yet.
Thanks to Dato' Mohammad Nurdin for the suggestion to use this plugin.