I was using tipsi-stripe library but now i migrated it to #stripe/stripe-react-native library but i am unable to create token and get country name from card , please let me know how to implement it ,Thanks in advance.
------------------ Tipsi-stripe Code ----------------
import stripe, { PaymentCardTextField, } from 'tipsi-stripe'
stripe
.paymentRequestWithCardForm()
.then(stripeTokenInfo => {
this.state.loading = true
console.log('Token created', { stripeTokenInfo });
-------------- New Code without Create token ---------------------
import { CardField, useStripe ,confirmPayment, loading} from '#stripe/stripe-react-native';
export default class CheckoutSignin extends Component {
state = {
TotalAmount:null,
clientSecret:null
}
componentDidMount(){
console.log("Total Amount : " + this.props.route.params.TotalAmount);
this.state.TotalAmount = this.props.route.params.TotalAmount;
this.setState(this.state)
}
fetchPaymentIntentClientSecret = async () => {
makePayment(100,"AUD").then(r => {
if(r.Status === "Success"){
this.state.clientSecret = r.ClientSecret;
this.setState(this.state)
// alert("Payment Indent Success");
// console.log("1===> "+ clientSecret);
this.handlePayPress();
// console.log("3===> "+ clientSecret);
}
else {
alert("Payment Indent Failed.");
}
}).catch(e => {
alert(e)
})
};
handlePayPress = async () => {
const {paymentIntent, error} = await confirmPayment(this.state.clientSecret, {
paymentMethodType: 'Card',
paymentMethodData: {
// email: _userInfo.email,
},
});
if (error) {
console.log('Payment confirmation error', error);
Alert.alert("Error","Payment confirmation error", error);
} else if (paymentIntent) {
console.log('Success from promise', paymentIntent);
// Alert.alert("Success","Succeed Payment with 3ds");
this.props.navigation.navigate("Thankyou")
}
}
}
Related
I'm using the react native ble manager package to build a react native app that communicates with a python client over BLE.
When writing to a characteristic on Android (this bug does not seem to appear on IOS) the write is successful but shortly after it I receive this error:
ERROR Error writing eeee2a38-0000-1000-8000-00805f9b34fb status=14
This is the simplified code that handles connecting, notifications and writing on the Android side:
import { NativeModules, NativeEventEmitter, Platform } from 'react-native'
import BleManager, { Peripheral } from 'react-native-ble-manager'
import { END } from 'redux-saga'
import { bytesToString } from 'convert-string'
const UPDATE_SERVICE_UUID = '0000180d-aaaa-1000-8000-00805f9b34fb'
export const Characteristic =
{
WIFI_STATUS_UUID: 'bbbb2a38-0000-1000-8000-00805f9b34fb',
WIFI_CREDS_UUID: 'aaaa2a38-0000-1000-8000-00805f9b34fb',
VERSION_UUID: 'cccc2a38-0000-1000-8000-00805f9b34fb',
UPDATE_STATUS_UUID: 'dddd2a38-0000-1000-8000-00805f9b34fb',
DO_UPDATE_UUID: 'eeee2a38-0000-1000-8000-00805f9b34fb',
ERROR_UUID: 'ffff2a38-0000-1000-8000-00805f9b34fb',
}
class BLEManager {
bleManagerModule: any
bleManagerEmitter: any
scanning: boolean
dispatch: any
stopScanListener: any
peripheralDiscoverListener: any
characteristicUpdateListener: any
onDisconnectListener: any
connectTimeout: any
constructor() {
BleManager.start({ showAlert: false })
this.bleManagerModule = NativeModules.BleManager
this.bleManagerEmitter = new NativeEventEmitter(this.bleManagerModule)
this.scanning = false
}
startScan = (onPeripheralFound: (peripheral: Peripheral | null) => void) => {
if (!this.scanning) {
BleManager.scan([], 3, true)
.then(() => {
console.log('Scanning...')
this.scanning = true
this.peripheralDiscoverListener = this.bleManagerEmitter.addListener(
'BleManagerDiscoverPeripheral',
onPeripheralFound,
)
this.stopScanListener = this.bleManagerEmitter.addListener(
'BleManagerStopScan',
() => {
onPeripheralFound(END)
},
)
return
})
.catch(err => {
console.error(err)
})
} else {
console.log('already scanning')
}
return () => {
console.log('stopped scanning')
this.peripheralDiscoverListener.remove()
this.stopScanListener.remove()
}
}
getBondedDevices = (onGetBondedPeripherals: any) => {
BleManager.getBondedPeripherals().then(bondedPeripheralsArray => {
onGetBondedPeripherals(bondedPeripheralsArray)
// TODO: is the END message here necessary?
onGetBondedPeripherals(END)
return
})
return () => {}
}
connectToPeripheral = async (peripheralID: string) => {
try {
await new Promise(async (resolve, reject) => {
this.connectTimeout = setTimeout(reject, 3000)
console.log('connecting to ' + peripheralID)
try {
await BleManager.connect(peripheralID)
await BleManager.retrieveServices(peripheralID)
} catch (error) {
reject()
}
if (this.connectTimeout) {
clearTimeout(this.connectTimeout)
this.connectTimeout = null
this.onDisconnectListener = this.bleManagerEmitter.addListener(
'BleManagerDisconnectPeripheral',
this.onDisconnectPeripheral,
)
resolve()
}
})
} catch (err) {
clearTimeout(this.connectTimeout)
this.connectTimeout = null
console.error('Could not connect to device.')
throw new Error(err)
}
return
}
watchForCharacteristicsUpdates = async (
updateCharValue: (arg0: { payload: any }) => void,
peripheralID: string,
) => {
try {
await BleManager.startNotification(
peripheralID,
UPDATE_SERVICE_UUID,
Characteristic.ERROR_UUID,
)
await BleManager.startNotification(
peripheralID,
UPDATE_SERVICE_UUID,
Characteristic.VERSION_UUID,
)
await BleManager.startNotification(
peripheralID,
UPDATE_SERVICE_UUID,
Characteristic.UPDATE_STATUS_UUID,
)
} catch (e) {
updateCharValue(new Error(e))
console.error(e)
}
console.log('watch for notifications')
this.characteristicUpdateListener = this.bleManagerEmitter.addListener(
'BleManagerDidUpdateValueForCharacteristic',
({ value, characteristic }) => {
// Convert bytes array to string
const data = bytesToString(value)
console.log(
`Received ${data} (${value}) for characteristic ${characteristic}`,
)
updateCharValue({
payload: {
characteristic: characteristic,
data: data,
},
})
},
)
}
disconnectFromPeripheral = async (peripheralID: string) => {
await BleManager.disconnect(peripheralID)
this.characteristicUpdateListener.remove()
}
onDisconnectPeripheral = (peripheralID: string) => {
console.log(peripheralID + ' disconnected')
this.onDisconnectListener.remove()
}
checkIfConnected = async (peripheralID: string) => {
return await BleManager.isPeripheralConnected(peripheralID, [])
}
triggerUpdateCheck = async (peripheralID: string) => {
return await BleManager.write(
peripheralID,
UPDATE_SERVICE_UUID,
Characteristic.WIFI_STATUS_UUID,
[1],
)
}
runUpdate = async (peripheralID: string) => {
return await BleManager.write(
peripheralID,
UPDATE_SERVICE_UUID,
Characteristic.DO_UPDATE_UUID,
[1],
)
}
}
const bleManager = new BLEManager()
export default bleManager
I've researched this a bit and it seems that some people have the problem but I could not find an explanation or solution to it.
I'm even unsure where to start debugging. Any suggestions are welcome.
Details:
Device: [Pixel 6]
OS: [Android 12]
react-native-ble-manager version: ^8.4.1
react-native version: 0.67.4
Note: I've also asked this question on Github: https://github.com/innoveit/react-native-ble-manager/issues/887
The problem (as mentioned by Martijn) was the bug in Bluez which is fixed in 5.65. Simply upgrading and clearing the Bluetooth cache fixed it.
I'm using the following code to download a file (can be a PDF or a DOC) and then opening it using Linking.
const { dirs } = RNFetchBlob.fs;
let config = {
fileCache : true,
appendExt : extension,
addAndroidDownloads : {
useDownloadManager : false,
notification : false,
title : 'File',
description : 'A file.',
path: `${dirs.DownloadDir}/file.${extension}`,
},
};
RNFetchBlob.config(config)
.fetch(
method,
remoteUrl,
APIHelpers.getDefaultHeaders()
)
.then((res) => {
let status = res.info().status;
if (status == 200) {
Linking.canOpenURL(res.path())
.then((supported) => {
if (!supported) {
alert('Can\'t handle url: ' + res.path());
} else {
Linking.openURL(res.path())
.catch((err) => alert('An error occurred while opening the file. ' + err));
}
})
.catch((err) => alert('The file cannot be opened. ' + err));
} else {
alert('File was not found.')
}
})
.catch((errorMessage, statusCode) => {
alert('There was some error while downloading the file. ' + errorMessage);
});
However, I'm getting the following error:
An error occurred while opening the file. Error: Unable to open URL:
file:///Users/abhishekpokhriyal/Library/Developer/CoreSimulator/Devices/3E2A9C16-0222-40A6-8C1C-EC174B6EE9E8/data/Containers/Data/Application/A37B9D69-583D-4DC8-94B2-0F4AF8272310/Documents/RNFetchBlob_tmp/RNFetchBlobTmp_o259xexg7axbwq3fh6f4.pdf
I need to implement the solution for both iOS and Android.
I think the easiest way to do so is by using react-native-file-viewer package.
It allows you to Prompt the user to choose an app to open the file with (if there are multiple installed apps that support the mimetype).
import FileViewer from 'react-native-file-viewer';
const path = // absolute-path-to-my-local-file.
FileViewer.open(path, { showOpenWithDialog: true })
.then(() => {
// success
})
.catch(error => {
// error
});
So, I finally did this by replacing Linking by the package react-native-file-viewer.
In my APIHelpers.js:
async getRemoteFile(filePath, extension, method = 'GET') {
const remoteUrl = `${API_BASE_URL}/${encodeURIComponent(filePath)}`;
const { dirs } = RNFetchBlob.fs;
let config = {
fileCache : true,
appendExt : extension,
addAndroidDownloads : {
useDownloadManager : false,
notification : false,
title : 'File',
description : 'A file.',
path: `${dirs.DownloadDir}/file.${extension}`,
},
};
return new Promise(async (next, error) => {
try {
let response = await RNFetchBlob.config(config)
.fetch(
method,
remoteUrl,
this.getDefaultHeaders()
);
next(response);
} catch (err) {
error(err);
}
});
}
In my Actions.js
export function openDocument(docPath, ext) {
return async (dispatch) => {
dispatch(fetchingFile());
APIHelpers.getRemoteFile(docPath, ext).then(async function(response) {
dispatch(successFetchingFile());
let status = response.info().status;
if (status == 200) {
const path = response.path();
setTimeout(() => {
FileViewer.open(path, {
showOpenWithDialog: true,
showAppsSuggestions: true,
})
.catch(error => {
dispatch(errorOpeningFile(error));
});
}, 100);
} else {
dispatch(invalidFile());
}
}).catch(function(err) {
dispatch(errorFetchingFile(err));
});
}
}
In my Screen.js
import { openDocument } from 'path/to/Actions';
render() {
return <Button
title={'View file'}
onPress={() => this.props.dispatchOpenDocument(doc.filepath, doc.extension)}
/>;
}
.
.
.
const mapDispatchToProps = {
dispatchOpenDocument: (docPath, ext) => openDocument(docPath, ext),
}
Are you downloading it from the web? I can see the pdf path is attached at the end of the error path.
For web URLs, the protocol ("http://", "https://") must be set accordingly!
Try to append appropriate schemes to your path. Check it out from the link mentioned below.
This can be done with 'rn-fetch-blob'
RNFetchBlob.android.actionViewIntent(fileLocation, mimeType);
I have installed the plugin implemented the code.. Uploaded the signed apk as Internal tester but when I click the purchase button nothing happens.. Can anyone tell me where am I going wrong
import { Component, OnInit } from '#angular/core';
import { NewTransactionPage } from '../instamojo/new_transaction';
import { IonicPage, Platform, NavController, NavParams } from 'ionic-angular';
import { InAppPurchase2, IAPProduct } from '#ionic-native/in-app-purchase-2/ngx';
#IonicPage()
#Component({
selector: 'page-pay',
templateUrl: 'pay.html',
})
export class PayPage {
public product: any = {
name: 'Upgrade to Pro',
appleProductId: 'android.test.purchased',
googleProductId: 'ultimate'
};
constructor(
public navCtrl: NavController,
public navParams: NavParams,
public platform: Platform,
public store: InAppPurchase2
) {
platform.ready().then(() => {
this.configurePurchasing();
});
}
configurePurchasing() {
if (!this.platform.is('cordova')) { return; }
let productId;
try {
if (this.platform.is('ios')) {
productId = this.product.appleProductId;
} else if (this.platform.is('android')) {
productId = this.product.googleProductId;
}
// Register Product
// Set Debug High
this.store.verbosity = this.store.DEBUG;
// Register the product with the store
this.store.register({
id: productId,
alias: productId,
type: this.store.NON_CONSUMABLE
});
this.registerHandlers(productId);
InAppPurchase2.getPlugin().ready().then((status) => {
console.log(JSON.stringify(this.store.get(productId)));
console.log('Store is Ready: ' + JSON.stringify(status));
console.log('Products: ' + JSON.stringify(this.store.products));
});
// Errors On The Specific Product
this.store.when(productId).error( (error) => {
alert('An Error Occured' + JSON.stringify(error));
});
// Refresh Always
console.log('Refresh Store');
this.store.refresh();
} catch (err) {
console.log('Error On Store Issues' + JSON.stringify(err));
}
}
registerHandlers(productId) {
// Handlers
this.store.when(productId).approved( (product: IAPProduct) => {
// Purchase was approved
product.finish();
});
this.store.when(productId).registered( (product: IAPProduct) => {
console.log('Registered: ' + JSON.stringify(product));
});
this.store.when(productId).updated( (product: IAPProduct) => {
console.log('Loaded' + JSON.stringify(product));
});
this.store.when(productId).cancelled( (product) => {
alert('Purchase was Cancelled');
});
// Overall Store Error
this.store.error( (err) => {
alert('Store Error ' + JSON.stringify(err));
});
}
async purchase() {
/* Only configuring purchase when you want to buy, because when you configure a purchase
It prompts the user to input their apple id info on config which is annoying */
if (!this.platform.is('cordova')) { return };
let productId;
if (this.platform.is('ios')) {
productId = this.product.appleProductId;
} else if (this.platform.is('android')) {
productId = this.product.googleProductId;
}
console.log('Products: ' + JSON.stringify(this.store.products));
console.log('Ordering From Store: ' + productId);
try {
let product = this.store.get(productId);
console.log('Product Info: ' + JSON.stringify(product));
let order = this.store.order(productId);
alert('Finished Purchase');
} catch (err) {
console.log('Error Ordering ' + JSON.stringify(err));
}
}
backHomePage() {
this.navCtrl.pop();
}
}
I have tried building the app without --prod but still its not working. I am calling the purchase() function but nothing happens
I have implemented firebase phone authentication mechanism to login user with following
code:
(<any>window).FirebasePlugin.verifyPhoneNumber('+91'+this.phone, 60, function (credential) {
//alert("sms sent successfully"+ credential.verificationId);
//this.verificationId = credential.verificationId;
let modal = this.modalCtrl.create(verificationPage,{verificationId: credential.verificationId});
modal.present();
}, error => {
alert(JSON.stringify(error));
console.log("error: " + error);
});
}
but credential.verificationId value can't able to store or send to another page
verify() {
this.signInCredential = firebase.auth.PhoneAuthProvider.credential(this.verificationId, this.code);
alert("u"+JSON.stringify(this.signInCredential));
firebase.auth().signInWithCredential(this.signInCredential).then((info) => { alert("check"+JSON.stringify(info));}, (error) => {
alert("err"+JSON.stringify(error));})
}
How to resolve above error?
You should get the parameters from the nav params, directly it won't work.
try
constructor(public params: Navparams){
}
verify() {
let verificationId = params.get("verificationId");
this.signInCredential =
firebase.auth.PhoneAuthProvider.credential(verificationId, this.code);
alert("u"+JSON.stringify(this.signInCredential));
firebase.auth().signInWithCredential(this.signInCredential).then((info) =>
{
alert("check"+JSON.stringify(info));}, (error) => {
alert("err"+JSON.stringify(error));
})
}
i hope this will help you.
For your reference check this article
https://medium.com/#gbrigens/ionic-3-phone-authentication-with-firebase-dbed967e95ef
Hi I have implemented the Facebook login in my react native app. I have not used the standard button that comes with sdk. Everything work fine login is successful. But now I don't know how to extract data from Facebook user profile i.e name, email.
Below is my code
_fbAuth() {
LoginManager.logInWithReadPermissions(['public_profile']).then(function (result) {
if (result.isCancelled) {
console.log('Login was Cancelled');
} else {
const { navigate } = this.props.navigation;
//
console.log('Login Successful' + result.grantedPermissions.toString());
}
}, function (error) {
console.log('An error has occured' + error);
})
}
code for button
<TouchableHighlight onPress={() => { this._fbAuth() }}>
<Image source={require('../images/facebook-logo.png')} style={styles.facebook}></Image>
</TouchableHighlight>
You need to use AccessToken function along with the LoginManager to get the token when login is successful. After receiving the token, we can use this token to retrieve data of logged-in user using graph api of facebook.
Consider the code below:
import { LoginManager, AccessToken } from 'react-native-fbsdk';
async _fbAuth() {
let { isCancelled } = await LoginManager.logInWithReadPermissions(['public_profile','user_posts']);
if ( !isCancelled ) {
let data = await AccessToken.getCurrentAccessToken();
let token = data.accessToken.toString();
await afterLoginComplete(token);
}
else {
console.log('Login incomplete');
}
}
const afterLoginComplete = async (token) => {
const response = await fetch(
`https://graph.facebook.com/me?fields=id,name,first_name,last_name,gender,picture,cover&access_token=${token}`);
let result = await response.json();
// use this result as per the requirement
};
You can learn how to use facebook graph API from here
import {AccessToken,LoginManager} from 'react-native-fbsdk';
fbAuth() {
var current = this;
const { navigate } = this.props.navigation;
LoginManager.setLoginBehavior('web');
LoginManager.logInWithReadPermissions(['public_profile','email']).then(
function (result) {
if (result.isCancelled) {
console.log('Login was cancelled');
}
else {
//var accessToken = null;
AccessToken.getCurrentAccessToken().then(
(data) => {
console.log(data.accessToken.toString())
const{accessToken} = data
// with the help of access token you can get details for fb login
console.log('accessToken: ' + accessToken);
fetch('https://graph.facebook.com/v2.5/me?fields=email,name,friends&access_token=' +accessToken)
.then((response) => response.json())
.then((json) => {
console.log('jsonn: ' + json);
console.log('Login name: ' + json.name);
console.log('Login id: ' + json.id);
console.log('Login email: ' + json.email);
var nsn = json.name
console.log('Login email state: ' +nsn);
var idfb = json.id
console.log('Login email state: ' +idfb);
var idemail = json.email
console.log('Login email state: ' +idemail);
})
.catch(() => {
reject('ERROR GETTING DATA FROM FACEBOOK')
})
})
}
},
function (error) {
console.log('Login failed with error: ' + error);
}
);
}