Expo in-app-purchases: ReferenceError: Can't find variable: connectAsync - android

I'm trying to follow along with expo's in app purchases documentation.. I have the android developer account and set up my in-app-purchase on that account for the same app. I'm just trying to get started with the documentation and receive an error immediately.
If you look at the documentation, I'm just trying to enter in what's in the first example. I call this function at the beginning of the render method of my app.
import * as InAppPurchases from 'expo-in-app-purchases';
...
const getHistory = async function(){
const history = await connectAsync();
if (history.responseCode === IAPResponseCode.OK) {
history.results.forEach(result => {
console.log(result)
});
}
}
And I receive these errors
[Unhandled promise rejection: ReferenceError: Can't find variable: connectAsync]
* App.js:57:19 in getHistory
- node_modules/regenerator-runtime/runtime.js:45:44 in tryCatch
- node_modules/regenerator-runtime/runtime.js:271:30 in invoke
- node_modules/regenerator-runtime/runtime.js:45:44 in tryCatch
- node_modules/regenerator-runtime/runtime.js:135:28 in invoke
- node_modules/regenerator-runtime/runtime.js:170:17 in Promise$argument_0
- node_modules/promise/setimmediate/core.js:45:7 in tryCallTwo
...

You need to import in-app purchases module first. Like this:
import * as InAppPurchases from 'expo-in-app-purchases';
const getHistory = async function(){
const history = await InAppPurchases.connectAsync();
if (history.responseCode === IAPResponseCode.OK) {
history.results.forEach(result => {
console.log(result)
});
}
}
Also, note this from the documentation you linked:
You must ensure that you have installed and configured the react-native-unimodules package before continuing.
and this:
Note that in-app purchases require physical devices to work on both platforms and therefore cannot be tested on simulators.

Since you used:
import * as InAppPurchases from 'expo-in-app-purchases';
That means your code should look like:
...
const getHistory = async function(){
const history = await InAppPurchases.connectAsync();
if (history.responseCode === InAppPurchases.IAPResponseCode.OK) {
history.results.forEach(result => {
console.log(result)
});
}
}

Related

Why navigator.geolocation.getcurrentposition is not available with react native and expo

I am trying to get some position information from a device, I am using React-native, Expo, and ExpoGo on android mobile, I am not using simulators, the application is working with ExpoGo on Android, but geolocation is not working, it sends this error message every time:
window.navigator.geolocation.getCurrentPosition is not available. Import and execute installWebGeolocationPolyfill() from expo-location to add it, or use the expo-location APIs instead.
Please help me find the solution to this issue.
This is the App code used:
import { Text, View} from "react-native";
import styles from "./styles";
const API_KEY = "";
const URL = `https://maps.google.com/maps/api/geocode/json?key=${API_KEY}&latlng=`;
export default function WhereAmI() {
const [address, setAddress] = useState("loading...");
const [longitude, setLongitude] = useState();
const [latitude, setLatitude] = useState();
useEffect(() => {
function setPosition({ coords: { latitude, longitude } }) {
setLongitude(longitude);
setLatitude(latitude);
fetch(`${URL}${latitude},${longitude}`)
.then(
(resp) => resp.json(),
(e) => console.error(e)
)
.then(({ results }) => {
setAddress(results[0].formatted_address);
});
}
navigator.geolocation.getCurrentPosition(setPosition);
let watcher = navigator.geolocation.watchPosition(
setPosition,
(err) => console.error(err),
{ enableHighAccuracy: true }
);
return () => {
navigator.geolocation.clearWatch(watcher);
};
});
return (
<View style={styles.container}>
<Text style={styles.label}>Address: {address}</Text>
<Text style={styles.label}>Latitude: {latitude}</Text>
<Text style={styles.label}>Longitude: {longitude}</Text>
</View>
);
}
I fixed this problem, and this worked for me.
geolocation on iOS and Android:
I installed the expo-location package by running expo install expo-location.
I imported expo location in App.js as Location: import * as Location from 'expo-location'.
I used the #installWebGeolocationPolyfill function that polyfills #navigator.geolocation for interop with the core React Native
and Web API approach to geolocation just before using of the #navigator.geolocation.getCurrentPosition like
this:
# ... some code
Location.installWebGeolocationPolyfill()
navigator.geolocation.getCurrentPosition(setPosition);
# ... some code
2.The error 'formatted_address' is undefined:
That because there is no API_KEY, you should get an API key from Google, instead, I just Added it manually into the #setPosition function like this:
#...some code
.then(
({ results }) => {
results[0]={formatted_address:"here"}
setAddress(results[0].formatted_address)
},
#...some code

React Native : Native method ExpoLocalAuthentication.authenticateAsync expects 0 arguments but received 1

I'm in need of your expertise in React Native.
I'm trying to use expo-local-authentication for local fingerprint authentication for my application.
My project was created using expo init command.
I have done the setup as per the documentation and still running into a strange issue:
Below is the error I'm facing for LocalAuthentication.authenticateAsync(options):
Native method ExpoLocalAuthentication.authenticateAsync expects 0
arguments but received 1
Here is the required part of my code:
import * as LocalAuthentication from 'expo-local-authentication';
const authenticate = async () => {
const hasHardwareAsync = await LocalAuthentication.hasHardwareAsync();
if (hasHardwareAsync) {
const supportedAuthentications = await LocalAuthentication.supportedAuthenticationTypesAsync();
if (supportedAuthentications.indexOf(1) !== -1) {
// Finger print supported
const isFingerprintEnrolled = await LocalAuthentication.isEnrolledAsync();
if (isFingerprintEnrolled) {
const options = {
promptMessage: 'Authenticate yourself',
};
try {
// Also tried with await but it throws the same error
// await LocalAuthentication.authenticateAsync(options)
LocalAuthentication.authenticateAsync(options).then(result => {
// I never get inside this block
console.warn(result)
})
.catch(error => {
console.warn('Authentication Error: ', error)
})
} catch (error) {
console.warn(error)
}
}
}
}
}
Not sure what I'm missing. Seems like there is no information available about the error. I also tried to run the LocalAuthentication.authenticateAsync() without any arguments but it still throws the same error.
Any help on what could be the root cause of the issue and how can I resolve it or any other alternative for local authentication would be highly appreciated.
Update your app to the latest version of expo (38 in my case) and to the latest version of expo-local-authentication, and the error goes away.

In App Purchase Verify Using Cloud Function

After Researching for last 24 hour i have found a very effective way to verify in app purchase but didn't get proper Information . I am looking to verify product purchase .
I tried to deploy the js file to firebase cloud function but showing i have error in exports.validatePurchases = functions.database method . Can anyone please have a look on it and fix the error ?
Here is the code :
const functions = require('firebase-functions');
const admin = require('firebase-admin');
const {google} = require("googleapis");
const publisher = google.androidpublisher('v2');
const authClient = new google.auth.JWT({
email: '',
key: '',
scopes: ['https://www.googleapis.com/auth/androidpublisher']
});
admin.initializeApp();
exports.validatePurchases = functions.database
.ref('/purchases/{uId}/{orderId}')
.onCreate((event, context) => {
const purchase = event.val();
if (purchase.is_processed === true) {
console.log('Purchase already processed!, exiting');
return null;
}
const orderId = context.params.orderId;
const dbRoot = event.ref.root;
const package_name = purchase.package_name;
const sku = purchase.sku;
const my_token = purchase.token;
authClient.authorize((err, result) => {
if (err) {
console.log(err);
}
publisher.purchases.products.get({
auth: authClient,
packageName: package_name,
productId: sku,
token: my_token
}, (err, response) => {
if (err) {
console.log(err);
}
// Result Status must be equals to 200 so that the purchase is valid
if (response.status === 200) {
return event.ref.child('is_validated').set(true);
} else {
return event.ref.child('is_validated').set(false);
}
});
});
return null;
});
The Error i have got while deploy :
Functions deploy had errors with the following functions:
validatePurchases
To try redeploying those functions, run:
firebase deploy --only functions:validatePurchases
To continue deploying other features (such as database), run:
firebase deploy --except functions
Error: Functions did not deploy properly.
In Firebase Function Log :
Code in file index.js can't be loaded.
Did you list all required modules in the package.json dependencies?
Detailed stack trace: Error: Cannot find module 'googleapis'
at Function.Module._resolveFilename (module.js:548:15)
at Function.Module._load (module.js:475:25)
at Module.require (module.js:597:17)
at require (internal/module.js:11:18)
at Object.<anonymous> (/srv/index.js:3:18)
at Module._compile (module.js:653:30)
at Object.Module._extensions..js (module.js:664:10)
at Module.load (module.js:566:32)
at tryModuleLoad (module.js:506:12)
at Function.Module._load (module.js:498:3)
First, run cmd on Function Folder of your project :
Then, In order to add it as a dependency, run the following command:
$ npm install googleapis
Now Check if any functions are live on your project. If there are functions in the firebase console remove it. Now Try Deploy.

FeathersJS login error when building for Android

I am building an Android app using Ionic. And using the following feathers_client.js
const feathers = require('#feathersjs/feathers');
const socketio = require('#feathersjs/socketio-client');
const auth = require('#feathersjs/authentication-client');
const io = require('socket.io-client');
const socket = io('http://mydomain.example:3030');
const feathers_client = feathers();
feathers_client
.configure(socketio(socket))
.configure(auth({ storage: window.localStorage }));
module.exports = feathers_client;
When I run the app at the browser it works fine. But when I run it at an Android device I only get "NotAuthenticated".
I am assuming this is happening because FeathersJS stores the JWT token at window.localStorage and this is not available at the Android app userspace.
Two questions:
1) Is there any way to tell FeathersJS to store this token somewhere else?
2) If not, anyone faced this situation and may provide me a solution?
By the way, this is my code for authenticating:
export class SSHSettingsPage implements OnInit {
public inputEmail: string;
public inputPassword: string;
constructor() { }
ngOnInit() {
}
public performLogin($event) {
let authObj: object = { "strategy": "local", "email": this.inputEmail, "password": this.inputPassword};
client.authenticate(authObj)
.then(res => {
console.log(res);
window.localStorage.setItem("user",JSON.stringify(res.user));
window.location.href = "/download";
})
.catch(err => {
console.log(err);
window.location.href = "/login-error";
})
}
}
As mentioned in the configuration API the storage option can be passed an instance of the React Native AsyncStorage:
import {AsyncStorage} from 'react-native';
// Available options are listed in the "Options" section
app.configure(auth({
storage: AsyncStorage
}))

Can't find variable: Expo

I am making an app with react native. It has login with facebook option, it keeps giving me this error. "Facebook Login Error: Can't find variable: Expo"
What am I doing wrong here?
Do I have to install some dependencies on Linux
f.auth().onAuthStateChanged(function(user) {
if(user){
//logged in
console.log('Logged in', user);
}else {
//logged out
console.log('logged out');
}
});
const { type, token} = await Expo.Facebook.logInWithReadPermissionsAsync(
'APP_ID',
{ permissions: ['email', 'public_profile'] }
);
if(type === 'success'){
const credential = firebase.auth.FacebookAuthProvider.credential(token);
firebase.auth().signInWithCredential(credential).catch((error) => {
console.log('Error...',error);
})
}
Possible Unhandled Promise Rejection (id:0): ReferenceError: Can't find variable: Expo loginWithFacebook$
Assuming you have included Facebook SDK as following
import * as Facebook from 'expo-facebook';
You shouldn't be redundantly calling Expo.Facbook but instead try
const { type, token} = await Facebook.logInWithReadPermissionsAsync...
You have forgot to import Expo
import Expo from 'expo';
But you should use expo-facebook module for facebook login for more information please read document here
https://docs.expo.io/versions/latest/sdk/facebook/

Categories

Resources